@imgly/plugin-ai-text-generation-web 0.1.8 → 0.1.10
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.
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/version.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/_shims/registry.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/_shims/MultipartBody.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/_shims/web-runtime.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/_shims/index.mjs", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/error.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/internal/decoders/line.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/internal/stream-utils.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/streaming.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/uploads.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/core.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/pagination.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/resource.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/resources/beta/models.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/internal/decoders/jsonl.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/resources/beta/messages/batches.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/_vendor/partial-json-parser/parser.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/lib/BetaMessageStream.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/resources/beta/messages/messages.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/resources/beta/beta.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/resources/completions.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/resources/messages/batches.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/lib/MessageStream.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/resources/messages/messages.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/resources/models.ts", "../../../../node_modules/.pnpm/@anthropic-ai+sdk@0.39.0/node_modules/@anthropic-ai/sdk/src/index.ts", "../../src/anthropic/sendPrompt.ts", "../../src/anthropic/prompts/improve.ts", "../../src/anthropic/prompts/shorter.ts", "../../src/anthropic/prompts/longer.ts", "../../src/anthropic/prompts/fix.ts", "../../src/anthropic/prompts/generateTextForSpeech.ts", "../../src/anthropic/prompts/translate.ts", "../../src/anthropic/prompts/changeTone.ts", "../../src/anthropic/prompts/changeTextTo.ts", "../../src/anthropic/AnthropicProvider.ts", "../../src/anthropic/index.ts"],
|
|
4
|
-
"sourcesContent": ["export const VERSION = '0.39.0'; // x-release-please-version\n", "/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport { type RequestOptions } from \"../core.js\";\n\nexport interface Shims {\n kind: string;\n fetch: any;\n Request: any;\n Response: any;\n Headers: any;\n FormData: any;\n Blob: any;\n File: any;\n ReadableStream: any;\n getMultipartRequestOptions: <T = Record<string, unknown>>(\n form: Shims['FormData'],\n opts: RequestOptions<T>,\n ) => Promise<RequestOptions<T>>;\n getDefaultAgent: (url: string) => any;\n fileFromPath:\n | ((path: string, filename?: string, options?: {}) => Promise<Shims['File']>)\n | ((path: string, options?: {}) => Promise<Shims['File']>);\n isFsReadStream: (value: any) => boolean;\n}\n\nexport let auto = false;\nexport let kind: Shims['kind'] | undefined = undefined;\nexport let fetch: Shims['fetch'] | undefined = undefined;\nexport let Request: Shims['Request'] | undefined = undefined;\nexport let Response: Shims['Response'] | undefined = undefined;\nexport let Headers: Shims['Headers'] | undefined = undefined;\nexport let FormData: Shims['FormData'] | undefined = undefined;\nexport let Blob: Shims['Blob'] | undefined = undefined;\nexport let File: Shims['File'] | undefined = undefined;\nexport let ReadableStream: Shims['ReadableStream'] | undefined = undefined;\nexport let getMultipartRequestOptions: Shims['getMultipartRequestOptions'] | undefined = undefined;\nexport let getDefaultAgent: Shims['getDefaultAgent'] | undefined = undefined;\nexport let fileFromPath: Shims['fileFromPath'] | undefined = undefined;\nexport let isFsReadStream: Shims['isFsReadStream'] | undefined = undefined;\n\nexport function setShims(shims: Shims, options: { auto: boolean } = { auto: false }) {\n if (auto) {\n throw new Error(\n `you must \\`import '@anthropic-ai/sdk/shims/${shims.kind}'\\` before importing anything else from @anthropic-ai/sdk`,\n );\n }\n if (kind) {\n throw new Error(\n `can't \\`import '@anthropic-ai/sdk/shims/${shims.kind}'\\` after \\`import '@anthropic-ai/sdk/shims/${kind}'\\``,\n );\n }\n auto = options.auto;\n kind = shims.kind;\n fetch = shims.fetch;\n Request = shims.Request;\n Response = shims.Response;\n Headers = shims.Headers;\n FormData = shims.FormData;\n Blob = shims.Blob;\n File = shims.File;\n ReadableStream = shims.ReadableStream;\n getMultipartRequestOptions = shims.getMultipartRequestOptions;\n getDefaultAgent = shims.getDefaultAgent;\n fileFromPath = shims.fileFromPath;\n isFsReadStream = shims.isFsReadStream;\n}\n", "/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nexport class MultipartBody {\n constructor(public body: any) {}\n get [Symbol.toStringTag](): string {\n return 'MultipartBody';\n }\n}\n", "/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport { MultipartBody } from \"./MultipartBody.js\";\nimport { type RequestOptions } from \"../core.js\";\nimport { type Shims } from \"./registry.js\";\n\nexport function getRuntime({ manuallyImported }: { manuallyImported?: boolean } = {}): Shims {\n const recommendation =\n manuallyImported ?\n `You may need to use polyfills`\n : `Add one of these imports before your first \\`import \u2026 from '@anthropic-ai/sdk'\\`:\n- \\`import '@anthropic-ai/sdk/shims/node'\\` (if you're running on Node)\n- \\`import '@anthropic-ai/sdk/shims/web'\\` (otherwise)\n`;\n\n let _fetch, _Request, _Response, _Headers;\n try {\n // @ts-ignore\n _fetch = fetch;\n // @ts-ignore\n _Request = Request;\n // @ts-ignore\n _Response = Response;\n // @ts-ignore\n _Headers = Headers;\n } catch (error) {\n throw new Error(\n `this environment is missing the following Web Fetch API type: ${\n (error as any).message\n }. ${recommendation}`,\n );\n }\n\n return {\n kind: 'web',\n fetch: _fetch,\n Request: _Request,\n Response: _Response,\n Headers: _Headers,\n FormData:\n // @ts-ignore\n typeof FormData !== 'undefined' ? FormData : (\n class FormData {\n // @ts-ignore\n constructor() {\n throw new Error(\n `file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`,\n );\n }\n }\n ),\n Blob:\n typeof Blob !== 'undefined' ? Blob : (\n class Blob {\n constructor() {\n throw new Error(\n `file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`,\n );\n }\n }\n ),\n File:\n // @ts-ignore\n typeof File !== 'undefined' ? File : (\n class File {\n // @ts-ignore\n constructor() {\n throw new Error(\n `file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`,\n );\n }\n }\n ),\n ReadableStream:\n // @ts-ignore\n typeof ReadableStream !== 'undefined' ? ReadableStream : (\n class ReadableStream {\n // @ts-ignore\n constructor() {\n throw new Error(\n `streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`,\n );\n }\n }\n ),\n getMultipartRequestOptions: async <T = Record<string, unknown>>(\n // @ts-ignore\n form: FormData,\n opts: RequestOptions<T>,\n ): Promise<RequestOptions<T>> => ({\n ...opts,\n body: new MultipartBody(form) as any,\n }),\n getDefaultAgent: (url: string) => undefined,\n fileFromPath: () => {\n throw new Error(\n 'The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads',\n );\n },\n isFsReadStream: (value: any) => false,\n };\n}\n", "/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport * as shims from './registry.mjs';\nimport * as auto from '@anthropic-ai/sdk/_shims/auto/runtime';\nif (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true });\nexport * from './registry.mjs';\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { castToError, Headers } from \"./core.js\";\n\nexport class AnthropicError extends Error {}\n\nexport class APIError<\n TStatus extends number | undefined = number | undefined,\n THeaders extends Headers | undefined = Headers | undefined,\n TError extends Object | undefined = Object | undefined,\n> extends AnthropicError {\n /** HTTP status for the response that caused the error */\n readonly status: TStatus;\n /** HTTP headers for the response that caused the error */\n readonly headers: THeaders;\n /** JSON body of the response that caused the error */\n readonly error: TError;\n\n readonly request_id: string | null | undefined;\n\n constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) {\n super(`${APIError.makeMessage(status, error, message)}`);\n this.status = status;\n this.headers = headers;\n this.request_id = headers?.['request-id'];\n this.error = error;\n }\n\n private static makeMessage(status: number | undefined, error: any, message: string | undefined) {\n const msg =\n error?.message ?\n typeof error.message === 'string' ?\n error.message\n : JSON.stringify(error.message)\n : error ? JSON.stringify(error)\n : message;\n\n if (status && msg) {\n return `${status} ${msg}`;\n }\n if (status) {\n return `${status} status code (no body)`;\n }\n if (msg) {\n return msg;\n }\n return '(no status code or body)';\n }\n\n static generate(\n status: number | undefined,\n errorResponse: Object | undefined,\n message: string | undefined,\n headers: Headers | undefined,\n ): APIError {\n if (!status || !headers) {\n return new APIConnectionError({ message, cause: castToError(errorResponse) });\n }\n\n const error = errorResponse as Record<string, any>;\n\n if (status === 400) {\n return new BadRequestError(status, error, message, headers);\n }\n\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers);\n }\n\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers);\n }\n\n if (status === 404) {\n return new NotFoundError(status, error, message, headers);\n }\n\n if (status === 409) {\n return new ConflictError(status, error, message, headers);\n }\n\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers);\n }\n\n if (status === 429) {\n return new RateLimitError(status, error, message, headers);\n }\n\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers);\n }\n\n return new APIError(status, error, message, headers);\n }\n}\n\nexport class APIUserAbortError extends APIError<undefined, undefined, undefined> {\n constructor({ message }: { message?: string } = {}) {\n super(undefined, undefined, message || 'Request was aborted.', undefined);\n }\n}\n\nexport class APIConnectionError extends APIError<undefined, undefined, undefined> {\n constructor({ message, cause }: { message?: string | undefined; cause?: Error | undefined }) {\n super(undefined, undefined, message || 'Connection error.', undefined);\n // in some environments the 'cause' property is already declared\n // @ts-ignore\n if (cause) this.cause = cause;\n }\n}\n\nexport class APIConnectionTimeoutError extends APIConnectionError {\n constructor({ message }: { message?: string } = {}) {\n super({ message: message ?? 'Request timed out.' });\n }\n}\n\nexport class BadRequestError extends APIError<400, Headers> {}\n\nexport class AuthenticationError extends APIError<401, Headers> {}\n\nexport class PermissionDeniedError extends APIError<403, Headers> {}\n\nexport class NotFoundError extends APIError<404, Headers> {}\n\nexport class ConflictError extends APIError<409, Headers> {}\n\nexport class UnprocessableEntityError extends APIError<422, Headers> {}\n\nexport class RateLimitError extends APIError<429, Headers> {}\n\nexport class InternalServerError extends APIError<number, Headers> {}\n", "import { AnthropicError } from \"../../error.js\";\n\nexport type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;\n\n/**\n * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally\n * reading lines from text.\n *\n * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258\n */\nexport class LineDecoder {\n // prettier-ignore\n static NEWLINE_CHARS = new Set(['\\n', '\\r']);\n static NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\n\n buffer: Uint8Array;\n #carriageReturnIndex: number | null;\n textDecoder: any; // TextDecoder found in browsers; not typed to avoid pulling in either \"dom\" or \"node\" types.\n\n constructor() {\n this.buffer = new Uint8Array();\n this.#carriageReturnIndex = null;\n }\n\n decode(chunk: Bytes): string[] {\n if (chunk == null) {\n return [];\n }\n\n const binaryChunk =\n chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? new TextEncoder().encode(chunk)\n : chunk;\n\n let newData = new Uint8Array(this.buffer.length + binaryChunk.length);\n newData.set(this.buffer);\n newData.set(binaryChunk, this.buffer.length);\n this.buffer = newData;\n\n const lines: string[] = [];\n let patternIndex;\n while ((patternIndex = findNewlineIndex(this.buffer, this.#carriageReturnIndex)) != null) {\n if (patternIndex.carriage && this.#carriageReturnIndex == null) {\n // skip until we either get a corresponding `\\n`, a new `\\r` or nothing\n this.#carriageReturnIndex = patternIndex.index;\n continue;\n }\n\n // we got double \\r or \\rtext\\n\n if (\n this.#carriageReturnIndex != null &&\n (patternIndex.index !== this.#carriageReturnIndex + 1 || patternIndex.carriage)\n ) {\n lines.push(this.decodeText(this.buffer.slice(0, this.#carriageReturnIndex - 1)));\n this.buffer = this.buffer.slice(this.#carriageReturnIndex);\n this.#carriageReturnIndex = null;\n continue;\n }\n\n const endIndex =\n this.#carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;\n\n const line = this.decodeText(this.buffer.slice(0, endIndex));\n lines.push(line);\n\n this.buffer = this.buffer.slice(patternIndex.index);\n this.#carriageReturnIndex = null;\n }\n\n return lines;\n }\n\n decodeText(bytes: Bytes): string {\n if (bytes == null) return '';\n if (typeof bytes === 'string') return bytes;\n\n // Node:\n if (typeof Buffer !== 'undefined') {\n if (bytes instanceof Buffer) {\n return bytes.toString();\n }\n if (bytes instanceof Uint8Array) {\n return Buffer.from(bytes).toString();\n }\n\n throw new AnthropicError(\n `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global \"Buffer\" defined, which this library assumes to be Node. Please report this error.`,\n );\n }\n\n // Browser\n if (typeof TextDecoder !== 'undefined') {\n if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {\n this.textDecoder ??= new TextDecoder('utf8');\n return this.textDecoder.decode(bytes);\n }\n\n throw new AnthropicError(\n `Unexpected: received non-Uint8Array/ArrayBuffer (${\n (bytes as any).constructor.name\n }) in a web platform. Please report this error.`,\n );\n }\n\n throw new AnthropicError(\n `Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`,\n );\n }\n\n flush(): string[] {\n if (!this.buffer.length) {\n return [];\n }\n return this.decode('\\n');\n }\n}\n\n/**\n * This function searches the buffer for the end patterns, (\\r or \\n)\n * and returns an object with the index preceding the matched newline and the\n * index after the newline char. `null` is returned if no new line is found.\n *\n * ```ts\n * findNewLineIndex('abc\\ndef') -> { preceding: 2, index: 3 }\n * ```\n */\nfunction findNewlineIndex(\n buffer: Uint8Array,\n startIndex: number | null,\n): { preceding: number; index: number; carriage: boolean } | null {\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n\n for (let i = startIndex ?? 0; i < buffer.length; i++) {\n if (buffer[i] === newline) {\n return { preceding: i, index: i + 1, carriage: false };\n }\n\n if (buffer[i] === carriage) {\n return { preceding: i, index: i + 1, carriage: true };\n }\n }\n\n return null;\n}\n\nexport function findDoubleNewlineIndex(buffer: Uint8Array): number {\n // This function searches the buffer for the end patterns (\\r\\r, \\n\\n, \\r\\n\\r\\n)\n // and returns the index right after the first occurrence of any pattern,\n // or -1 if none of the patterns are found.\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n\n for (let i = 0; i < buffer.length - 1; i++) {\n if (buffer[i] === newline && buffer[i + 1] === newline) {\n // \\n\\n\n return i + 2;\n }\n if (buffer[i] === carriage && buffer[i + 1] === carriage) {\n // \\r\\r\n return i + 2;\n }\n if (\n buffer[i] === carriage &&\n buffer[i + 1] === newline &&\n i + 3 < buffer.length &&\n buffer[i + 2] === carriage &&\n buffer[i + 3] === newline\n ) {\n // \\r\\n\\r\\n\n return i + 4;\n }\n }\n\n return -1;\n}\n", "/**\n * Most browsers don't yet have async iterable support for ReadableStream,\n * and Node has a very different way of reading bytes from its \"ReadableStream\".\n *\n * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nexport function ReadableStreamToAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {\n if (stream[Symbol.asyncIterator]) return stream;\n\n const reader = stream.getReader();\n return {\n async next() {\n try {\n const result = await reader.read();\n if (result?.done) reader.releaseLock(); // release lock when stream becomes closed\n return result;\n } catch (e) {\n reader.releaseLock(); // release lock when stream becomes errored\n throw e;\n }\n },\n async return() {\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n return { done: true, value: undefined };\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n", "import { ReadableStream, type Response } from \"./_shims/index.js\";\nimport { AnthropicError } from \"./error.js\";\nimport { findDoubleNewlineIndex, LineDecoder } from \"./internal/decoders/line.js\";\nimport { ReadableStreamToAsyncIterable } from \"./internal/stream-utils.js\";\n\nimport { createResponseHeaders } from \"./core.js\";\nimport { APIError } from \"./error.js\";\n\ntype Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;\n\nexport type ServerSentEvent = {\n event: string | null;\n data: string;\n raw: string[];\n};\n\nexport class Stream<Item> implements AsyncIterable<Item> {\n controller: AbortController;\n\n constructor(\n private iterator: () => AsyncIterator<Item>,\n controller: AbortController,\n ) {\n this.controller = controller;\n }\n\n static fromSSEResponse<Item>(response: Response, controller: AbortController): Stream<Item> {\n let consumed = false;\n\n async function* iterator(): AsyncIterator<Item, any, undefined> {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const sse of _iterSSEMessages(response, controller)) {\n if (sse.event === 'completion') {\n try {\n yield JSON.parse(sse.data);\n } catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n }\n\n if (\n sse.event === 'message_start' ||\n sse.event === 'message_delta' ||\n sse.event === 'message_stop' ||\n sse.event === 'content_block_start' ||\n sse.event === 'content_block_delta' ||\n sse.event === 'content_block_stop'\n ) {\n try {\n yield JSON.parse(sse.data);\n } catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n }\n\n if (sse.event === 'ping') {\n continue;\n }\n\n if (sse.event === 'error') {\n throw APIError.generate(\n undefined,\n `SSE Error: ${sse.data}`,\n sse.data,\n createResponseHeaders(response.headers),\n );\n }\n }\n done = true;\n } catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError') return;\n throw e;\n } finally {\n // If the user `break`s, abort the ongoing request.\n if (!done) controller.abort();\n }\n }\n\n return new Stream(iterator, controller);\n }\n\n /**\n * Generates a Stream from a newline-separated ReadableStream\n * where each item is a JSON value.\n */\n static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController): Stream<Item> {\n let consumed = false;\n\n async function* iterLines(): AsyncGenerator<string, void, unknown> {\n const lineDecoder = new LineDecoder();\n\n const iter = ReadableStreamToAsyncIterable<Bytes>(readableStream);\n for await (const chunk of iter) {\n for (const line of lineDecoder.decode(chunk)) {\n yield line;\n }\n }\n\n for (const line of lineDecoder.flush()) {\n yield line;\n }\n }\n\n async function* iterator(): AsyncIterator<Item, any, undefined> {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const line of iterLines()) {\n if (done) continue;\n if (line) yield JSON.parse(line);\n }\n done = true;\n } catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError') return;\n throw e;\n } finally {\n // If the user `break`s, abort the ongoing request.\n if (!done) controller.abort();\n }\n }\n\n return new Stream(iterator, controller);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Item> {\n return this.iterator();\n }\n\n /**\n * Splits the stream into two streams which can be\n * independently read from at different speeds.\n */\n tee(): [Stream<Item>, Stream<Item>] {\n const left: Array<Promise<IteratorResult<Item>>> = [];\n const right: Array<Promise<IteratorResult<Item>>> = [];\n const iterator = this.iterator();\n\n const teeIterator = (queue: Array<Promise<IteratorResult<Item>>>): AsyncIterator<Item> => {\n return {\n next: () => {\n if (queue.length === 0) {\n const result = iterator.next();\n left.push(result);\n right.push(result);\n }\n return queue.shift()!;\n },\n };\n };\n\n return [\n new Stream(() => teeIterator(left), this.controller),\n new Stream(() => teeIterator(right), this.controller),\n ];\n }\n\n /**\n * Converts this stream to a newline-separated ReadableStream of\n * JSON stringified values in the stream\n * which can be turned back into a Stream with `Stream.fromReadableStream()`.\n */\n toReadableStream(): ReadableStream {\n const self = this;\n let iter: AsyncIterator<Item>;\n const encoder = new TextEncoder();\n\n return new ReadableStream({\n async start() {\n iter = self[Symbol.asyncIterator]();\n },\n async pull(ctrl: any) {\n try {\n const { value, done } = await iter.next();\n if (done) return ctrl.close();\n\n const bytes = encoder.encode(JSON.stringify(value) + '\\n');\n\n ctrl.enqueue(bytes);\n } catch (err) {\n ctrl.error(err);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n }\n}\n\nexport async function* _iterSSEMessages(\n response: Response,\n controller: AbortController,\n): AsyncGenerator<ServerSentEvent, void, unknown> {\n if (!response.body) {\n controller.abort();\n throw new AnthropicError(`Attempted to iterate over a response with no body`);\n }\n\n const sseDecoder = new SSEDecoder();\n const lineDecoder = new LineDecoder();\n\n const iter = ReadableStreamToAsyncIterable<Bytes>(response.body);\n for await (const sseChunk of iterSSEChunks(iter)) {\n for (const line of lineDecoder.decode(sseChunk)) {\n const sse = sseDecoder.decode(line);\n if (sse) yield sse;\n }\n }\n\n for (const line of lineDecoder.flush()) {\n const sse = sseDecoder.decode(line);\n if (sse) yield sse;\n }\n}\n\n/**\n * Given an async iterable iterator, iterates over it and yields full\n * SSE chunks, i.e. yields when a double new-line is encountered.\n */\nasync function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> {\n let data = new Uint8Array();\n\n for await (const chunk of iterator) {\n if (chunk == null) {\n continue;\n }\n\n const binaryChunk =\n chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? new TextEncoder().encode(chunk)\n : chunk;\n\n let newData = new Uint8Array(data.length + binaryChunk.length);\n newData.set(data);\n newData.set(binaryChunk, data.length);\n data = newData;\n\n let patternIndex;\n while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {\n yield data.slice(0, patternIndex);\n data = data.slice(patternIndex);\n }\n }\n\n if (data.length > 0) {\n yield data;\n }\n}\n\nclass SSEDecoder {\n private data: string[];\n private event: string | null;\n private chunks: string[];\n\n constructor() {\n this.event = null;\n this.data = [];\n this.chunks = [];\n }\n\n decode(line: string) {\n if (line.endsWith('\\r')) {\n line = line.substring(0, line.length - 1);\n }\n\n if (!line) {\n // empty line and we didn't previously encounter any messages\n if (!this.event && !this.data.length) return null;\n\n const sse: ServerSentEvent = {\n event: this.event,\n data: this.data.join('\\n'),\n raw: this.chunks,\n };\n\n this.event = null;\n this.data = [];\n this.chunks = [];\n\n return sse;\n }\n\n this.chunks.push(line);\n\n if (line.startsWith(':')) {\n return null;\n }\n\n let [fieldname, _, value] = partition(line, ':');\n\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n\n if (fieldname === 'event') {\n this.event = value;\n } else if (fieldname === 'data') {\n this.data.push(value);\n }\n\n return null;\n }\n}\n\nfunction partition(str: string, delimiter: string): [string, string, string] {\n const index = str.indexOf(delimiter);\n if (index !== -1) {\n return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\n }\n\n return [str, '', ''];\n}\n", "import { type RequestOptions } from \"./core.js\";\nimport {\n FormData,\n File,\n type Blob,\n type FilePropertyBag,\n getMultipartRequestOptions,\n type FsReadStream,\n isFsReadStream,\n} from \"./_shims/index.js\";\nimport { MultipartBody } from \"./_shims/MultipartBody.js\";\nexport { fileFromPath } from \"./_shims/index.js\";\n\ntype BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView;\nexport type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | Uint8Array | DataView;\n\n/**\n * Typically, this is a native \"File\" class.\n *\n * We provide the {@link toFile} utility to convert a variety of objects\n * into the File class.\n *\n * For convenience, you can also pass a fetch Response, or in Node,\n * the result of fs.createReadStream().\n */\nexport type Uploadable = FileLike | ResponseLike | FsReadStream;\n\n/**\n * Intended to match web.Blob, node.Blob, node-fetch.Blob, etc.\n */\nexport interface BlobLike {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */\n readonly size: number;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */\n readonly type: string;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */\n text(): Promise<string>;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */\n slice(start?: number, end?: number): BlobLike;\n // unfortunately @types/node-fetch@^2.6.4 doesn't type the arrayBuffer method\n}\n\n/**\n * Intended to match web.File, node.File, node-fetch.File, etc.\n */\nexport interface FileLike extends BlobLike {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */\n readonly lastModified: number;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */\n readonly name: string;\n}\n\n/**\n * Intended to match web.Response, node.Response, node-fetch.Response, etc.\n */\nexport interface ResponseLike {\n url: string;\n blob(): Promise<BlobLike>;\n}\n\nexport const isResponseLike = (value: any): value is ResponseLike =>\n value != null &&\n typeof value === 'object' &&\n typeof value.url === 'string' &&\n typeof value.blob === 'function';\n\nexport const isFileLike = (value: any): value is FileLike =>\n value != null &&\n typeof value === 'object' &&\n typeof value.name === 'string' &&\n typeof value.lastModified === 'number' &&\n isBlobLike(value);\n\n/**\n * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check\n * adds the arrayBuffer() method type because it is available and used at runtime\n */\nexport const isBlobLike = (value: any): value is BlobLike & { arrayBuffer(): Promise<ArrayBuffer> } =>\n value != null &&\n typeof value === 'object' &&\n typeof value.size === 'number' &&\n typeof value.type === 'string' &&\n typeof value.text === 'function' &&\n typeof value.slice === 'function' &&\n typeof value.arrayBuffer === 'function';\n\nexport const isUploadable = (value: any): value is Uploadable => {\n return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);\n};\n\nexport type ToFileInput = Uploadable | Exclude<BlobLikePart, string> | AsyncIterable<BlobLikePart>;\n\n/**\n * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats\n * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s\n * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible\n * @param {Object=} options additional properties\n * @param {string=} options.type the MIME type of the content\n * @param {number=} options.lastModified the last modified timestamp\n * @returns a {@link File} with the given properties\n */\nexport async function toFile(\n value: ToFileInput | PromiseLike<ToFileInput>,\n name?: string | null | undefined,\n options?: FilePropertyBag | undefined,\n): Promise<FileLike> {\n // If it's a promise, resolve it.\n value = await value;\n\n // If we've been given a `File` we don't need to do anything\n if (isFileLike(value)) {\n return value;\n }\n\n if (isResponseLike(value)) {\n const blob = await value.blob();\n name ||= new URL(value.url).pathname.split(/[\\\\/]/).pop() ?? 'unknown_file';\n\n // we need to convert the `Blob` into an array buffer because the `Blob` class\n // that `node-fetch` defines is incompatible with the web standard which results\n // in `new File` interpreting it as a string instead of binary data.\n const data = isBlobLike(blob) ? [(await blob.arrayBuffer()) as any] : [blob];\n\n return new File(data, name, options);\n }\n\n const bits = await getBytes(value);\n\n name ||= getName(value) ?? 'unknown_file';\n\n if (!options?.type) {\n const type = (bits[0] as any)?.type;\n if (typeof type === 'string') {\n options = { ...options, type };\n }\n }\n\n return new File(bits, name, options);\n}\n\nasync function getBytes(value: ToFileInput): Promise<Array<BlobPart>> {\n let parts: Array<BlobPart> = [];\n if (\n typeof value === 'string' ||\n ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\n value instanceof ArrayBuffer\n ) {\n parts.push(value);\n } else if (isBlobLike(value)) {\n parts.push(await value.arrayBuffer());\n } else if (\n isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc.\n ) {\n for await (const chunk of value) {\n parts.push(chunk as BlobPart); // TODO, consider validating?\n }\n } else {\n throw new Error(\n `Unexpected data type: ${typeof value}; constructor: ${value?.constructor\n ?.name}; props: ${propsForError(value)}`,\n );\n }\n\n return parts;\n}\n\nfunction propsForError(value: any): string {\n const props = Object.getOwnPropertyNames(value);\n return `[${props.map((p) => `\"${p}\"`).join(', ')}]`;\n}\n\nfunction getName(value: any): string | undefined {\n return (\n getStringFromMaybeBuffer(value.name) ||\n getStringFromMaybeBuffer(value.filename) ||\n // For fs.ReadStream\n getStringFromMaybeBuffer(value.path)?.split(/[\\\\/]/).pop()\n );\n}\n\nconst getStringFromMaybeBuffer = (x: string | Buffer | unknown): string | undefined => {\n if (typeof x === 'string') return x;\n if (typeof Buffer !== 'undefined' && x instanceof Buffer) return String(x);\n return undefined;\n};\n\nconst isAsyncIterableIterator = (value: any): value is AsyncIterableIterator<unknown> =>\n value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';\n\nexport const isMultipartBody = (body: any): body is MultipartBody =>\n body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';\n\n/**\n * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.\n * Otherwise returns the request as is.\n */\nexport const maybeMultipartFormRequestOptions = async <T = Record<string, unknown>>(\n opts: RequestOptions<T>,\n): Promise<RequestOptions<T | MultipartBody>> => {\n if (!hasUploadableValue(opts.body)) return opts;\n\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\n\nexport const multipartFormRequestOptions = async <T = Record<string, unknown>>(\n opts: RequestOptions<T>,\n): Promise<RequestOptions<T | MultipartBody>> => {\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\n\nexport const createForm = async <T = Record<string, unknown>>(body: T | undefined): Promise<FormData> => {\n const form = new FormData();\n await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));\n return form;\n};\n\nconst hasUploadableValue = (value: unknown): boolean => {\n if (isUploadable(value)) return true;\n if (Array.isArray(value)) return value.some(hasUploadableValue);\n if (value && typeof value === 'object') {\n for (const k in value) {\n if (hasUploadableValue((value as any)[k])) return true;\n }\n }\n return false;\n};\n\nconst addFormValue = async (form: FormData, key: string, value: unknown): Promise<void> => {\n if (value === undefined) return;\n if (value == null) {\n throw new TypeError(\n `Received null for \"${key}\"; to pass null in FormData, you must use the string 'null'`,\n );\n }\n\n // TODO: make nested formats configurable\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n form.append(key, String(value));\n } else if (isUploadable(value)) {\n const file = await toFile(value);\n form.append(key, file as File);\n } else if (Array.isArray(value)) {\n await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));\n } else if (typeof value === 'object') {\n await Promise.all(\n Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)),\n );\n } else {\n throw new TypeError(\n `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`,\n );\n }\n};\n", "import { VERSION } from \"./version.js\";\nimport { Stream } from \"./streaming.js\";\nimport {\n AnthropicError,\n APIError,\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n} from \"./error.js\";\nimport {\n kind as shimsKind,\n type Readable,\n getDefaultAgent,\n type Agent,\n fetch,\n type RequestInfo,\n type RequestInit,\n type Response,\n type HeadersInit,\n} from \"./_shims/index.js\";\nexport { type Response };\nimport { BlobLike, isBlobLike, isMultipartBody } from \"./uploads.js\";\nexport {\n maybeMultipartFormRequestOptions,\n multipartFormRequestOptions,\n createForm,\n type Uploadable,\n} from \"./uploads.js\";\n\nexport type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\ntype APIResponseProps = {\n response: Response;\n options: FinalRequestOptions;\n controller: AbortController;\n};\n\nasync function defaultParseResponse<T>(props: APIResponseProps): Promise<WithRequestID<T>> {\n const { response } = props;\n if (props.options.stream) {\n debug('response', response.status, response.url, response.headers, response.body);\n\n // Note: there is an invariant here that isn't represented in the type system\n // that if you set `stream: true` the response type must also be `Stream<T>`\n\n if (props.options.__streamClass) {\n return props.options.__streamClass.fromSSEResponse(response, props.controller) as any;\n }\n\n return Stream.fromSSEResponse(response, props.controller) as any;\n }\n\n // fetch refuses to read the body when the status code is 204.\n if (response.status === 204) {\n return null as WithRequestID<T>;\n }\n\n if (props.options.__binaryResponse) {\n return response as unknown as WithRequestID<T>;\n }\n\n const contentType = response.headers.get('content-type');\n const isJSON =\n contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');\n if (isJSON) {\n const json = await response.json();\n\n debug('response', response.status, response.url, response.headers, json);\n\n return _addRequestID(json as T, response);\n }\n\n const text = await response.text();\n debug('response', response.status, response.url, response.headers, text);\n\n // TODO handle blob, arraybuffer, other content types, etc.\n return text as unknown as WithRequestID<T>;\n}\n\ntype WithRequestID<T> =\n T extends Array<any> | Response | AbstractPage<any> ? T\n : T extends Record<string, any> ? T & { _request_id?: string | null }\n : T;\n\nfunction _addRequestID<T>(value: T, response: Response): WithRequestID<T> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value as WithRequestID<T>;\n }\n\n return Object.defineProperty(value, '_request_id', {\n value: response.headers.get('request-id'),\n enumerable: false,\n }) as WithRequestID<T>;\n}\n\n/**\n * A subclass of `Promise` providing additional helper methods\n * for interacting with the SDK.\n */\nexport class APIPromise<T> extends Promise<WithRequestID<T>> {\n private parsedPromise: Promise<WithRequestID<T>> | undefined;\n\n constructor(\n private responsePromise: Promise<APIResponseProps>,\n private parseResponse: (\n props: APIResponseProps,\n ) => PromiseOrValue<WithRequestID<T>> = defaultParseResponse,\n ) {\n super((resolve) => {\n // this is maybe a bit weird but this has to be a no-op to not implicitly\n // parse the response body; instead .then, .catch, .finally are overridden\n // to parse the response\n resolve(null as any);\n });\n }\n\n _thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U> {\n return new APIPromise(this.responsePromise, async (props) =>\n _addRequestID(transform(await this.parseResponse(props), props), props.response),\n );\n }\n\n /**\n * Gets the raw `Response` instance instead of parsing the response\n * data.\n *\n * If you want to parse the response body but still get the `Response`\n * instance, you can use {@link withResponse()}.\n *\n * \uD83D\uDC4B Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n * - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n * - `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n */\n asResponse(): Promise<Response> {\n return this.responsePromise.then((p) => p.response);\n }\n\n /**\n * Gets the parsed response data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * If you just want to get the raw `Response` instance without parsing it,\n * you can use {@link asResponse()}.\n *\n * \uD83D\uDC4B Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n * - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n * - `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n */\n async withResponse(): Promise<{ data: T; response: Response; request_id: string | null | undefined }> {\n const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\n return { data, response, request_id: response.headers.get('request-id') };\n }\n\n private parse(): Promise<WithRequestID<T>> {\n if (!this.parsedPromise) {\n this.parsedPromise = this.responsePromise.then(this.parseResponse) as any as Promise<WithRequestID<T>>;\n }\n return this.parsedPromise;\n }\n\n override then<TResult1 = WithRequestID<T>, TResult2 = never>(\n onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): Promise<TResult1 | TResult2> {\n return this.parse().then(onfulfilled, onrejected);\n }\n\n override catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,\n ): Promise<WithRequestID<T> | TResult> {\n return this.parse().catch(onrejected);\n }\n\n override finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<T>> {\n return this.parse().finally(onfinally);\n }\n}\n\nexport abstract class APIClient {\n baseURL: string;\n maxRetries: number;\n timeout: number;\n httpAgent: Agent | undefined;\n\n private fetch: Fetch;\n protected idempotencyHeader?: string;\n\n constructor({\n baseURL,\n maxRetries = 2,\n timeout = 600000, // 10 minutes\n httpAgent,\n fetch: overriddenFetch,\n }: {\n baseURL: string;\n maxRetries?: number | undefined;\n timeout: number | undefined;\n httpAgent: Agent | undefined;\n fetch: Fetch | undefined;\n }) {\n this.baseURL = baseURL;\n this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);\n this.timeout = validatePositiveInteger('timeout', timeout);\n this.httpAgent = httpAgent;\n\n this.fetch = overriddenFetch ?? fetch;\n }\n\n protected authHeaders(opts: FinalRequestOptions): Headers {\n return {};\n }\n\n /**\n * Override this to add your own default headers, for example:\n *\n * {\n * ...super.defaultHeaders(),\n * Authorization: 'Bearer 123',\n * }\n */\n protected defaultHeaders(opts: FinalRequestOptions): Headers {\n return {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': this.getUserAgent(),\n ...getPlatformHeaders(),\n ...this.authHeaders(opts),\n };\n }\n\n protected abstract defaultQuery(): DefaultQuery | undefined;\n\n /**\n * Override this to add your own headers validation:\n */\n protected validateHeaders(headers: Headers, customHeaders: Headers) {}\n\n protected defaultIdempotencyKey(): string {\n return `stainless-node-retry-${uuid4()}`;\n }\n\n get<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('get', path, opts);\n }\n\n post<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('post', path, opts);\n }\n\n patch<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('patch', path, opts);\n }\n\n put<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('put', path, opts);\n }\n\n delete<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('delete', path, opts);\n }\n\n private methodRequest<Req, Rsp>(\n method: HTTPMethod,\n path: string,\n opts?: PromiseOrValue<RequestOptions<Req>>,\n ): APIPromise<Rsp> {\n return this.request(\n Promise.resolve(opts).then(async (opts) => {\n const body =\n opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer())\n : opts?.body instanceof DataView ? opts.body\n : opts?.body instanceof ArrayBuffer ? new DataView(opts.body)\n : opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)\n : opts?.body;\n return { method, path, ...opts, body };\n }),\n );\n }\n\n getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(\n path: string,\n Page: new (...args: any[]) => PageClass,\n opts?: RequestOptions<any>,\n ): PagePromise<PageClass, Item> {\n return this.requestAPIList(Page, { method: 'get', path, ...opts });\n }\n\n private calculateContentLength(body: unknown): string | null {\n if (typeof body === 'string') {\n if (typeof Buffer !== 'undefined') {\n return Buffer.byteLength(body, 'utf8').toString();\n }\n\n if (typeof TextEncoder !== 'undefined') {\n const encoder = new TextEncoder();\n const encoded = encoder.encode(body);\n return encoded.length.toString();\n }\n } else if (ArrayBuffer.isView(body)) {\n return body.byteLength.toString();\n }\n\n return null;\n }\n\n buildRequest<Req>(\n options: FinalRequestOptions<Req>,\n { retryCount = 0 }: { retryCount?: number } = {},\n ): { req: RequestInit; url: string; timeout: number } {\n options = { ...options };\n const { method, path, query, headers: headers = {} } = options;\n\n const body =\n ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?\n options.body\n : isMultipartBody(options.body) ? options.body.body\n : options.body ? JSON.stringify(options.body, null, 2)\n : null;\n const contentLength = this.calculateContentLength(body);\n\n const url = this.buildURL(path!, query);\n if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);\n options.timeout = options.timeout ?? this.timeout;\n const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);\n const minAgentTimeout = options.timeout + 1000;\n if (\n typeof (httpAgent as any)?.options?.timeout === 'number' &&\n minAgentTimeout > ((httpAgent as any).options.timeout ?? 0)\n ) {\n // Allow any given request to bump our agent active socket timeout.\n // This may seem strange, but leaking active sockets should be rare and not particularly problematic,\n // and without mutating agent we would need to create more of them.\n // This tradeoff optimizes for performance.\n (httpAgent as any).options.timeout = minAgentTimeout;\n }\n\n if (this.idempotencyHeader && method !== 'get') {\n if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();\n headers[this.idempotencyHeader] = options.idempotencyKey;\n }\n\n const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });\n\n const req: RequestInit = {\n method,\n ...(body && { body: body as any }),\n headers: reqHeaders,\n ...(httpAgent && { agent: httpAgent }),\n // @ts-ignore node-fetch uses a custom AbortSignal type that is\n // not compatible with standard web types\n signal: options.signal ?? null,\n };\n\n return { req, url, timeout: options.timeout };\n }\n\n private buildHeaders({\n options,\n headers,\n contentLength,\n retryCount,\n }: {\n options: FinalRequestOptions;\n headers: Record<string, string | null | undefined>;\n contentLength: string | null | undefined;\n retryCount: number;\n }): Record<string, string> {\n const reqHeaders: Record<string, string> = {};\n if (contentLength) {\n reqHeaders['content-length'] = contentLength;\n }\n\n const defaultHeaders = this.defaultHeaders(options);\n applyHeadersMut(reqHeaders, defaultHeaders);\n applyHeadersMut(reqHeaders, headers);\n\n // let builtin fetch set the Content-Type for multipart bodies\n if (isMultipartBody(options.body) && shimsKind !== 'node') {\n delete reqHeaders['content-type'];\n }\n\n // Don't set theses headers if they were already set or removed through default headers or by the caller.\n // We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account\n // for the removal case.\n if (\n getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&\n getHeader(headers, 'x-stainless-retry-count') === undefined\n ) {\n reqHeaders['x-stainless-retry-count'] = String(retryCount);\n }\n if (\n getHeader(defaultHeaders, 'x-stainless-timeout') === undefined &&\n getHeader(headers, 'x-stainless-timeout') === undefined &&\n options.timeout\n ) {\n reqHeaders['x-stainless-timeout'] = String(options.timeout);\n }\n\n this.validateHeaders(reqHeaders, headers);\n\n return reqHeaders;\n }\n\n _calculateNonstreamingTimeout(maxTokens: number): number {\n const defaultTimeout = 10 * 60;\n const expectedTimeout = (60 * 60 * maxTokens) / 128_000;\n if (expectedTimeout > defaultTimeout) {\n throw new AnthropicError(\n 'Streaming is strongly recommended for operations that may take longer than 10 minutes. ' +\n 'See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details',\n );\n }\n return defaultTimeout * 1000;\n }\n\n /**\n * Used as a callback for mutating the given `FinalRequestOptions` object.\n */\n protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}\n\n /**\n * Used as a callback for mutating the given `RequestInit` object.\n *\n * This is useful for cases where you want to add certain headers based off of\n * the request properties, e.g. `method` or `url`.\n */\n protected async prepareRequest(\n request: RequestInit,\n { url, options }: { url: string; options: FinalRequestOptions },\n ): Promise<void> {}\n\n protected parseHeaders(headers: HeadersInit | null | undefined): Record<string, string> {\n return (\n !headers ? {}\n : Symbol.iterator in headers ?\n Object.fromEntries(Array.from(headers as Iterable<string[]>).map((header) => [...header]))\n : { ...headers }\n );\n }\n\n protected makeStatusError(\n status: number | undefined,\n error: Object | undefined,\n message: string | undefined,\n headers: Headers | undefined,\n ): APIError {\n return APIError.generate(status, error, message, headers);\n }\n\n request<Req, Rsp>(\n options: PromiseOrValue<FinalRequestOptions<Req>>,\n remainingRetries: number | null = null,\n ): APIPromise<Rsp> {\n return new APIPromise(this.makeRequest(options, remainingRetries));\n }\n\n private async makeRequest<Req>(\n optionsInput: PromiseOrValue<FinalRequestOptions<Req>>,\n retriesRemaining: number | null,\n ): Promise<APIResponseProps> {\n const options = await optionsInput;\n const maxRetries = options.maxRetries ?? this.maxRetries;\n if (retriesRemaining == null) {\n retriesRemaining = maxRetries;\n }\n\n await this.prepareOptions(options);\n\n const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });\n\n await this.prepareRequest(req, { url, options });\n\n debug('request', url, options, req.headers);\n\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n\n const controller = new AbortController();\n const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);\n\n if (response instanceof Error) {\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n if (retriesRemaining) {\n return this.retryRequest(options, retriesRemaining);\n }\n if (response.name === 'AbortError') {\n throw new APIConnectionTimeoutError();\n }\n throw new APIConnectionError({ cause: response });\n }\n\n const responseHeaders = createResponseHeaders(response.headers);\n\n if (!response.ok) {\n if (retriesRemaining && this.shouldRetry(response)) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);\n return this.retryRequest(options, retriesRemaining, responseHeaders);\n }\n\n const errText = await response.text().catch((e) => castToError(e).message);\n const errJSON = safeJSON(errText);\n const errMessage = errJSON ? undefined : errText;\n const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;\n\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);\n\n const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);\n throw err;\n }\n\n return { response, options, controller };\n }\n\n requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(\n Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,\n options: FinalRequestOptions,\n ): PagePromise<PageClass, Item> {\n const request = this.makeRequest(options, null);\n return new PagePromise<PageClass, Item>(this, request, Page);\n }\n\n buildURL<Req>(path: string, query: Req | null | undefined): string {\n const url =\n isAbsoluteURL(path) ?\n new URL(path)\n : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));\n\n const defaultQuery = this.defaultQuery();\n if (!isEmptyObj(defaultQuery)) {\n query = { ...defaultQuery, ...query } as Req;\n }\n\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query as Record<string, unknown>);\n }\n\n return url.toString();\n }\n\n protected stringifyQuery(query: Record<string, unknown>): string {\n return Object.entries(query)\n .filter(([_, value]) => typeof value !== 'undefined')\n .map(([key, value]) => {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n }\n if (value === null) {\n return `${encodeURIComponent(key)}=`;\n }\n throw new AnthropicError(\n `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.`,\n );\n })\n .join('&');\n }\n\n async fetchWithTimeout(\n url: RequestInfo,\n init: RequestInit | undefined,\n ms: number,\n controller: AbortController,\n ): Promise<Response> {\n const { signal, ...options } = init || {};\n if (signal) signal.addEventListener('abort', () => controller.abort());\n\n const timeout = setTimeout(() => controller.abort(), ms);\n\n const fetchOptions = {\n signal: controller.signal as any,\n ...options,\n };\n if (fetchOptions.method) {\n // Custom methods like 'patch' need to be uppercased\n // See https://github.com/nodejs/undici/issues/2294\n fetchOptions.method = fetchOptions.method.toUpperCase();\n }\n\n // turn on TCP keep-alive for the sockets, if the runtime supports it\n const socketKeepAliveInterval = 60 * 1000;\n const keepAliveTimeout = setTimeout(() => {\n if (fetchOptions && (fetchOptions as any)?.agent?.sockets) {\n for (const socket of Object.values((fetchOptions as any)?.agent?.sockets).flat()) {\n if ((socket as any)?.setKeepAlive) {\n (socket as any).setKeepAlive(true, socketKeepAliveInterval);\n }\n }\n }\n }, socketKeepAliveInterval);\n\n return (\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n this.fetch.call(undefined, url, fetchOptions).finally(() => {\n clearTimeout(timeout);\n clearTimeout(keepAliveTimeout);\n })\n );\n }\n\n private shouldRetry(response: Response): boolean {\n // Note this is not a standard header.\n const shouldRetryHeader = response.headers.get('x-should-retry');\n\n // If the server explicitly says whether or not to retry, obey.\n if (shouldRetryHeader === 'true') return true;\n if (shouldRetryHeader === 'false') return false;\n\n // Retry on request timeouts.\n if (response.status === 408) return true;\n\n // Retry on lock timeouts.\n if (response.status === 409) return true;\n\n // Retry on rate limits.\n if (response.status === 429) return true;\n\n // Retry internal errors.\n if (response.status >= 500) return true;\n\n return false;\n }\n\n private async retryRequest(\n options: FinalRequestOptions,\n retriesRemaining: number,\n responseHeaders?: Headers | undefined,\n ): Promise<APIResponseProps> {\n let timeoutMillis: number | undefined;\n\n // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.\n const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];\n if (retryAfterMillisHeader) {\n const timeoutMs = parseFloat(retryAfterMillisHeader);\n if (!Number.isNaN(timeoutMs)) {\n timeoutMillis = timeoutMs;\n }\n }\n\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfterHeader = responseHeaders?.['retry-after'];\n if (retryAfterHeader && !timeoutMillis) {\n const timeoutSeconds = parseFloat(retryAfterHeader);\n if (!Number.isNaN(timeoutSeconds)) {\n timeoutMillis = timeoutSeconds * 1000;\n } else {\n timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\n }\n }\n\n // If the API asks us to wait a certain amount of time (and it's a reasonable amount),\n // just do what it says, but otherwise calculate a default\n if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\n const maxRetries = options.maxRetries ?? this.maxRetries;\n timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\n }\n await sleep(timeoutMillis);\n\n return this.makeRequest(options, retriesRemaining - 1);\n }\n\n private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {\n const initialRetryDelay = 0.5;\n const maxRetryDelay = 8.0;\n\n const numRetries = maxRetries - retriesRemaining;\n\n // Apply exponential backoff, but not more than the max.\n const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\n\n // Apply some jitter, take up to at most 25 percent of the retry time.\n const jitter = 1 - Math.random() * 0.25;\n\n return sleepSeconds * jitter * 1000;\n }\n\n private getUserAgent(): string {\n return `${this.constructor.name}/JS ${VERSION}`;\n }\n}\n\nexport type PageInfo = { url: URL } | { params: Record<string, unknown> | null };\n\nexport abstract class AbstractPage<Item> implements AsyncIterable<Item> {\n #client: APIClient;\n protected options: FinalRequestOptions;\n\n protected response: Response;\n protected body: unknown;\n\n constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions) {\n this.#client = client;\n this.options = options;\n this.response = response;\n this.body = body;\n }\n\n /**\n * @deprecated Use nextPageInfo instead\n */\n abstract nextPageParams(): Partial<Record<string, unknown>> | null;\n abstract nextPageInfo(): PageInfo | null;\n\n abstract getPaginatedItems(): Item[];\n\n hasNextPage(): boolean {\n const items = this.getPaginatedItems();\n if (!items.length) return false;\n return this.nextPageInfo() != null;\n }\n\n async getNextPage(): Promise<this> {\n const nextInfo = this.nextPageInfo();\n if (!nextInfo) {\n throw new AnthropicError(\n 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',\n );\n }\n const nextOptions = { ...this.options };\n if ('params' in nextInfo && typeof nextOptions.query === 'object') {\n nextOptions.query = { ...nextOptions.query, ...nextInfo.params };\n } else if ('url' in nextInfo) {\n const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];\n for (const [key, value] of params) {\n nextInfo.url.searchParams.set(key, value as any);\n }\n nextOptions.query = undefined;\n nextOptions.path = nextInfo.url.toString();\n }\n return await this.#client.requestAPIList(this.constructor as any, nextOptions);\n }\n\n async *iterPages(): AsyncGenerator<this> {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let page: this = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<Item> {\n for await (const page of this.iterPages()) {\n for (const item of page.getPaginatedItems()) {\n yield item;\n }\n }\n }\n}\n\n/**\n * This subclass of Promise will resolve to an instantiated Page once the request completes.\n *\n * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\nexport class PagePromise<\n PageClass extends AbstractPage<Item>,\n Item = ReturnType<PageClass['getPaginatedItems']>[number],\n >\n extends APIPromise<PageClass>\n implements AsyncIterable<Item>\n{\n constructor(\n client: APIClient,\n request: Promise<APIResponseProps>,\n Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,\n ) {\n super(\n request,\n async (props) =>\n new Page(\n client,\n props.response,\n await defaultParseResponse(props),\n props.options,\n ) as WithRequestID<PageClass>,\n );\n }\n\n /**\n * Allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<Item> {\n const page = await this;\n for await (const item of page) {\n yield item;\n }\n }\n}\n\nexport const createResponseHeaders = (\n headers: Awaited<ReturnType<Fetch>>['headers'],\n): Record<string, string> => {\n return new Proxy(\n Object.fromEntries(\n // @ts-ignore\n headers.entries(),\n ),\n {\n get(target, name) {\n const key = name.toString();\n return target[key.toLowerCase()] || target[key];\n },\n },\n );\n};\n\ntype HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport type RequestClient = { fetch: Fetch };\nexport type Headers = Record<string, string | null | undefined>;\nexport type DefaultQuery = Record<string, string | undefined>;\nexport type KeysEnum<T> = { [P in keyof Required<T>]: true };\n\nexport type RequestOptions<\n Req = unknown | Record<string, unknown> | Readable | BlobLike | ArrayBufferView | ArrayBuffer,\n> = {\n method?: HTTPMethod;\n path?: string;\n query?: Req | undefined;\n body?: Req | null | undefined;\n headers?: Headers | undefined;\n\n maxRetries?: number;\n stream?: boolean | undefined;\n timeout?: number;\n httpAgent?: Agent;\n signal?: AbortSignal | undefined | null;\n idempotencyKey?: string;\n\n __binaryRequest?: boolean | undefined;\n __binaryResponse?: boolean | undefined;\n __streamClass?: typeof Stream;\n};\n\n// This is required so that we can determine if a given object matches the RequestOptions\n// type at runtime. While this requires duplication, it is enforced by the TypeScript\n// compiler such that any missing / extraneous keys will cause an error.\nconst requestOptionsKeys: KeysEnum<RequestOptions> = {\n method: true,\n path: true,\n query: true,\n body: true,\n headers: true,\n\n maxRetries: true,\n stream: true,\n timeout: true,\n httpAgent: true,\n signal: true,\n idempotencyKey: true,\n\n __binaryRequest: true,\n __binaryResponse: true,\n __streamClass: true,\n};\n\nexport const isRequestOptions = (obj: unknown): obj is RequestOptions => {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n !isEmptyObj(obj) &&\n Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))\n );\n};\n\nexport type FinalRequestOptions<Req = unknown | Record<string, unknown> | Readable | DataView> =\n RequestOptions<Req> & {\n method: HTTPMethod;\n path: string;\n };\n\ndeclare const Deno: any;\ndeclare const EdgeRuntime: any;\ntype Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown';\ntype PlatformName =\n | 'MacOS'\n | 'Linux'\n | 'Windows'\n | 'FreeBSD'\n | 'OpenBSD'\n | 'iOS'\n | 'Android'\n | `Other:${string}`\n | 'Unknown';\ntype Browser = 'ie' | 'edge' | 'chrome' | 'firefox' | 'safari';\ntype PlatformProperties = {\n 'X-Stainless-Lang': 'js';\n 'X-Stainless-Package-Version': string;\n 'X-Stainless-OS': PlatformName;\n 'X-Stainless-Arch': Arch;\n 'X-Stainless-Runtime': 'node' | 'deno' | 'edge' | `browser:${Browser}` | 'unknown';\n 'X-Stainless-Runtime-Version': string;\n};\nconst getPlatformProperties = (): PlatformProperties => {\n if (typeof Deno !== 'undefined' && Deno.build != null) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(Deno.build.os),\n 'X-Stainless-Arch': normalizeArch(Deno.build.arch),\n 'X-Stainless-Runtime': 'deno',\n 'X-Stainless-Runtime-Version':\n typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',\n };\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': `other:${EdgeRuntime}`,\n 'X-Stainless-Runtime': 'edge',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n // Check if Node.js\n if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(process.platform),\n 'X-Stainless-Arch': normalizeArch(process.arch),\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n\n const browserInfo = getBrowserInfo();\n if (browserInfo) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,\n 'X-Stainless-Runtime-Version': browserInfo.version,\n };\n }\n\n // TODO add support for Cloudflare workers, etc.\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': 'unknown',\n 'X-Stainless-Runtime-Version': 'unknown',\n };\n};\n\ntype BrowserInfo = {\n browser: Browser;\n version: string;\n};\n\ndeclare const navigator: { userAgent: string } | undefined;\n\n// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts\nfunction getBrowserInfo(): BrowserInfo | null {\n if (typeof navigator === 'undefined' || !navigator) {\n return null;\n }\n\n // NOTE: The order matters here!\n const browserPatterns = [\n { key: 'edge' as const, pattern: /Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie' as const, pattern: /MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie' as const, pattern: /Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'chrome' as const, pattern: /Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'firefox' as const, pattern: /Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'safari' as const, pattern: /(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/ },\n ];\n\n // Find the FIRST matching browser\n for (const { key, pattern } of browserPatterns) {\n const match = pattern.exec(navigator.userAgent);\n if (match) {\n const major = match[1] || 0;\n const minor = match[2] || 0;\n const patch = match[3] || 0;\n\n return { browser: key, version: `${major}.${minor}.${patch}` };\n }\n }\n\n return null;\n}\n\nconst normalizeArch = (arch: string): Arch => {\n // Node docs:\n // - https://nodejs.org/api/process.html#processarch\n // Deno docs:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n if (arch === 'x32') return 'x32';\n if (arch === 'x86_64' || arch === 'x64') return 'x64';\n if (arch === 'arm') return 'arm';\n if (arch === 'aarch64' || arch === 'arm64') return 'arm64';\n if (arch) return `other:${arch}`;\n return 'unknown';\n};\n\nconst normalizePlatform = (platform: string): PlatformName => {\n // Node platforms:\n // - https://nodejs.org/api/process.html#processplatform\n // Deno platforms:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n // - https://github.com/denoland/deno/issues/14799\n\n platform = platform.toLowerCase();\n\n // NOTE: this iOS check is untested and may not work\n // Node does not work natively on IOS, there is a fork at\n // https://github.com/nodejs-mobile/nodejs-mobile\n // however it is unknown at the time of writing how to detect if it is running\n if (platform.includes('ios')) return 'iOS';\n if (platform === 'android') return 'Android';\n if (platform === 'darwin') return 'MacOS';\n if (platform === 'win32') return 'Windows';\n if (platform === 'freebsd') return 'FreeBSD';\n if (platform === 'openbsd') return 'OpenBSD';\n if (platform === 'linux') return 'Linux';\n if (platform) return `Other:${platform}`;\n return 'Unknown';\n};\n\nlet _platformHeaders: PlatformProperties;\nconst getPlatformHeaders = () => {\n return (_platformHeaders ??= getPlatformProperties());\n};\n\nexport const safeJSON = (text: string) => {\n try {\n return JSON.parse(text);\n } catch (err) {\n return undefined;\n }\n};\n\n// https://url.spec.whatwg.org/#url-scheme-string\nconst startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\nconst isAbsoluteURL = (url: string): boolean => {\n return startsWithSchemeRegexp.test(url);\n};\n\nexport const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst validatePositiveInteger = (name: string, n: unknown): number => {\n if (typeof n !== 'number' || !Number.isInteger(n)) {\n throw new AnthropicError(`${name} must be an integer`);\n }\n if (n < 0) {\n throw new AnthropicError(`${name} must be a positive integer`);\n }\n return n;\n};\n\nexport const castToError = (err: any): Error => {\n if (err instanceof Error) return err;\n if (typeof err === 'object' && err !== null) {\n try {\n return new Error(JSON.stringify(err));\n } catch {}\n }\n return new Error(String(err));\n};\n\nexport const ensurePresent = <T>(value: T | null | undefined): T => {\n if (value == null) throw new AnthropicError(`Expected a value to be given but received ${value} instead.`);\n return value;\n};\n\n/**\n * Read an environment variable.\n *\n * Trims beginning and trailing whitespace.\n *\n * Will return undefined if the environment variable doesn't exist or cannot be accessed.\n */\nexport const readEnv = (env: string): string | undefined => {\n if (typeof process !== 'undefined') {\n return process.env?.[env]?.trim() ?? undefined;\n }\n if (typeof Deno !== 'undefined') {\n return Deno.env?.get?.(env)?.trim();\n }\n return undefined;\n};\n\nexport const coerceInteger = (value: unknown): number => {\n if (typeof value === 'number') return Math.round(value);\n if (typeof value === 'string') return parseInt(value, 10);\n\n throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceFloat = (value: unknown): number => {\n if (typeof value === 'number') return value;\n if (typeof value === 'string') return parseFloat(value);\n\n throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceBoolean = (value: unknown): boolean => {\n if (typeof value === 'boolean') return value;\n if (typeof value === 'string') return value === 'true';\n return Boolean(value);\n};\n\nexport const maybeCoerceInteger = (value: unknown): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n return coerceInteger(value);\n};\n\nexport const maybeCoerceFloat = (value: unknown): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n return coerceFloat(value);\n};\n\nexport const maybeCoerceBoolean = (value: unknown): boolean | undefined => {\n if (value === undefined) {\n return undefined;\n }\n return coerceBoolean(value);\n};\n\n// https://stackoverflow.com/a/34491287\nexport function isEmptyObj(obj: Object | null | undefined): boolean {\n if (!obj) return true;\n for (const _k in obj) return false;\n return true;\n}\n\n// https://eslint.org/docs/latest/rules/no-prototype-builtins\nexport function hasOwn(obj: Object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Copies headers from \"newHeaders\" onto \"targetHeaders\",\n * using lower-case for all properties,\n * ignoring any keys with undefined values,\n * and deleting any keys with null values.\n */\nfunction applyHeadersMut(targetHeaders: Headers, newHeaders: Headers): void {\n for (const k in newHeaders) {\n if (!hasOwn(newHeaders, k)) continue;\n const lowerKey = k.toLowerCase();\n if (!lowerKey) continue;\n\n const val = newHeaders[k];\n\n if (val === null) {\n delete targetHeaders[lowerKey];\n } else if (val !== undefined) {\n targetHeaders[lowerKey] = val;\n }\n }\n}\n\nexport function debug(action: string, ...args: any[]) {\n if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {\n console.log(`Anthropic:DEBUG:${action}`, ...args);\n }\n}\n\n/**\n * https://stackoverflow.com/a/2117523\n */\nconst uuid4 = () => {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n\nexport const isRunningInBrowser = () => {\n return (\n // @ts-ignore\n typeof window !== 'undefined' &&\n // @ts-ignore\n typeof window.document !== 'undefined' &&\n // @ts-ignore\n typeof navigator !== 'undefined'\n );\n};\n\nexport interface HeadersProtocol {\n get: (header: string) => string | null | undefined;\n}\nexport type HeadersLike = Record<string, string | string[] | undefined> | HeadersProtocol;\n\nexport const isHeadersProtocol = (headers: any): headers is HeadersProtocol => {\n return typeof headers?.get === 'function';\n};\n\nexport const getRequiredHeader = (headers: HeadersLike | Headers, header: string): string => {\n const foundHeader = getHeader(headers, header);\n if (foundHeader === undefined) {\n throw new Error(`Could not find ${header} header`);\n }\n return foundHeader;\n};\n\nexport const getHeader = (headers: HeadersLike | Headers, header: string): string | undefined => {\n const lowerCasedHeader = header.toLowerCase();\n if (isHeadersProtocol(headers)) {\n // to deal with the case where the header looks like Stainless-Event-Id\n const intercapsHeader =\n header[0]?.toUpperCase() +\n header.substring(1).replace(/([^\\w])(\\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());\n for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {\n const value = headers.get(key);\n if (value) {\n return value;\n }\n }\n }\n\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === lowerCasedHeader) {\n if (Array.isArray(value)) {\n if (value.length <= 1) return value[0];\n console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);\n return value[0];\n }\n return value;\n }\n }\n\n return undefined;\n};\n\n/**\n * Encodes a string to Base64 format.\n */\nexport const toBase64 = (str: string | null | undefined): string => {\n if (!str) return '';\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str).toString('base64');\n }\n\n if (typeof btoa !== 'undefined') {\n return btoa(str);\n }\n\n throw new AnthropicError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');\n};\n\nexport function isObj(obj: unknown): obj is Record<string, unknown> {\n return obj != null && typeof obj === 'object' && !Array.isArray(obj);\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { AbstractPage, Response, APIClient, FinalRequestOptions, PageInfo } from \"./core.js\";\n\nexport interface PageResponse<Item> {\n data: Array<Item>;\n\n has_more: boolean;\n\n first_id: string | null;\n\n last_id: string | null;\n}\n\nexport interface PageParams {\n /**\n * Number of items per page.\n */\n limit?: number;\n\n before_id?: string;\n\n after_id?: string;\n}\n\nexport class Page<Item> extends AbstractPage<Item> implements PageResponse<Item> {\n data: Array<Item>;\n\n has_more: boolean;\n\n first_id: string | null;\n\n last_id: string | null;\n\n constructor(client: APIClient, response: Response, body: PageResponse<Item>, options: FinalRequestOptions) {\n super(client, response, body, options);\n\n this.data = body.data || [];\n this.has_more = body.has_more || false;\n this.first_id = body.first_id || null;\n this.last_id = body.last_id || null;\n }\n\n getPaginatedItems(): Item[] {\n return this.data ?? [];\n }\n\n override hasNextPage(): boolean {\n if (this.has_more === false) {\n return false;\n }\n\n return super.hasNextPage();\n }\n\n // @deprecated Please use `nextPageInfo()` instead\n nextPageParams(): Partial<PageParams> | null {\n const info = this.nextPageInfo();\n if (!info) return null;\n if ('params' in info) return info.params;\n const params = Object.fromEntries(info.url.searchParams);\n if (!Object.keys(params).length) return null;\n return params;\n }\n\n nextPageInfo(): PageInfo | null {\n if ((this.options.query as Record<string, unknown>)?.['before_id']) {\n // in reverse\n const firstId = this.first_id;\n if (!firstId) {\n return null;\n }\n\n return {\n params: {\n before_id: firstId,\n },\n };\n }\n\n const cursor = this.last_id;\n if (!cursor) {\n return null;\n }\n\n return {\n params: {\n after_id: cursor,\n },\n };\n }\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport * as Core from \"./core.js\";\n\nexport class APIResource {\n protected _client: Core.APIClient;\n\n constructor(client: Core.APIClient) {\n this._client = client;\n }\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../resource.js\";\nimport { isRequestOptions } from \"../../core.js\";\nimport * as Core from \"../../core.js\";\nimport { Page, type PageParams } from \"../../pagination.js\";\n\nexport class Models extends APIResource {\n /**\n * Get a specific model.\n *\n * The Models API response can be used to determine information about a specific\n * model or resolve a model alias to a model ID.\n */\n retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo> {\n return this._client.get(`/v1/models/${modelId}?beta=true`, options);\n }\n\n /**\n * List available models.\n *\n * The Models API response can be used to determine which models are available for\n * use in the API. More recently released models are listed first.\n */\n list(\n query?: ModelListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;\n list(options?: Core.RequestOptions): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;\n list(\n query: ModelListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<BetaModelInfosPage, BetaModelInfo> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, { query, ...options });\n }\n}\n\nexport class BetaModelInfosPage extends Page<BetaModelInfo> {}\n\nexport interface BetaModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the model was released.\n * May be set to an epoch value if the release date is unknown.\n */\n created_at: string;\n\n /**\n * A human-readable name for the model.\n */\n display_name: string;\n\n /**\n * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\n}\n\nexport interface ModelListParams extends PageParams {}\n\nModels.BetaModelInfosPage = BetaModelInfosPage;\n\nexport declare namespace Models {\n export {\n type BetaModelInfo as BetaModelInfo,\n BetaModelInfosPage as BetaModelInfosPage,\n type ModelListParams as ModelListParams,\n };\n}\n", "import { AnthropicError } from \"../../error.js\";\nimport { ReadableStreamToAsyncIterable } from \"../stream-utils.js\";\nimport { type Response } from \"../../_shims/index.js\";\nimport { LineDecoder, type Bytes } from \"./line.js\";\n\nexport class JSONLDecoder<T> {\n controller: AbortController;\n\n constructor(\n private iterator: AsyncIterableIterator<Bytes>,\n controller: AbortController,\n ) {\n this.controller = controller;\n }\n\n private async *decoder(): AsyncIterator<T, any, undefined> {\n const lineDecoder = new LineDecoder();\n for await (const chunk of this.iterator) {\n for (const line of lineDecoder.decode(chunk)) {\n yield JSON.parse(line);\n }\n }\n\n for (const line of lineDecoder.flush()) {\n yield JSON.parse(line);\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this.decoder();\n }\n\n static fromResponse<T>(response: Response, controller: AbortController): JSONLDecoder<T> {\n if (!response.body) {\n controller.abort();\n throw new AnthropicError(`Attempted to iterate over a response with no body`);\n }\n\n return new JSONLDecoder(ReadableStreamToAsyncIterable<Bytes>(response.body), controller);\n }\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../../resource.js\";\nimport { isRequestOptions } from \"../../../core.js\";\nimport * as Core from \"../../../core.js\";\nimport * as BetaAPI from \"../beta.js\";\nimport * as BetaMessagesAPI from \"./messages.js\";\nimport { Page, type PageParams } from \"../../../pagination.js\";\nimport { JSONLDecoder } from \"../../../internal/decoders/jsonl.js\";\nimport { AnthropicError } from \"../../../error.js\";\n\nexport class Batches extends APIResource {\n /**\n * Send a batch of Message creation requests.\n *\n * The Message Batches API can be used to process multiple Messages API requests at\n * once. Once a Message Batch is created, it begins processing immediately. Batches\n * can take up to 24 hours to complete.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n create(params: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch> {\n const { betas, ...body } = params;\n return this._client.post('/v1/messages/batches?beta=true', {\n body,\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * This endpoint is idempotent and can be used to poll for Message Batch\n * completion. To access the results of a Message Batch, make a request to the\n * `results_url` field in the response.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n retrieve(\n messageBatchId: string,\n params?: BatchRetrieveParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageBatch>;\n retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;\n retrieve(\n messageBatchId: string,\n params: BatchRetrieveParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageBatch> {\n if (isRequestOptions(params)) {\n return this.retrieve(messageBatchId, {}, params);\n }\n const { betas } = params;\n return this._client.get(`/v1/messages/batches/${messageBatchId}?beta=true`, {\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * List all Message Batches within a Workspace. Most recently created batches are\n * returned first.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n list(\n params?: BatchListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;\n list(options?: Core.RequestOptions): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;\n list(\n params: BatchListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch> {\n if (isRequestOptions(params)) {\n return this.list({}, params);\n }\n const { betas, ...query } = params;\n return this._client.getAPIList('/v1/messages/batches?beta=true', BetaMessageBatchesPage, {\n query,\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * Delete a Message Batch.\n *\n * Message Batches can only be deleted once they've finished processing. If you'd\n * like to delete an in-progress batch, you must first cancel it.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n delete(\n messageBatchId: string,\n params?: BatchDeleteParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaDeletedMessageBatch>;\n delete(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaDeletedMessageBatch>;\n delete(\n messageBatchId: string,\n params: BatchDeleteParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaDeletedMessageBatch> {\n if (isRequestOptions(params)) {\n return this.delete(messageBatchId, {}, params);\n }\n const { betas } = params;\n return this._client.delete(`/v1/messages/batches/${messageBatchId}?beta=true`, {\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * Batches may be canceled any time before processing ends. Once cancellation is\n * initiated, the batch enters a `canceling` state, at which time the system may\n * complete any in-progress, non-interruptible requests before finalizing\n * cancellation.\n *\n * The number of canceled requests is specified in `request_counts`. To determine\n * which requests were canceled, check the individual results within the batch.\n * Note that cancellation may not result in any canceled requests if they were\n * non-interruptible.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n cancel(\n messageBatchId: string,\n params?: BatchCancelParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageBatch>;\n cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;\n cancel(\n messageBatchId: string,\n params: BatchCancelParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageBatch> {\n if (isRequestOptions(params)) {\n return this.cancel(messageBatchId, {}, params);\n }\n const { betas } = params;\n return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel?beta=true`, {\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * Streams the results of a Message Batch as a `.jsonl` file.\n *\n * Each line in the file is a JSON object containing the result of a single request\n * in the Message Batch. Results are not guaranteed to be in the same order as\n * requests. Use the `custom_id` field to match results to requests.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n async results(\n messageBatchId: string,\n params?: BatchResultsParams,\n options?: Core.RequestOptions,\n ): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;\n async results(\n messageBatchId: string,\n options?: Core.RequestOptions,\n ): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;\n async results(\n messageBatchId: string,\n params: BatchResultsParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>> {\n if (isRequestOptions(params)) {\n return this.results(messageBatchId, {}, params);\n }\n\n const batch = await this.retrieve(messageBatchId);\n if (!batch.results_url) {\n throw new AnthropicError(\n `No batch \\`results_url\\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`,\n );\n }\n\n const { betas } = params;\n return this._client\n .get(batch.results_url, {\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n Accept: 'application/binary',\n ...options?.headers,\n },\n __binaryResponse: true,\n })\n ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));\n }\n}\n\nexport class BetaMessageBatchesPage extends Page<BetaMessageBatch> {}\n\nexport interface BetaDeletedMessageBatch {\n /**\n * ID of the Message Batch.\n */\n id: string;\n\n /**\n * Deleted object type.\n *\n * For Message Batches, this is always `\"message_batch_deleted\"`.\n */\n type: 'message_batch_deleted';\n}\n\nexport interface BetaMessageBatch {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * archived and its results became unavailable.\n */\n archived_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which cancellation was\n * initiated for the Message Batch. Specified only if cancellation was initiated.\n */\n cancel_initiated_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * created.\n */\n created_at: string;\n\n /**\n * RFC 3339 datetime string representing the time at which processing for the\n * Message Batch ended. Specified only once processing ends.\n *\n * Processing ends when every request in a Message Batch has either succeeded,\n * errored, canceled, or expired.\n */\n ended_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch will\n * expire and end processing, which is 24 hours after creation.\n */\n expires_at: string;\n\n /**\n * Processing status of the Message Batch.\n */\n processing_status: 'in_progress' | 'canceling' | 'ended';\n\n /**\n * Tallies requests within the Message Batch, categorized by their status.\n *\n * Requests start as `processing` and move to one of the other statuses only once\n * processing of the entire batch ends. The sum of all values always matches the\n * total number of requests in the batch.\n */\n request_counts: BetaMessageBatchRequestCounts;\n\n /**\n * URL to a `.jsonl` file containing the results of the Message Batch requests.\n * Specified only once processing ends.\n *\n * Results in the file are not guaranteed to be in the same order as requests. Use\n * the `custom_id` field to match results to requests.\n */\n results_url: string | null;\n\n /**\n * Object type.\n *\n * For Message Batches, this is always `\"message_batch\"`.\n */\n type: 'message_batch';\n}\n\nexport interface BetaMessageBatchCanceledResult {\n type: 'canceled';\n}\n\nexport interface BetaMessageBatchErroredResult {\n error: BetaAPI.BetaErrorResponse;\n\n type: 'errored';\n}\n\nexport interface BetaMessageBatchExpiredResult {\n type: 'expired';\n}\n\n/**\n * This is a single line in the response `.jsonl` file and does not represent the\n * response as a whole.\n */\nexport interface BetaMessageBatchIndividualResponse {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\n result: BetaMessageBatchResult;\n}\n\nexport interface BetaMessageBatchRequestCounts {\n /**\n * Number of requests in the Message Batch that have been canceled.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n canceled: number;\n\n /**\n * Number of requests in the Message Batch that encountered an error.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n errored: number;\n\n /**\n * Number of requests in the Message Batch that have expired.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n expired: number;\n\n /**\n * Number of requests in the Message Batch that are processing.\n */\n processing: number;\n\n /**\n * Number of requests in the Message Batch that have completed successfully.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n succeeded: number;\n}\n\n/**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\nexport type BetaMessageBatchResult =\n | BetaMessageBatchSucceededResult\n | BetaMessageBatchErroredResult\n | BetaMessageBatchCanceledResult\n | BetaMessageBatchExpiredResult;\n\nexport interface BetaMessageBatchSucceededResult {\n message: BetaMessagesAPI.BetaMessage;\n\n type: 'succeeded';\n}\n\nexport interface BatchCreateParams {\n /**\n * Body param: List of requests for prompt completion. Each is an individual\n * request to create a Message.\n */\n requests: Array<BatchCreateParams.Request>;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport namespace BatchCreateParams {\n export interface Request {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Messages API creation parameters for the individual request.\n *\n * See the [Messages API reference](/en/api/messages) for full documentation on\n * available parameters.\n */\n params: Omit<BetaMessagesAPI.MessageCreateParamsNonStreaming, 'betas'>;\n }\n}\n\nexport interface BatchRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchListParams extends PageParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchDeleteParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchCancelParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchResultsParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nBatches.BetaMessageBatchesPage = BetaMessageBatchesPage;\n\nexport declare namespace Batches {\n export {\n type BetaDeletedMessageBatch as BetaDeletedMessageBatch,\n type BetaMessageBatch as BetaMessageBatch,\n type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult,\n type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult,\n type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult,\n type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse,\n type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts,\n type BetaMessageBatchResult as BetaMessageBatchResult,\n type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult,\n BetaMessageBatchesPage as BetaMessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchRetrieveParams as BatchRetrieveParams,\n type BatchListParams as BatchListParams,\n type BatchDeleteParams as BatchDeleteParams,\n type BatchCancelParams as BatchCancelParams,\n type BatchResultsParams as BatchResultsParams,\n };\n}\n", "type Token = {\n type: string;\n value: string;\n};\n\nconst tokenize = (input: string): Token[] => {\n let current = 0;\n let tokens: Token[] = [];\n\n while (current < input.length) {\n let char = input[current];\n\n if (char === '\\\\') {\n current++;\n continue;\n }\n\n if (char === '{') {\n tokens.push({\n type: 'brace',\n value: '{',\n });\n\n current++;\n continue;\n }\n\n if (char === '}') {\n tokens.push({\n type: 'brace',\n value: '}',\n });\n\n current++;\n continue;\n }\n\n if (char === '[') {\n tokens.push({\n type: 'paren',\n value: '[',\n });\n\n current++;\n continue;\n }\n\n if (char === ']') {\n tokens.push({\n type: 'paren',\n value: ']',\n });\n\n current++;\n continue;\n }\n\n if (char === ':') {\n tokens.push({\n type: 'separator',\n value: ':',\n });\n\n current++;\n continue;\n }\n\n if (char === ',') {\n tokens.push({\n type: 'delimiter',\n value: ',',\n });\n\n current++;\n continue;\n }\n\n if (char === '\"') {\n let value = '';\n let danglingQuote = false;\n\n char = input[++current];\n\n while (char !== '\"') {\n if (current === input.length) {\n danglingQuote = true;\n break;\n }\n\n if (char === '\\\\') {\n current++;\n if (current === input.length) {\n danglingQuote = true;\n break;\n }\n value += char + input[current];\n char = input[++current];\n } else {\n value += char;\n char = input[++current];\n }\n }\n\n char = input[++current];\n\n if (!danglingQuote) {\n tokens.push({\n type: 'string',\n value,\n });\n }\n continue;\n }\n\n let WHITESPACE = /\\s/;\n if (char && WHITESPACE.test(char)) {\n current++;\n continue;\n }\n\n let NUMBERS = /[0-9]/;\n if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {\n let value = '';\n\n if (char === '-') {\n value += char;\n char = input[++current];\n }\n\n while ((char && NUMBERS.test(char)) || char === '.') {\n value += char;\n char = input[++current];\n }\n\n tokens.push({\n type: 'number',\n value,\n });\n continue;\n }\n\n let LETTERS = /[a-z]/i;\n if (char && LETTERS.test(char)) {\n let value = '';\n\n while (char && LETTERS.test(char)) {\n if (current === input.length) {\n break;\n }\n value += char;\n char = input[++current];\n }\n\n if (value == 'true' || value == 'false' || value === 'null') {\n tokens.push({\n type: 'name',\n value,\n });\n } else {\n // unknown token, e.g. `nul` which isn't quite `null`\n current++;\n continue;\n }\n continue;\n }\n\n current++;\n }\n\n return tokens;\n },\n strip = (tokens: Token[]): Token[] => {\n if (tokens.length === 0) {\n return tokens;\n }\n\n let lastToken = tokens[tokens.length - 1]!;\n\n switch (lastToken.type) {\n case 'separator':\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n break;\n case 'number':\n let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];\n if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n }\n case 'string':\n let tokenBeforeTheLastToken = tokens[tokens.length - 2];\n if (tokenBeforeTheLastToken?.type === 'delimiter') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n } else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n }\n break;\n case 'delimiter':\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n break;\n }\n\n return tokens;\n },\n unstrip = (tokens: Token[]): Token[] => {\n let tail: string[] = [];\n\n tokens.map((token) => {\n if (token.type === 'brace') {\n if (token.value === '{') {\n tail.push('}');\n } else {\n tail.splice(tail.lastIndexOf('}'), 1);\n }\n }\n if (token.type === 'paren') {\n if (token.value === '[') {\n tail.push(']');\n } else {\n tail.splice(tail.lastIndexOf(']'), 1);\n }\n }\n });\n\n if (tail.length > 0) {\n tail.reverse().map((item) => {\n if (item === '}') {\n tokens.push({\n type: 'brace',\n value: '}',\n });\n } else if (item === ']') {\n tokens.push({\n type: 'paren',\n value: ']',\n });\n }\n });\n }\n\n return tokens;\n },\n generate = (tokens: Token[]): string => {\n let output = '';\n\n tokens.map((token) => {\n switch (token.type) {\n case 'string':\n output += '\"' + token.value + '\"';\n break;\n default:\n output += token.value;\n break;\n }\n });\n\n return output;\n },\n partialParse = (input: string): unknown => JSON.parse(generate(unstrip(strip(tokenize(input)))));\n\nexport { partialParse };\n", "import * as Core from \"../core.js\";\nimport { AnthropicError, APIUserAbortError } from \"../error.js\";\nimport {\n type BetaContentBlock,\n Messages as BetaMessages,\n type BetaMessage,\n type BetaRawMessageStreamEvent as BetaMessageStreamEvent,\n type BetaMessageParam,\n type MessageCreateParams as BetaMessageCreateParams,\n type MessageCreateParamsBase as BetaMessageCreateParamsBase,\n type BetaTextBlock,\n type BetaTextCitation,\n} from \"../resources/beta/messages/messages.js\";\nimport { type ReadableStream, type Response } from \"../_shims/index.js\";\nimport { Stream } from \"../streaming.js\";\nimport { partialParse } from \"../_vendor/partial-json-parser/parser.js\";\n\nexport interface MessageStreamEvents {\n connect: () => void;\n streamEvent: (event: BetaMessageStreamEvent, snapshot: BetaMessage) => void;\n text: (textDelta: string, textSnapshot: string) => void;\n citation: (citation: BetaTextCitation, citationsSnapshot: BetaTextCitation[]) => void;\n inputJson: (partialJson: string, jsonSnapshot: unknown) => void;\n thinking: (thinkingDelta: string, thinkingSnapshot: string) => void;\n signature: (signature: string) => void;\n message: (message: BetaMessage) => void;\n contentBlock: (content: BetaContentBlock) => void;\n finalMessage: (message: BetaMessage) => void;\n error: (error: AnthropicError) => void;\n abort: (error: APIUserAbortError) => void;\n end: () => void;\n}\n\ntype MessageStreamEventListeners<Event extends keyof MessageStreamEvents> = {\n listener: MessageStreamEvents[Event];\n once?: boolean;\n}[];\n\nconst JSON_BUF_PROPERTY = '__json_buf';\n\nexport class BetaMessageStream implements AsyncIterable<BetaMessageStreamEvent> {\n messages: BetaMessageParam[] = [];\n receivedMessages: BetaMessage[] = [];\n #currentMessageSnapshot: BetaMessage | undefined;\n\n controller: AbortController = new AbortController();\n\n #connectedPromise: Promise<Response | null>;\n #resolveConnectedPromise: (response: Response | null) => void = () => {};\n #rejectConnectedPromise: (error: AnthropicError) => void = () => {};\n\n #endPromise: Promise<void>;\n #resolveEndPromise: () => void = () => {};\n #rejectEndPromise: (error: AnthropicError) => void = () => {};\n\n #listeners: { [Event in keyof MessageStreamEvents]?: MessageStreamEventListeners<Event> } = {};\n\n #ended = false;\n #errored = false;\n #aborted = false;\n #catchingPromiseCreated = false;\n #response: Response | null | undefined;\n #request_id: string | null | undefined;\n\n constructor() {\n this.#connectedPromise = new Promise<Response | null>((resolve, reject) => {\n this.#resolveConnectedPromise = resolve;\n this.#rejectConnectedPromise = reject;\n });\n\n this.#endPromise = new Promise<void>((resolve, reject) => {\n this.#resolveEndPromise = resolve;\n this.#rejectEndPromise = reject;\n });\n\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n this.#connectedPromise.catch(() => {});\n this.#endPromise.catch(() => {});\n }\n\n get response(): Response | null | undefined {\n return this.#response;\n }\n\n get request_id(): string | null | undefined {\n return this.#request_id;\n }\n\n /**\n * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * This is the same as the `APIPromise.withResponse()` method.\n *\n * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`\n * as no `Response` is available.\n */\n async withResponse(): Promise<{\n data: BetaMessageStream;\n response: Response;\n request_id: string | null | undefined;\n }> {\n const response = await this.#connectedPromise;\n if (!response) {\n throw new Error('Could not resolve a `Response` object');\n }\n\n return {\n data: this,\n response,\n request_id: response.headers.get('request-id'),\n };\n }\n\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream: ReadableStream): BetaMessageStream {\n const runner = new BetaMessageStream();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n\n static createMessage(\n messages: BetaMessages,\n params: BetaMessageCreateParamsBase,\n options?: Core.RequestOptions,\n ): BetaMessageStream {\n const runner = new BetaMessageStream();\n for (const message of params.messages) {\n runner._addMessageParam(message);\n }\n runner._run(() =>\n runner._createMessage(\n messages,\n { ...params, stream: true },\n { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } },\n ),\n );\n return runner;\n }\n\n protected _run(executor: () => Promise<any>) {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, this.#handleError);\n }\n\n protected _addMessageParam(message: BetaMessageParam) {\n this.messages.push(message);\n }\n\n protected _addMessage(message: BetaMessage, emit = true) {\n this.receivedMessages.push(message);\n if (emit) {\n this._emit('message', message);\n }\n }\n\n protected async _createMessage(\n messages: BetaMessages,\n params: BetaMessageCreateParams,\n options?: Core.RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n const { response, data: stream } = await messages\n .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })\n .withResponse();\n this._connected(response);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n }\n\n protected _connected(response: Response | null) {\n if (this.ended) return;\n this.#response = response;\n this.#request_id = response?.headers.get('request-id');\n this.#resolveConnectedPromise(response);\n this._emit('connect');\n }\n\n get ended(): boolean {\n return this.#ended;\n }\n\n get errored(): boolean {\n return this.#errored;\n }\n\n get aborted(): boolean {\n return this.#aborted;\n }\n\n abort() {\n this.controller.abort();\n }\n\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this MessageStream, so that calls can be chained\n */\n on<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener });\n return this;\n }\n\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this MessageStream, so that calls can be chained\n */\n off<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners = this.#listeners[event];\n if (!listeners) return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0) listeners.splice(index, 1);\n return this;\n }\n\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this MessageStream, so that calls can be chained\n */\n once<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted<Event extends keyof MessageStreamEvents>(\n event: Event,\n ): Promise<\n Parameters<MessageStreamEvents[Event]> extends [infer Param] ? Param\n : Parameters<MessageStreamEvents[Event]> extends [] ? void\n : Parameters<MessageStreamEvents[Event]>\n > {\n return new Promise((resolve, reject) => {\n this.#catchingPromiseCreated = true;\n if (event !== 'error') this.once('error', reject);\n this.once(event, resolve as any);\n });\n }\n\n async done(): Promise<void> {\n this.#catchingPromiseCreated = true;\n await this.#endPromise;\n }\n\n get currentMessage(): BetaMessage | undefined {\n return this.#currentMessageSnapshot;\n }\n\n #getFinalMessage(): BetaMessage {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n return this.receivedMessages.at(-1)!;\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message response,\n * or rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalMessage(): Promise<BetaMessage> {\n await this.done();\n return this.#getFinalMessage();\n }\n\n #getFinalText(): string {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n const textBlocks = this.receivedMessages\n .at(-1)!\n .content.filter((block): block is BetaTextBlock => block.type === 'text')\n .map((block) => block.text);\n if (textBlocks.length === 0) {\n throw new AnthropicError('stream ended without producing a content block with type=text');\n }\n return textBlocks.join(' ');\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message's text response, concatenated\n * together if there are more than one text blocks.\n * Rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalText(): Promise<string> {\n await this.done();\n return this.#getFinalText();\n }\n\n #handleError = (error: unknown) => {\n this.#errored = true;\n if (error instanceof Error && error.name === 'AbortError') {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n this.#aborted = true;\n return this._emit('abort', error);\n }\n if (error instanceof AnthropicError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const anthropicError: AnthropicError = new AnthropicError(error.message);\n // @ts-ignore\n anthropicError.cause = error;\n return this._emit('error', anthropicError);\n }\n return this._emit('error', new AnthropicError(String(error)));\n };\n\n protected _emit<Event extends keyof MessageStreamEvents>(\n event: Event,\n ...args: Parameters<MessageStreamEvents[Event]>\n ) {\n // make sure we don't emit any MessageStreamEvents after end\n if (this.#ended) return;\n\n if (event === 'end') {\n this.#ended = true;\n this.#resolveEndPromise();\n }\n\n const listeners: MessageStreamEventListeners<Event> | undefined = this.#listeners[event];\n if (listeners) {\n this.#listeners[event] = listeners.filter((l) => !l.once) as any;\n listeners.forEach(({ listener }: any) => listener(...args));\n }\n\n if (event === 'abort') {\n const error = args[0] as APIUserAbortError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n return;\n }\n\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n\n const error = args[0] as AnthropicError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.final...()\n // - etc.\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n }\n }\n\n protected _emitFinal() {\n const finalMessage = this.receivedMessages.at(-1);\n if (finalMessage) {\n this._emit('finalMessage', this.#getFinalMessage());\n }\n }\n\n #beginRequest() {\n if (this.ended) return;\n this.#currentMessageSnapshot = undefined;\n }\n #addStreamEvent(event: BetaMessageStreamEvent) {\n if (this.ended) return;\n const messageSnapshot = this.#accumulateMessage(event);\n this._emit('streamEvent', event, messageSnapshot);\n\n switch (event.type) {\n case 'content_block_delta': {\n const content = messageSnapshot.content.at(-1)!;\n switch (event.delta.type) {\n case 'text_delta': {\n if (content.type === 'text') {\n this._emit('text', event.delta.text, content.text || '');\n }\n break;\n }\n case 'citations_delta': {\n if (content.type === 'text') {\n this._emit('citation', event.delta.citation, content.citations ?? []);\n }\n break;\n }\n case 'input_json_delta': {\n if (content.type === 'tool_use' && content.input) {\n this._emit('inputJson', event.delta.partial_json, content.input);\n }\n break;\n }\n case 'thinking_delta': {\n if (content.type === 'thinking') {\n this._emit('thinking', event.delta.thinking, content.thinking);\n }\n break;\n }\n case 'signature_delta': {\n if (content.type === 'thinking') {\n this._emit('signature', content.signature);\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n break;\n }\n case 'message_stop': {\n this._addMessageParam(messageSnapshot);\n this._addMessage(messageSnapshot, true);\n break;\n }\n case 'content_block_stop': {\n this._emit('contentBlock', messageSnapshot.content.at(-1)!);\n break;\n }\n case 'message_start': {\n this.#currentMessageSnapshot = messageSnapshot;\n break;\n }\n case 'content_block_start':\n case 'message_delta':\n break;\n }\n }\n #endRequest(): BetaMessage {\n if (this.ended) {\n throw new AnthropicError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = this.#currentMessageSnapshot;\n if (!snapshot) {\n throw new AnthropicError(`request ended without sending any chunks`);\n }\n this.#currentMessageSnapshot = undefined;\n return snapshot;\n }\n\n protected async _fromReadableStream(\n readableStream: ReadableStream,\n options?: Core.RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n this._connected(null);\n const stream = Stream.fromReadableStream<BetaMessageStreamEvent>(readableStream, this.controller);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n }\n\n /**\n * Mutates this.#currentMessage with the current event. Handling the accumulation of multiple messages\n * will be needed to be handled by the caller, this method will throw if you try to accumulate for multiple\n * messages.\n */\n #accumulateMessage(event: BetaMessageStreamEvent): BetaMessage {\n let snapshot = this.#currentMessageSnapshot;\n\n if (event.type === 'message_start') {\n if (snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving \"message_stop\"`);\n }\n return event.message;\n }\n\n if (!snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before \"message_start\"`);\n }\n\n switch (event.type) {\n case 'message_stop':\n return snapshot;\n case 'message_delta':\n snapshot.stop_reason = event.delta.stop_reason;\n snapshot.stop_sequence = event.delta.stop_sequence;\n snapshot.usage.output_tokens = event.usage.output_tokens;\n return snapshot;\n case 'content_block_start':\n snapshot.content.push(event.content_block);\n return snapshot;\n case 'content_block_delta': {\n const snapshotContent = snapshot.content.at(event.index);\n\n switch (event.delta.type) {\n case 'text_delta': {\n if (snapshotContent?.type === 'text') {\n snapshotContent.text += event.delta.text;\n }\n break;\n }\n case 'citations_delta': {\n if (snapshotContent?.type === 'text') {\n snapshotContent.citations ??= [];\n snapshotContent.citations.push(event.delta.citation);\n }\n break;\n }\n case 'input_json_delta': {\n if (snapshotContent?.type === 'tool_use') {\n // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = (snapshotContent as any)[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n\n Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n\n if (jsonBuf) {\n snapshotContent.input = partialParse(jsonBuf);\n }\n }\n break;\n }\n case 'thinking_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshotContent.thinking += event.delta.thinking;\n }\n break;\n }\n case 'signature_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshotContent.signature = event.delta.signature;\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n return snapshot;\n }\n case 'content_block_stop':\n return snapshot;\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<BetaMessageStreamEvent> {\n const pushQueue: BetaMessageStreamEvent[] = [];\n const readQueue: {\n resolve: (chunk: BetaMessageStreamEvent | undefined) => void;\n reject: (error: unknown) => void;\n }[] = [];\n let done = false;\n\n this.on('streamEvent', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n } else {\n pushQueue.push(event);\n }\n });\n\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n return {\n next: async (): Promise<IteratorResult<BetaMessageStreamEvent>> => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise<BetaMessageStreamEvent | undefined>((resolve, reject) =>\n readQueue.push({ resolve, reject }),\n ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift()!;\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n\n toReadableStream(): ReadableStream {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\n\n// used to ensure exhaustive case matching without throwing a runtime error\nfunction checkNever(x: never) {}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../../resource.js\";\nimport { APIPromise } from \"../../../core.js\";\nimport * as Core from \"../../../core.js\";\nimport * as MessagesMessagesAPI from \"./messages.js\";\nimport * as BetaAPI from \"../beta.js\";\nimport * as MessagesAPI from \"../../messages/messages.js\";\nimport * as BatchesAPI from \"./batches.js\";\nimport {\n BatchCancelParams,\n BatchCreateParams,\n BatchDeleteParams,\n BatchListParams,\n BatchResultsParams,\n BatchRetrieveParams,\n Batches,\n BetaDeletedMessageBatch,\n BetaMessageBatch,\n BetaMessageBatchCanceledResult,\n BetaMessageBatchErroredResult,\n BetaMessageBatchExpiredResult,\n BetaMessageBatchIndividualResponse,\n BetaMessageBatchRequestCounts,\n BetaMessageBatchResult,\n BetaMessageBatchSucceededResult,\n BetaMessageBatchesPage,\n} from \"./batches.js\";\nimport { Stream } from \"../../../streaming.js\";\nimport { BetaMessageStream } from \"../../../lib/BetaMessageStream.js\";\nimport type { Model } from \"../../messages/messages.js\";\n\nconst DEPRECATED_MODELS: {\n [K in Model]?: string;\n} = {\n 'claude-1.3': 'November 6th, 2024',\n 'claude-1.3-100k': 'November 6th, 2024',\n 'claude-instant-1.1': 'November 6th, 2024',\n 'claude-instant-1.1-100k': 'November 6th, 2024',\n 'claude-instant-1.2': 'November 6th, 2024',\n 'claude-3-sonnet-20240229': 'July 21st, 2025',\n 'claude-2.1': 'July 21st, 2025',\n 'claude-2.0': 'July 21st, 2025',\n};\n\nexport class Messages extends APIResource {\n batches: BatchesAPI.Batches = new BatchesAPI.Batches(this._client);\n\n /**\n * Send a structured list of input messages with text and/or image content, and the\n * model will generate the next message in the conversation.\n *\n * The Messages API can be used for either single queries or stateless multi-turn\n * conversations.\n *\n * Learn more about the Messages API in our [user guide](/en/docs/initial-setup)\n */\n create(params: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<BetaMessage>;\n create(\n params: MessageCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<BetaRawMessageStreamEvent>>;\n create(\n params: MessageCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<BetaRawMessageStreamEvent> | BetaMessage>;\n create(\n params: MessageCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<BetaMessage> | APIPromise<Stream<BetaRawMessageStreamEvent>> {\n const { betas, ...body } = params;\n\n if (body.model in DEPRECATED_MODELS) {\n console.warn(\n `The model '${body.model}' is deprecated and will reach end-of-life on ${\n DEPRECATED_MODELS[body.model]\n }\\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`,\n );\n }\n\n return this._client.post('/v1/messages?beta=true', {\n body,\n timeout:\n (this._client as any)._options.timeout ??\n (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)),\n ...options,\n headers: {\n ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),\n ...options?.headers,\n },\n stream: params.stream ?? false,\n }) as APIPromise<BetaMessage> | APIPromise<Stream<BetaRawMessageStreamEvent>>;\n }\n\n /**\n * Create a Message stream\n */\n stream(body: BetaMessageStreamParams, options?: Core.RequestOptions): BetaMessageStream {\n return BetaMessageStream.createMessage(this, body, options);\n }\n\n /**\n * Count the number of tokens in a Message.\n *\n * The Token Count API can be used to count the number of tokens in a Message,\n * including tools, images, and documents, without creating it.\n *\n * Learn more about token counting in our\n * [user guide](/en/docs/build-with-claude/token-counting)\n */\n countTokens(\n params: MessageCountTokensParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageTokensCount> {\n const { betas, ...body } = params;\n return this._client.post('/v1/messages/count_tokens?beta=true', {\n body,\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString(),\n ...options?.headers,\n },\n });\n }\n}\n\nexport type BetaMessageStreamParams = MessageCreateParamsBase;\n\nexport interface BetaBase64ImageSource {\n data: string;\n\n media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';\n\n type: 'base64';\n}\n\nexport interface BetaBase64PDFBlock {\n source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | BetaURLPDFSource;\n\n type: 'document';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n citations?: BetaCitationsConfigParam;\n\n context?: string | null;\n\n title?: string | null;\n}\n\nexport interface BetaBase64PDFSource {\n data: string;\n\n media_type: 'application/pdf';\n\n type: 'base64';\n}\n\nexport interface BetaCacheControlEphemeral {\n type: 'ephemeral';\n}\n\nexport interface BetaCitationCharLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface BetaCitationCharLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface BetaCitationContentBlockLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface BetaCitationContentBlockLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface BetaCitationPageLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface BetaCitationPageLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface BetaCitationsConfigParam {\n enabled?: boolean;\n}\n\nexport interface BetaCitationsDelta {\n citation: BetaCitationCharLocation | BetaCitationPageLocation | BetaCitationContentBlockLocation;\n\n type: 'citations_delta';\n}\n\nexport type BetaContentBlock =\n | BetaTextBlock\n | BetaToolUseBlock\n | BetaThinkingBlock\n | BetaRedactedThinkingBlock;\n\nexport type BetaContentBlockParam =\n | BetaTextBlockParam\n | BetaImageBlockParam\n | BetaToolUseBlockParam\n | BetaToolResultBlockParam\n | BetaBase64PDFBlock\n | BetaThinkingBlockParam\n | BetaRedactedThinkingBlockParam;\n\nexport interface BetaContentBlockSource {\n content: string | Array<BetaContentBlockSourceContent>;\n\n type: 'content';\n}\n\nexport type BetaContentBlockSourceContent = BetaTextBlockParam | BetaImageBlockParam;\n\nexport interface BetaImageBlockParam {\n source: BetaBase64ImageSource | BetaURLImageSource;\n\n type: 'image';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaInputJSONDelta {\n partial_json: string;\n\n type: 'input_json_delta';\n}\n\nexport interface BetaMessage {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * Content generated by the model.\n *\n * This is an array of content blocks, each of which has a `type` that determines\n * its shape.\n *\n * Example:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"Hi, I'm Claude.\" }]\n * ```\n *\n * If the request input `messages` ended with an `assistant` turn, then the\n * response `content` will continue directly from that last turn. You can use this\n * to constrain the model's output.\n *\n * For example, if the input `messages` were:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Then the response `content` might be:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"B)\" }]\n * ```\n */\n content: Array<BetaContentBlock>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Conversational role of the generated message.\n *\n * This will always be `\"assistant\"`.\n */\n role: 'assistant';\n\n /**\n * The reason that we stopped.\n *\n * This may be one the following values:\n *\n * - `\"end_turn\"`: the model reached a natural stopping point\n * - `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n * - `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n * - `\"tool_use\"`: the model invoked one or more tools\n *\n * In non-streaming mode this value is always non-null. In streaming mode, it is\n * null in the `message_start` event and non-null otherwise.\n */\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;\n\n /**\n * Which custom stop sequence was generated, if any.\n *\n * This value will be a non-null string if one of your custom stop sequences was\n * generated.\n */\n stop_sequence: string | null;\n\n /**\n * Object type.\n *\n * For Messages, this is always `\"message\"`.\n */\n type: 'message';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: BetaUsage;\n}\n\nexport interface BetaMessageDeltaUsage {\n /**\n * The cumulative number of output tokens which were used.\n */\n output_tokens: number;\n}\n\nexport interface BetaMessageParam {\n content: string | Array<BetaContentBlockParam>;\n\n role: 'user' | 'assistant';\n}\n\nexport interface BetaMessageTokensCount {\n /**\n * The total number of tokens across the provided list of messages, system prompt,\n * and tools.\n */\n input_tokens: number;\n}\n\nexport interface BetaMetadata {\n /**\n * An external identifier for the user who is associated with the request.\n *\n * This should be a uuid, hash value, or other opaque identifier. Anthropic may use\n * this id to help detect abuse. Do not include any identifying information such as\n * name, email address, or phone number.\n */\n user_id?: string | null;\n}\n\nexport interface BetaPlainTextSource {\n data: string;\n\n media_type: 'text/plain';\n\n type: 'text';\n}\n\nexport interface BetaRawContentBlockDeltaEvent {\n delta: BetaTextDelta | BetaInputJSONDelta | BetaCitationsDelta | BetaThinkingDelta | BetaSignatureDelta;\n\n index: number;\n\n type: 'content_block_delta';\n}\n\nexport interface BetaRawContentBlockStartEvent {\n content_block: BetaTextBlock | BetaToolUseBlock | BetaThinkingBlock | BetaRedactedThinkingBlock;\n\n index: number;\n\n type: 'content_block_start';\n}\n\nexport interface BetaRawContentBlockStopEvent {\n index: number;\n\n type: 'content_block_stop';\n}\n\nexport interface BetaRawMessageDeltaEvent {\n delta: BetaRawMessageDeltaEvent.Delta;\n\n type: 'message_delta';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: BetaMessageDeltaUsage;\n}\n\nexport namespace BetaRawMessageDeltaEvent {\n export interface Delta {\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;\n\n stop_sequence: string | null;\n }\n}\n\nexport interface BetaRawMessageStartEvent {\n message: BetaMessage;\n\n type: 'message_start';\n}\n\nexport interface BetaRawMessageStopEvent {\n type: 'message_stop';\n}\n\nexport type BetaRawMessageStreamEvent =\n | BetaRawMessageStartEvent\n | BetaRawMessageDeltaEvent\n | BetaRawMessageStopEvent\n | BetaRawContentBlockStartEvent\n | BetaRawContentBlockDeltaEvent\n | BetaRawContentBlockStopEvent;\n\nexport interface BetaRedactedThinkingBlock {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface BetaRedactedThinkingBlockParam {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface BetaSignatureDelta {\n signature: string;\n\n type: 'signature_delta';\n}\n\nexport interface BetaTextBlock {\n /**\n * Citations supporting the text block.\n *\n * The type of citation returned will depend on the type of document being cited.\n * Citing a PDF results in `page_location`, plain text results in `char_location`,\n * and content document results in `content_block_location`.\n */\n citations: Array<BetaTextCitation> | null;\n\n text: string;\n\n type: 'text';\n}\n\nexport interface BetaTextBlockParam {\n text: string;\n\n type: 'text';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n citations?: Array<BetaTextCitationParam> | null;\n}\n\nexport type BetaTextCitation =\n | BetaCitationCharLocation\n | BetaCitationPageLocation\n | BetaCitationContentBlockLocation;\n\nexport type BetaTextCitationParam =\n | BetaCitationCharLocationParam\n | BetaCitationPageLocationParam\n | BetaCitationContentBlockLocationParam;\n\nexport interface BetaTextDelta {\n text: string;\n\n type: 'text_delta';\n}\n\nexport interface BetaThinkingBlock {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface BetaThinkingBlockParam {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface BetaThinkingConfigDisabled {\n type: 'disabled';\n}\n\nexport interface BetaThinkingConfigEnabled {\n /**\n * Determines how many tokens Claude can use for its internal reasoning process.\n * Larger budgets can enable more thorough analysis for complex problems, improving\n * response quality.\n *\n * Must be \u22651024 and less than `max_tokens`.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n budget_tokens: number;\n\n type: 'enabled';\n}\n\n/**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\nexport type BetaThinkingConfigParam = BetaThinkingConfigEnabled | BetaThinkingConfigDisabled;\n\nexport interface BetaThinkingDelta {\n thinking: string;\n\n type: 'thinking_delta';\n}\n\nexport interface BetaTool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n input_schema: BetaTool.InputSchema;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: string;\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Description of what this tool does.\n *\n * Tool descriptions should be as detailed as possible. The more information that\n * the model has about what the tool is and how to use it, the better it will\n * perform. You can use natural language descriptions to reinforce important\n * aspects of the tool input JSON schema.\n */\n description?: string;\n\n type?: 'custom' | null;\n}\n\nexport namespace BetaTool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n export interface InputSchema {\n type: 'object';\n\n properties?: unknown | null;\n [k: string]: unknown;\n }\n}\n\nexport interface BetaToolBash20241022 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'bash';\n\n type: 'bash_20241022';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaToolBash20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'bash';\n\n type: 'bash_20250124';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\n/**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\nexport type BetaToolChoice = BetaToolChoiceAuto | BetaToolChoiceAny | BetaToolChoiceTool | BetaToolChoiceNone;\n\n/**\n * The model will use any available tools.\n */\nexport interface BetaToolChoiceAny {\n type: 'any';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will automatically decide whether to use tools.\n */\nexport interface BetaToolChoiceAuto {\n type: 'auto';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output at most one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will not be allowed to use tools.\n */\nexport interface BetaToolChoiceNone {\n type: 'none';\n}\n\n/**\n * The model will use the specified tool with `tool_choice.name`.\n */\nexport interface BetaToolChoiceTool {\n /**\n * The name of the tool to use.\n */\n name: string;\n\n type: 'tool';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\nexport interface BetaToolComputerUse20241022 {\n /**\n * The height of the display in pixels.\n */\n display_height_px: number;\n\n /**\n * The width of the display in pixels.\n */\n display_width_px: number;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'computer';\n\n type: 'computer_20241022';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * The X11 display number (e.g. 0, 1) for the display.\n */\n display_number?: number | null;\n}\n\nexport interface BetaToolComputerUse20250124 {\n /**\n * The height of the display in pixels.\n */\n display_height_px: number;\n\n /**\n * The width of the display in pixels.\n */\n display_width_px: number;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'computer';\n\n type: 'computer_20250124';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * The X11 display number (e.g. 0, 1) for the display.\n */\n display_number?: number | null;\n}\n\nexport interface BetaToolResultBlockParam {\n tool_use_id: string;\n\n type: 'tool_result';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n content?: string | Array<BetaTextBlockParam | BetaImageBlockParam>;\n\n is_error?: boolean;\n}\n\nexport interface BetaToolTextEditor20241022 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'str_replace_editor';\n\n type: 'text_editor_20241022';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaToolTextEditor20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'str_replace_editor';\n\n type: 'text_editor_20250124';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport type BetaToolUnion =\n | BetaTool\n | BetaToolComputerUse20241022\n | BetaToolBash20241022\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20250124\n | BetaToolBash20250124\n | BetaToolTextEditor20250124;\n\nexport interface BetaToolUseBlock {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n}\n\nexport interface BetaToolUseBlockParam {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaURLImageSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface BetaURLPDFSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface BetaUsage {\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number | null;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number | null;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n}\n\nexport type MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming;\n\nexport interface MessageCreateParamsBase {\n /**\n * Body param: The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n *\n * Different models have different maximum values for this parameter. See\n * [models](https://docs.anthropic.com/en/docs/models-overview) for details.\n */\n max_tokens: number;\n\n /**\n * Body param: Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * Starting with Claude 3 models, you can also send image content blocks:\n *\n * ```json\n * {\n * \"role\": \"user\",\n * \"content\": [\n * {\n * \"type\": \"image\",\n * \"source\": {\n * \"type\": \"base64\",\n * \"media_type\": \"image/jpeg\",\n * \"data\": \"/9j/4AAQSkZJRg...\"\n * }\n * },\n * { \"type\": \"text\", \"text\": \"What is in this image?\" }\n * ]\n * }\n * ```\n *\n * We currently support the `base64` source type for images, and the `image/jpeg`,\n * `image/png`, `image/gif`, and `image/webp` media types.\n *\n * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for\n * more input examples.\n *\n * Note that if you want to include a\n * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use\n * the top-level `system` parameter \u2014 there is no `\"system\"` role for input\n * messages in the Messages API.\n */\n messages: Array<BetaMessageParam>;\n\n /**\n * Body param: The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Body param: An object describing metadata about the request.\n */\n metadata?: BetaMetadata;\n\n /**\n * Body param: Custom text sequences that will cause the model to stop generating.\n *\n * Our models will normally stop when they have naturally completed their turn,\n * which will result in a response `stop_reason` of `\"end_turn\"`.\n *\n * If you want the model to stop generating when it encounters custom strings of\n * text, you can use the `stop_sequences` parameter. If the model encounters one of\n * the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"`\n * and the response `stop_sequence` value will contain the matched stop sequence.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream?: boolean;\n\n /**\n * Body param: System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).\n */\n system?: string | Array<BetaTextBlockParam>;\n\n /**\n * Body param: Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\n */\n temperature?: number;\n\n /**\n * Body param: Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: BetaThinkingConfigParam;\n\n /**\n * Body param: How the model should use the provided tools. The model can use a\n * specific tool, any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: BetaToolChoice;\n\n /**\n * Body param: Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.\n */\n tools?: Array<BetaToolUnion>;\n\n /**\n * Body param: Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Body param: Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_p?: number;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport namespace MessageCreateParams {\n export type MessageCreateParamsNonStreaming = MessagesMessagesAPI.MessageCreateParamsNonStreaming;\n export type MessageCreateParamsStreaming = MessagesMessagesAPI.MessageCreateParamsStreaming;\n}\n\nexport interface MessageCreateParamsNonStreaming extends MessageCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream?: false;\n}\n\nexport interface MessageCreateParamsStreaming extends MessageCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream: true;\n}\n\nexport interface MessageCountTokensParams {\n /**\n * Body param: Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * Starting with Claude 3 models, you can also send image content blocks:\n *\n * ```json\n * {\n * \"role\": \"user\",\n * \"content\": [\n * {\n * \"type\": \"image\",\n * \"source\": {\n * \"type\": \"base64\",\n * \"media_type\": \"image/jpeg\",\n * \"data\": \"/9j/4AAQSkZJRg...\"\n * }\n * },\n * { \"type\": \"text\", \"text\": \"What is in this image?\" }\n * ]\n * }\n * ```\n *\n * We currently support the `base64` source type for images, and the `image/jpeg`,\n * `image/png`, `image/gif`, and `image/webp` media types.\n *\n * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for\n * more input examples.\n *\n * Note that if you want to include a\n * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use\n * the top-level `system` parameter \u2014 there is no `\"system\"` role for input\n * messages in the Messages API.\n */\n messages: Array<BetaMessageParam>;\n\n /**\n * Body param: The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Body param: System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).\n */\n system?: string | Array<BetaTextBlockParam>;\n\n /**\n * Body param: Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: BetaThinkingConfigParam;\n\n /**\n * Body param: How the model should use the provided tools. The model can use a\n * specific tool, any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: BetaToolChoice;\n\n /**\n * Body param: Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.\n */\n tools?: Array<\n | BetaTool\n | BetaToolComputerUse20241022\n | BetaToolBash20241022\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20250124\n | BetaToolBash20250124\n | BetaToolTextEditor20250124\n >;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nMessages.Batches = Batches;\nMessages.BetaMessageBatchesPage = BetaMessageBatchesPage;\n\nexport declare namespace Messages {\n export {\n type BetaBase64ImageSource as BetaBase64ImageSource,\n type BetaBase64PDFBlock as BetaBase64PDFBlock,\n type BetaBase64PDFSource as BetaBase64PDFSource,\n type BetaCacheControlEphemeral as BetaCacheControlEphemeral,\n type BetaCitationCharLocation as BetaCitationCharLocation,\n type BetaCitationCharLocationParam as BetaCitationCharLocationParam,\n type BetaCitationContentBlockLocation as BetaCitationContentBlockLocation,\n type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,\n type BetaCitationPageLocation as BetaCitationPageLocation,\n type BetaCitationPageLocationParam as BetaCitationPageLocationParam,\n type BetaCitationsConfigParam as BetaCitationsConfigParam,\n type BetaCitationsDelta as BetaCitationsDelta,\n type BetaContentBlock as BetaContentBlock,\n type BetaContentBlockParam as BetaContentBlockParam,\n type BetaContentBlockSource as BetaContentBlockSource,\n type BetaContentBlockSourceContent as BetaContentBlockSourceContent,\n type BetaImageBlockParam as BetaImageBlockParam,\n type BetaInputJSONDelta as BetaInputJSONDelta,\n type BetaMessage as BetaMessage,\n type BetaMessageDeltaUsage as BetaMessageDeltaUsage,\n type BetaMessageParam as BetaMessageParam,\n type BetaMessageTokensCount as BetaMessageTokensCount,\n type BetaMetadata as BetaMetadata,\n type BetaPlainTextSource as BetaPlainTextSource,\n type BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent,\n type BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent,\n type BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent,\n type BetaRawMessageDeltaEvent as BetaRawMessageDeltaEvent,\n type BetaRawMessageStartEvent as BetaRawMessageStartEvent,\n type BetaRawMessageStopEvent as BetaRawMessageStopEvent,\n type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,\n type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,\n type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,\n type BetaSignatureDelta as BetaSignatureDelta,\n type BetaTextBlock as BetaTextBlock,\n type BetaTextBlockParam as BetaTextBlockParam,\n type BetaTextCitation as BetaTextCitation,\n type BetaTextCitationParam as BetaTextCitationParam,\n type BetaTextDelta as BetaTextDelta,\n type BetaThinkingBlock as BetaThinkingBlock,\n type BetaThinkingBlockParam as BetaThinkingBlockParam,\n type BetaThinkingConfigDisabled as BetaThinkingConfigDisabled,\n type BetaThinkingConfigEnabled as BetaThinkingConfigEnabled,\n type BetaThinkingConfigParam as BetaThinkingConfigParam,\n type BetaThinkingDelta as BetaThinkingDelta,\n type BetaTool as BetaTool,\n type BetaToolBash20241022 as BetaToolBash20241022,\n type BetaToolBash20250124 as BetaToolBash20250124,\n type BetaToolChoice as BetaToolChoice,\n type BetaToolChoiceAny as BetaToolChoiceAny,\n type BetaToolChoiceAuto as BetaToolChoiceAuto,\n type BetaToolChoiceNone as BetaToolChoiceNone,\n type BetaToolChoiceTool as BetaToolChoiceTool,\n type BetaToolComputerUse20241022 as BetaToolComputerUse20241022,\n type BetaToolComputerUse20250124 as BetaToolComputerUse20250124,\n type BetaToolResultBlockParam as BetaToolResultBlockParam,\n type BetaToolTextEditor20241022 as BetaToolTextEditor20241022,\n type BetaToolTextEditor20250124 as BetaToolTextEditor20250124,\n type BetaToolUnion as BetaToolUnion,\n type BetaToolUseBlock as BetaToolUseBlock,\n type BetaToolUseBlockParam as BetaToolUseBlockParam,\n type BetaURLImageSource as BetaURLImageSource,\n type BetaURLPDFSource as BetaURLPDFSource,\n type BetaUsage as BetaUsage,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export {\n Batches as Batches,\n type BetaDeletedMessageBatch as BetaDeletedMessageBatch,\n type BetaMessageBatch as BetaMessageBatch,\n type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult,\n type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult,\n type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult,\n type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse,\n type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts,\n type BetaMessageBatchResult as BetaMessageBatchResult,\n type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult,\n BetaMessageBatchesPage as BetaMessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchRetrieveParams as BatchRetrieveParams,\n type BatchListParams as BatchListParams,\n type BatchDeleteParams as BatchDeleteParams,\n type BatchCancelParams as BatchCancelParams,\n type BatchResultsParams as BatchResultsParams,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../resource.js\";\nimport * as ModelsAPI from \"./models.js\";\nimport { BetaModelInfo, BetaModelInfosPage, ModelListParams, Models } from \"./models.js\";\nimport * as MessagesAPI from \"./messages/messages.js\";\nimport {\n BetaBase64ImageSource,\n BetaBase64PDFBlock,\n BetaBase64PDFSource,\n BetaCacheControlEphemeral,\n BetaCitationCharLocation,\n BetaCitationCharLocationParam,\n BetaCitationContentBlockLocation,\n BetaCitationContentBlockLocationParam,\n BetaCitationPageLocation,\n BetaCitationPageLocationParam,\n BetaCitationsConfigParam,\n BetaCitationsDelta,\n BetaContentBlock,\n BetaContentBlockParam,\n BetaContentBlockSource,\n BetaContentBlockSourceContent,\n BetaImageBlockParam,\n BetaInputJSONDelta,\n BetaMessage,\n BetaMessageDeltaUsage,\n BetaMessageParam,\n BetaMessageTokensCount,\n BetaMetadata,\n BetaPlainTextSource,\n BetaRawContentBlockDeltaEvent,\n BetaRawContentBlockStartEvent,\n BetaRawContentBlockStopEvent,\n BetaRawMessageDeltaEvent,\n BetaRawMessageStartEvent,\n BetaRawMessageStopEvent,\n BetaRawMessageStreamEvent,\n BetaRedactedThinkingBlock,\n BetaRedactedThinkingBlockParam,\n BetaSignatureDelta,\n BetaTextBlock,\n BetaTextBlockParam,\n BetaTextCitation,\n BetaTextCitationParam,\n BetaTextDelta,\n BetaThinkingBlock,\n BetaThinkingBlockParam,\n BetaThinkingConfigDisabled,\n BetaThinkingConfigEnabled,\n BetaThinkingConfigParam,\n BetaThinkingDelta,\n BetaTool,\n BetaToolBash20241022,\n BetaToolBash20250124,\n BetaToolChoice,\n BetaToolChoiceAny,\n BetaToolChoiceAuto,\n BetaToolChoiceNone,\n BetaToolChoiceTool,\n BetaToolComputerUse20241022,\n BetaToolComputerUse20250124,\n BetaToolResultBlockParam,\n BetaToolTextEditor20241022,\n BetaToolTextEditor20250124,\n BetaToolUnion,\n BetaToolUseBlock,\n BetaToolUseBlockParam,\n BetaURLImageSource,\n BetaURLPDFSource,\n BetaUsage,\n MessageCountTokensParams,\n MessageCreateParams,\n MessageCreateParamsNonStreaming,\n MessageCreateParamsStreaming,\n Messages,\n} from \"./messages/messages.js\";\n\nexport class Beta extends APIResource {\n models: ModelsAPI.Models = new ModelsAPI.Models(this._client);\n messages: MessagesAPI.Messages = new MessagesAPI.Messages(this._client);\n}\n\nexport type AnthropicBeta =\n | (string & {})\n | 'message-batches-2024-09-24'\n | 'prompt-caching-2024-07-31'\n | 'computer-use-2024-10-22'\n | 'computer-use-2025-01-24'\n | 'pdfs-2024-09-25'\n | 'token-counting-2024-11-01'\n | 'token-efficient-tools-2025-02-19'\n | 'output-128k-2025-02-19';\n\nexport interface BetaAPIError {\n message: string;\n\n type: 'api_error';\n}\n\nexport interface BetaAuthenticationError {\n message: string;\n\n type: 'authentication_error';\n}\n\nexport interface BetaBillingError {\n message: string;\n\n type: 'billing_error';\n}\n\nexport type BetaError =\n | BetaInvalidRequestError\n | BetaAuthenticationError\n | BetaBillingError\n | BetaPermissionError\n | BetaNotFoundError\n | BetaRateLimitError\n | BetaGatewayTimeoutError\n | BetaAPIError\n | BetaOverloadedError;\n\nexport interface BetaErrorResponse {\n error: BetaError;\n\n type: 'error';\n}\n\nexport interface BetaGatewayTimeoutError {\n message: string;\n\n type: 'timeout_error';\n}\n\nexport interface BetaInvalidRequestError {\n message: string;\n\n type: 'invalid_request_error';\n}\n\nexport interface BetaNotFoundError {\n message: string;\n\n type: 'not_found_error';\n}\n\nexport interface BetaOverloadedError {\n message: string;\n\n type: 'overloaded_error';\n}\n\nexport interface BetaPermissionError {\n message: string;\n\n type: 'permission_error';\n}\n\nexport interface BetaRateLimitError {\n message: string;\n\n type: 'rate_limit_error';\n}\n\nBeta.Models = Models;\nBeta.BetaModelInfosPage = BetaModelInfosPage;\nBeta.Messages = Messages;\n\nexport declare namespace Beta {\n export {\n type AnthropicBeta as AnthropicBeta,\n type BetaAPIError as BetaAPIError,\n type BetaAuthenticationError as BetaAuthenticationError,\n type BetaBillingError as BetaBillingError,\n type BetaError as BetaError,\n type BetaErrorResponse as BetaErrorResponse,\n type BetaGatewayTimeoutError as BetaGatewayTimeoutError,\n type BetaInvalidRequestError as BetaInvalidRequestError,\n type BetaNotFoundError as BetaNotFoundError,\n type BetaOverloadedError as BetaOverloadedError,\n type BetaPermissionError as BetaPermissionError,\n type BetaRateLimitError as BetaRateLimitError,\n };\n\n export {\n Models as Models,\n type BetaModelInfo as BetaModelInfo,\n BetaModelInfosPage as BetaModelInfosPage,\n type ModelListParams as ModelListParams,\n };\n\n export {\n Messages as Messages,\n type BetaBase64ImageSource as BetaBase64ImageSource,\n type BetaBase64PDFBlock as BetaBase64PDFBlock,\n type BetaBase64PDFSource as BetaBase64PDFSource,\n type BetaCacheControlEphemeral as BetaCacheControlEphemeral,\n type BetaCitationCharLocation as BetaCitationCharLocation,\n type BetaCitationCharLocationParam as BetaCitationCharLocationParam,\n type BetaCitationContentBlockLocation as BetaCitationContentBlockLocation,\n type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,\n type BetaCitationPageLocation as BetaCitationPageLocation,\n type BetaCitationPageLocationParam as BetaCitationPageLocationParam,\n type BetaCitationsConfigParam as BetaCitationsConfigParam,\n type BetaCitationsDelta as BetaCitationsDelta,\n type BetaContentBlock as BetaContentBlock,\n type BetaContentBlockParam as BetaContentBlockParam,\n type BetaContentBlockSource as BetaContentBlockSource,\n type BetaContentBlockSourceContent as BetaContentBlockSourceContent,\n type BetaImageBlockParam as BetaImageBlockParam,\n type BetaInputJSONDelta as BetaInputJSONDelta,\n type BetaMessage as BetaMessage,\n type BetaMessageDeltaUsage as BetaMessageDeltaUsage,\n type BetaMessageParam as BetaMessageParam,\n type BetaMessageTokensCount as BetaMessageTokensCount,\n type BetaMetadata as BetaMetadata,\n type BetaPlainTextSource as BetaPlainTextSource,\n type BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent,\n type BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent,\n type BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent,\n type BetaRawMessageDeltaEvent as BetaRawMessageDeltaEvent,\n type BetaRawMessageStartEvent as BetaRawMessageStartEvent,\n type BetaRawMessageStopEvent as BetaRawMessageStopEvent,\n type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,\n type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,\n type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,\n type BetaSignatureDelta as BetaSignatureDelta,\n type BetaTextBlock as BetaTextBlock,\n type BetaTextBlockParam as BetaTextBlockParam,\n type BetaTextCitation as BetaTextCitation,\n type BetaTextCitationParam as BetaTextCitationParam,\n type BetaTextDelta as BetaTextDelta,\n type BetaThinkingBlock as BetaThinkingBlock,\n type BetaThinkingBlockParam as BetaThinkingBlockParam,\n type BetaThinkingConfigDisabled as BetaThinkingConfigDisabled,\n type BetaThinkingConfigEnabled as BetaThinkingConfigEnabled,\n type BetaThinkingConfigParam as BetaThinkingConfigParam,\n type BetaThinkingDelta as BetaThinkingDelta,\n type BetaTool as BetaTool,\n type BetaToolBash20241022 as BetaToolBash20241022,\n type BetaToolBash20250124 as BetaToolBash20250124,\n type BetaToolChoice as BetaToolChoice,\n type BetaToolChoiceAny as BetaToolChoiceAny,\n type BetaToolChoiceAuto as BetaToolChoiceAuto,\n type BetaToolChoiceNone as BetaToolChoiceNone,\n type BetaToolChoiceTool as BetaToolChoiceTool,\n type BetaToolComputerUse20241022 as BetaToolComputerUse20241022,\n type BetaToolComputerUse20250124 as BetaToolComputerUse20250124,\n type BetaToolResultBlockParam as BetaToolResultBlockParam,\n type BetaToolTextEditor20241022 as BetaToolTextEditor20241022,\n type BetaToolTextEditor20250124 as BetaToolTextEditor20250124,\n type BetaToolUnion as BetaToolUnion,\n type BetaToolUseBlock as BetaToolUseBlock,\n type BetaToolUseBlockParam as BetaToolUseBlockParam,\n type BetaURLImageSource as BetaURLImageSource,\n type BetaURLPDFSource as BetaURLPDFSource,\n type BetaUsage as BetaUsage,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../resource.js\";\nimport { APIPromise } from \"../core.js\";\nimport * as Core from \"../core.js\";\nimport * as CompletionsAPI from \"./completions.js\";\nimport * as MessagesAPI from \"./messages/messages.js\";\nimport { Stream } from \"../streaming.js\";\n\nexport class Completions extends APIResource {\n /**\n * [Legacy] Create a Text Completion.\n *\n * The Text Completions API is a legacy API. We recommend using the\n * [Messages API](https://docs.anthropic.com/en/api/messages) going forward.\n *\n * Future models and features will not be compatible with Text Completions. See our\n * [migration guide](https://docs.anthropic.com/en/api/migrating-from-text-completions-to-messages)\n * for guidance in migrating from Text Completions to Messages.\n */\n create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;\n create(\n body: CompletionCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<Completion>>;\n create(\n body: CompletionCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<Completion> | Completion>;\n create(\n body: CompletionCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<Completion> | APIPromise<Stream<Completion>> {\n return this._client.post('/v1/complete', {\n body,\n timeout: (this._client as any)._options.timeout ?? 600000,\n ...options,\n stream: body.stream ?? false,\n }) as APIPromise<Completion> | APIPromise<Stream<Completion>>;\n }\n}\n\nexport interface Completion {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * The resulting completion up to and excluding the stop sequences.\n */\n completion: string;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * The reason that we stopped.\n *\n * This may be one the following values:\n *\n * - `\"stop_sequence\"`: we reached a stop sequence \u2014 either provided by you via the\n * `stop_sequences` parameter, or a stop sequence built into the model\n * - `\"max_tokens\"`: we exceeded `max_tokens_to_sample` or the model's maximum\n */\n stop_reason: string | null;\n\n /**\n * Object type.\n *\n * For Text Completions, this is always `\"completion\"`.\n */\n type: 'completion';\n}\n\nexport type CompletionCreateParams = CompletionCreateParamsNonStreaming | CompletionCreateParamsStreaming;\n\nexport interface CompletionCreateParamsBase {\n /**\n * The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n */\n max_tokens_to_sample: number;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * The prompt that you want Claude to complete.\n *\n * For proper response generation you will need to format your prompt using\n * alternating `\\n\\nHuman:` and `\\n\\nAssistant:` conversational turns. For example:\n *\n * ```\n * \"\\n\\nHuman: {userQuestion}\\n\\nAssistant:\"\n * ```\n *\n * See [prompt validation](https://docs.anthropic.com/en/api/prompt-validation) and\n * our guide to\n * [prompt design](https://docs.anthropic.com/en/docs/intro-to-prompting) for more\n * details.\n */\n prompt: string;\n\n /**\n * An object describing metadata about the request.\n */\n metadata?: MessagesAPI.Metadata;\n\n /**\n * Sequences that will cause the model to stop generating.\n *\n * Our models stop on `\"\\n\\nHuman:\"`, and may include additional built-in stop\n * sequences in the future. By providing the stop_sequences parameter, you may\n * include additional strings that will cause the model to stop generating.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/streaming) for details.\n */\n stream?: boolean;\n\n /**\n * Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\n */\n temperature?: number;\n\n /**\n * Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_p?: number;\n}\n\nexport namespace CompletionCreateParams {\n /**\n * @deprecated use `Anthropic.Messages.Metadata` instead\n */\n export type Metadata = MessagesAPI.Metadata;\n\n export type CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming;\n export type CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming;\n}\n\nexport interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase {\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/streaming) for details.\n */\n stream?: false;\n}\n\nexport interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase {\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/streaming) for details.\n */\n stream: true;\n}\n\nexport declare namespace Completions {\n export {\n type Completion as Completion,\n type CompletionCreateParams as CompletionCreateParams,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../resource.js\";\nimport { isRequestOptions } from \"../../core.js\";\nimport * as Core from \"../../core.js\";\nimport * as Shared from \"../shared.js\";\nimport * as MessagesAPI from \"./messages.js\";\nimport { Page, type PageParams } from \"../../pagination.js\";\nimport { JSONLDecoder } from \"../../internal/decoders/jsonl.js\";\nimport { AnthropicError } from \"../../error.js\";\n\nexport class Batches extends APIResource {\n /**\n * Send a batch of Message creation requests.\n *\n * The Message Batches API can be used to process multiple Messages API requests at\n * once. Once a Message Batch is created, it begins processing immediately. Batches\n * can take up to 24 hours to complete.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {\n return this._client.post('/v1/messages/batches', { body, ...options });\n }\n\n /**\n * This endpoint is idempotent and can be used to poll for Message Batch\n * completion. To access the results of a Message Batch, make a request to the\n * `results_url` field in the response.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {\n return this._client.get(`/v1/messages/batches/${messageBatchId}`, options);\n }\n\n /**\n * List all Message Batches within a Workspace. Most recently created batches are\n * returned first.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n list(\n query?: BatchListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<MessageBatchesPage, MessageBatch>;\n list(options?: Core.RequestOptions): Core.PagePromise<MessageBatchesPage, MessageBatch>;\n list(\n query: BatchListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<MessageBatchesPage, MessageBatch> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/v1/messages/batches', MessageBatchesPage, { query, ...options });\n }\n\n /**\n * Delete a Message Batch.\n *\n * Message Batches can only be deleted once they've finished processing. If you'd\n * like to delete an in-progress batch, you must first cancel it.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n delete(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<DeletedMessageBatch> {\n return this._client.delete(`/v1/messages/batches/${messageBatchId}`, options);\n }\n\n /**\n * Batches may be canceled any time before processing ends. Once cancellation is\n * initiated, the batch enters a `canceling` state, at which time the system may\n * complete any in-progress, non-interruptible requests before finalizing\n * cancellation.\n *\n * The number of canceled requests is specified in `request_counts`. To determine\n * which requests were canceled, check the individual results within the batch.\n * Note that cancellation may not result in any canceled requests if they were\n * non-interruptible.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {\n return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel`, options);\n }\n\n /**\n * Streams the results of a Message Batch as a `.jsonl` file.\n *\n * Each line in the file is a JSON object containing the result of a single request\n * in the Message Batch. Results are not guaranteed to be in the same order as\n * requests. Use the `custom_id` field to match results to requests.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n async results(\n messageBatchId: string,\n options?: Core.RequestOptions,\n ): Promise<JSONLDecoder<MessageBatchIndividualResponse>> {\n const batch = await this.retrieve(messageBatchId);\n if (!batch.results_url) {\n throw new AnthropicError(\n `No batch \\`results_url\\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`,\n );\n }\n\n return this._client\n .get(batch.results_url, {\n ...options,\n headers: {\n Accept: 'application/binary',\n ...options?.headers,\n },\n __binaryResponse: true,\n })\n ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));\n }\n}\n\nexport class MessageBatchesPage extends Page<MessageBatch> {}\n\nexport interface DeletedMessageBatch {\n /**\n * ID of the Message Batch.\n */\n id: string;\n\n /**\n * Deleted object type.\n *\n * For Message Batches, this is always `\"message_batch_deleted\"`.\n */\n type: 'message_batch_deleted';\n}\n\nexport interface MessageBatch {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * archived and its results became unavailable.\n */\n archived_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which cancellation was\n * initiated for the Message Batch. Specified only if cancellation was initiated.\n */\n cancel_initiated_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * created.\n */\n created_at: string;\n\n /**\n * RFC 3339 datetime string representing the time at which processing for the\n * Message Batch ended. Specified only once processing ends.\n *\n * Processing ends when every request in a Message Batch has either succeeded,\n * errored, canceled, or expired.\n */\n ended_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch will\n * expire and end processing, which is 24 hours after creation.\n */\n expires_at: string;\n\n /**\n * Processing status of the Message Batch.\n */\n processing_status: 'in_progress' | 'canceling' | 'ended';\n\n /**\n * Tallies requests within the Message Batch, categorized by their status.\n *\n * Requests start as `processing` and move to one of the other statuses only once\n * processing of the entire batch ends. The sum of all values always matches the\n * total number of requests in the batch.\n */\n request_counts: MessageBatchRequestCounts;\n\n /**\n * URL to a `.jsonl` file containing the results of the Message Batch requests.\n * Specified only once processing ends.\n *\n * Results in the file are not guaranteed to be in the same order as requests. Use\n * the `custom_id` field to match results to requests.\n */\n results_url: string | null;\n\n /**\n * Object type.\n *\n * For Message Batches, this is always `\"message_batch\"`.\n */\n type: 'message_batch';\n}\n\nexport interface MessageBatchCanceledResult {\n type: 'canceled';\n}\n\nexport interface MessageBatchErroredResult {\n error: Shared.ErrorResponse;\n\n type: 'errored';\n}\n\nexport interface MessageBatchExpiredResult {\n type: 'expired';\n}\n\n/**\n * This is a single line in the response `.jsonl` file and does not represent the\n * response as a whole.\n */\nexport interface MessageBatchIndividualResponse {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\n result: MessageBatchResult;\n}\n\nexport interface MessageBatchRequestCounts {\n /**\n * Number of requests in the Message Batch that have been canceled.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n canceled: number;\n\n /**\n * Number of requests in the Message Batch that encountered an error.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n errored: number;\n\n /**\n * Number of requests in the Message Batch that have expired.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n expired: number;\n\n /**\n * Number of requests in the Message Batch that are processing.\n */\n processing: number;\n\n /**\n * Number of requests in the Message Batch that have completed successfully.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n succeeded: number;\n}\n\n/**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\nexport type MessageBatchResult =\n | MessageBatchSucceededResult\n | MessageBatchErroredResult\n | MessageBatchCanceledResult\n | MessageBatchExpiredResult;\n\nexport interface MessageBatchSucceededResult {\n message: MessagesAPI.Message;\n\n type: 'succeeded';\n}\n\nexport interface BatchCreateParams {\n /**\n * List of requests for prompt completion. Each is an individual request to create\n * a Message.\n */\n requests: Array<BatchCreateParams.Request>;\n}\n\nexport namespace BatchCreateParams {\n export interface Request {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Messages API creation parameters for the individual request.\n *\n * See the [Messages API reference](/en/api/messages) for full documentation on\n * available parameters.\n */\n params: MessagesAPI.MessageCreateParamsNonStreaming;\n }\n}\n\nexport interface BatchListParams extends PageParams {}\n\nBatches.MessageBatchesPage = MessageBatchesPage;\n\nexport declare namespace Batches {\n export {\n type DeletedMessageBatch as DeletedMessageBatch,\n type MessageBatch as MessageBatch,\n type MessageBatchCanceledResult as MessageBatchCanceledResult,\n type MessageBatchErroredResult as MessageBatchErroredResult,\n type MessageBatchExpiredResult as MessageBatchExpiredResult,\n type MessageBatchIndividualResponse as MessageBatchIndividualResponse,\n type MessageBatchRequestCounts as MessageBatchRequestCounts,\n type MessageBatchResult as MessageBatchResult,\n type MessageBatchSucceededResult as MessageBatchSucceededResult,\n MessageBatchesPage as MessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchListParams as BatchListParams,\n };\n}\n", "import * as Core from \"../core.js\";\nimport { AnthropicError, APIUserAbortError } from \"../error.js\";\nimport {\n type ContentBlock,\n Messages,\n type Message,\n type MessageStreamEvent,\n type MessageParam,\n type MessageCreateParams,\n type MessageCreateParamsBase,\n type TextBlock,\n type TextCitation,\n} from \"../resources/messages.js\";\nimport { type ReadableStream, type Response } from \"../_shims/index.js\";\nimport { Stream } from \"../streaming.js\";\nimport { partialParse } from \"../_vendor/partial-json-parser/parser.js\";\n\nexport interface MessageStreamEvents {\n connect: () => void;\n streamEvent: (event: MessageStreamEvent, snapshot: Message) => void;\n text: (textDelta: string, textSnapshot: string) => void;\n citation: (citation: TextCitation, citationsSnapshot: TextCitation[]) => void;\n inputJson: (partialJson: string, jsonSnapshot: unknown) => void;\n thinking: (thinkingDelta: string, thinkingSnapshot: string) => void;\n signature: (signature: string) => void;\n message: (message: Message) => void;\n contentBlock: (content: ContentBlock) => void;\n finalMessage: (message: Message) => void;\n error: (error: AnthropicError) => void;\n abort: (error: APIUserAbortError) => void;\n end: () => void;\n}\n\ntype MessageStreamEventListeners<Event extends keyof MessageStreamEvents> = {\n listener: MessageStreamEvents[Event];\n once?: boolean;\n}[];\n\nconst JSON_BUF_PROPERTY = '__json_buf';\n\nexport class MessageStream implements AsyncIterable<MessageStreamEvent> {\n messages: MessageParam[] = [];\n receivedMessages: Message[] = [];\n #currentMessageSnapshot: Message | undefined;\n\n controller: AbortController = new AbortController();\n\n #connectedPromise: Promise<Response | null>;\n #resolveConnectedPromise: (response: Response | null) => void = () => {};\n #rejectConnectedPromise: (error: AnthropicError) => void = () => {};\n\n #endPromise: Promise<void>;\n #resolveEndPromise: () => void = () => {};\n #rejectEndPromise: (error: AnthropicError) => void = () => {};\n\n #listeners: { [Event in keyof MessageStreamEvents]?: MessageStreamEventListeners<Event> } = {};\n\n #ended = false;\n #errored = false;\n #aborted = false;\n #catchingPromiseCreated = false;\n #response: Response | null | undefined;\n #request_id: string | null | undefined;\n\n constructor() {\n this.#connectedPromise = new Promise<Response | null>((resolve, reject) => {\n this.#resolveConnectedPromise = resolve;\n this.#rejectConnectedPromise = reject;\n });\n\n this.#endPromise = new Promise<void>((resolve, reject) => {\n this.#resolveEndPromise = resolve;\n this.#rejectEndPromise = reject;\n });\n\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n this.#connectedPromise.catch(() => {});\n this.#endPromise.catch(() => {});\n }\n\n get response(): Response | null | undefined {\n return this.#response;\n }\n\n get request_id(): string | null | undefined {\n return this.#request_id;\n }\n\n /**\n * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * This is the same as the `APIPromise.withResponse()` method.\n *\n * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`\n * as no `Response` is available.\n */\n async withResponse(): Promise<{\n data: MessageStream;\n response: Response;\n request_id: string | null | undefined;\n }> {\n const response = await this.#connectedPromise;\n if (!response) {\n throw new Error('Could not resolve a `Response` object');\n }\n\n return {\n data: this,\n response,\n request_id: response.headers.get('request-id'),\n };\n }\n\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream: ReadableStream): MessageStream {\n const runner = new MessageStream();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n\n static createMessage(\n messages: Messages,\n params: MessageCreateParamsBase,\n options?: Core.RequestOptions,\n ): MessageStream {\n const runner = new MessageStream();\n for (const message of params.messages) {\n runner._addMessageParam(message);\n }\n runner._run(() =>\n runner._createMessage(\n messages,\n { ...params, stream: true },\n { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } },\n ),\n );\n return runner;\n }\n\n protected _run(executor: () => Promise<any>) {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, this.#handleError);\n }\n\n protected _addMessageParam(message: MessageParam) {\n this.messages.push(message);\n }\n\n protected _addMessage(message: Message, emit = true) {\n this.receivedMessages.push(message);\n if (emit) {\n this._emit('message', message);\n }\n }\n\n protected async _createMessage(\n messages: Messages,\n params: MessageCreateParams,\n options?: Core.RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n const { response, data: stream } = await messages\n .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })\n .withResponse();\n this._connected(response);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n }\n\n protected _connected(response: Response | null) {\n if (this.ended) return;\n this.#response = response;\n this.#request_id = response?.headers.get('request-id');\n this.#resolveConnectedPromise(response);\n this._emit('connect');\n }\n\n get ended(): boolean {\n return this.#ended;\n }\n\n get errored(): boolean {\n return this.#errored;\n }\n\n get aborted(): boolean {\n return this.#aborted;\n }\n\n abort() {\n this.controller.abort();\n }\n\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this MessageStream, so that calls can be chained\n */\n on<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener });\n return this;\n }\n\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this MessageStream, so that calls can be chained\n */\n off<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners = this.#listeners[event];\n if (!listeners) return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0) listeners.splice(index, 1);\n return this;\n }\n\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this MessageStream, so that calls can be chained\n */\n once<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted<Event extends keyof MessageStreamEvents>(\n event: Event,\n ): Promise<\n Parameters<MessageStreamEvents[Event]> extends [infer Param] ? Param\n : Parameters<MessageStreamEvents[Event]> extends [] ? void\n : Parameters<MessageStreamEvents[Event]>\n > {\n return new Promise((resolve, reject) => {\n this.#catchingPromiseCreated = true;\n if (event !== 'error') this.once('error', reject);\n this.once(event, resolve as any);\n });\n }\n\n async done(): Promise<void> {\n this.#catchingPromiseCreated = true;\n await this.#endPromise;\n }\n\n get currentMessage(): Message | undefined {\n return this.#currentMessageSnapshot;\n }\n\n #getFinalMessage(): Message {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n return this.receivedMessages.at(-1)!;\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message response,\n * or rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalMessage(): Promise<Message> {\n await this.done();\n return this.#getFinalMessage();\n }\n\n #getFinalText(): string {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n const textBlocks = this.receivedMessages\n .at(-1)!\n .content.filter((block): block is TextBlock => block.type === 'text')\n .map((block) => block.text);\n if (textBlocks.length === 0) {\n throw new AnthropicError('stream ended without producing a content block with type=text');\n }\n return textBlocks.join(' ');\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message's text response, concatenated\n * together if there are more than one text blocks.\n * Rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalText(): Promise<string> {\n await this.done();\n return this.#getFinalText();\n }\n\n #handleError = (error: unknown) => {\n this.#errored = true;\n if (error instanceof Error && error.name === 'AbortError') {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n this.#aborted = true;\n return this._emit('abort', error);\n }\n if (error instanceof AnthropicError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const anthropicError: AnthropicError = new AnthropicError(error.message);\n // @ts-ignore\n anthropicError.cause = error;\n return this._emit('error', anthropicError);\n }\n return this._emit('error', new AnthropicError(String(error)));\n };\n\n protected _emit<Event extends keyof MessageStreamEvents>(\n event: Event,\n ...args: Parameters<MessageStreamEvents[Event]>\n ) {\n // make sure we don't emit any MessageStreamEvents after end\n if (this.#ended) return;\n\n if (event === 'end') {\n this.#ended = true;\n this.#resolveEndPromise();\n }\n\n const listeners: MessageStreamEventListeners<Event> | undefined = this.#listeners[event];\n if (listeners) {\n this.#listeners[event] = listeners.filter((l) => !l.once) as any;\n listeners.forEach(({ listener }: any) => listener(...args));\n }\n\n if (event === 'abort') {\n const error = args[0] as APIUserAbortError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n return;\n }\n\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n\n const error = args[0] as AnthropicError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.final...()\n // - etc.\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n }\n }\n\n protected _emitFinal() {\n const finalMessage = this.receivedMessages.at(-1);\n if (finalMessage) {\n this._emit('finalMessage', this.#getFinalMessage());\n }\n }\n\n #beginRequest() {\n if (this.ended) return;\n this.#currentMessageSnapshot = undefined;\n }\n #addStreamEvent(event: MessageStreamEvent) {\n if (this.ended) return;\n const messageSnapshot = this.#accumulateMessage(event);\n this._emit('streamEvent', event, messageSnapshot);\n\n switch (event.type) {\n case 'content_block_delta': {\n const content = messageSnapshot.content.at(-1)!;\n switch (event.delta.type) {\n case 'text_delta': {\n if (content.type === 'text') {\n this._emit('text', event.delta.text, content.text || '');\n }\n break;\n }\n case 'citations_delta': {\n if (content.type === 'text') {\n this._emit('citation', event.delta.citation, content.citations ?? []);\n }\n break;\n }\n case 'input_json_delta': {\n if (content.type === 'tool_use' && content.input) {\n this._emit('inputJson', event.delta.partial_json, content.input);\n }\n break;\n }\n case 'thinking_delta': {\n if (content.type === 'thinking') {\n this._emit('thinking', event.delta.thinking, content.thinking);\n }\n break;\n }\n case 'signature_delta': {\n if (content.type === 'thinking') {\n this._emit('signature', content.signature);\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n break;\n }\n case 'message_stop': {\n this._addMessageParam(messageSnapshot);\n this._addMessage(messageSnapshot, true);\n break;\n }\n case 'content_block_stop': {\n this._emit('contentBlock', messageSnapshot.content.at(-1)!);\n break;\n }\n case 'message_start': {\n this.#currentMessageSnapshot = messageSnapshot;\n break;\n }\n case 'content_block_start':\n case 'message_delta':\n break;\n }\n }\n #endRequest(): Message {\n if (this.ended) {\n throw new AnthropicError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = this.#currentMessageSnapshot;\n if (!snapshot) {\n throw new AnthropicError(`request ended without sending any chunks`);\n }\n this.#currentMessageSnapshot = undefined;\n return snapshot;\n }\n\n protected async _fromReadableStream(\n readableStream: ReadableStream,\n options?: Core.RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n this._connected(null);\n const stream = Stream.fromReadableStream<MessageStreamEvent>(readableStream, this.controller);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n }\n\n /**\n * Mutates this.#currentMessage with the current event. Handling the accumulation of multiple messages\n * will be needed to be handled by the caller, this method will throw if you try to accumulate for multiple\n * messages.\n */\n #accumulateMessage(event: MessageStreamEvent): Message {\n let snapshot = this.#currentMessageSnapshot;\n\n if (event.type === 'message_start') {\n if (snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving \"message_stop\"`);\n }\n return event.message;\n }\n\n if (!snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before \"message_start\"`);\n }\n\n switch (event.type) {\n case 'message_stop':\n return snapshot;\n case 'message_delta':\n snapshot.stop_reason = event.delta.stop_reason;\n snapshot.stop_sequence = event.delta.stop_sequence;\n snapshot.usage.output_tokens = event.usage.output_tokens;\n return snapshot;\n case 'content_block_start':\n snapshot.content.push(event.content_block);\n return snapshot;\n case 'content_block_delta': {\n const snapshotContent = snapshot.content.at(event.index);\n\n switch (event.delta.type) {\n case 'text_delta': {\n if (snapshotContent?.type === 'text') {\n snapshotContent.text += event.delta.text;\n }\n break;\n }\n case 'citations_delta': {\n if (snapshotContent?.type === 'text') {\n snapshotContent.citations ??= [];\n snapshotContent.citations.push(event.delta.citation);\n }\n break;\n }\n case 'input_json_delta': {\n if (snapshotContent?.type === 'tool_use') {\n // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = (snapshotContent as any)[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n\n Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n\n if (jsonBuf) {\n snapshotContent.input = partialParse(jsonBuf);\n }\n }\n break;\n }\n case 'thinking_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshotContent.thinking += event.delta.thinking;\n }\n break;\n }\n case 'signature_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshotContent.signature = event.delta.signature;\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n\n return snapshot;\n }\n case 'content_block_stop':\n return snapshot;\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<MessageStreamEvent> {\n const pushQueue: MessageStreamEvent[] = [];\n const readQueue: {\n resolve: (chunk: MessageStreamEvent | undefined) => void;\n reject: (error: unknown) => void;\n }[] = [];\n let done = false;\n\n this.on('streamEvent', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n } else {\n pushQueue.push(event);\n }\n });\n\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n return {\n next: async (): Promise<IteratorResult<MessageStreamEvent>> => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise<MessageStreamEvent | undefined>((resolve, reject) =>\n readQueue.push({ resolve, reject }),\n ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift()!;\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n\n toReadableStream(): ReadableStream {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\n\n// used to ensure exhaustive case matching without throwing a runtime error\nfunction checkNever(x: never) {}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../resource.js\";\nimport { APIPromise } from \"../../core.js\";\nimport * as Core from \"../../core.js\";\nimport * as MessagesAPI from \"./messages.js\";\nimport * as BatchesAPI from \"./batches.js\";\nimport {\n BatchCreateParams,\n BatchListParams,\n Batches,\n DeletedMessageBatch,\n MessageBatch,\n MessageBatchCanceledResult,\n MessageBatchErroredResult,\n MessageBatchExpiredResult,\n MessageBatchIndividualResponse,\n MessageBatchRequestCounts,\n MessageBatchResult,\n MessageBatchSucceededResult,\n MessageBatchesPage,\n} from \"./batches.js\";\nimport { Stream } from \"../../streaming.js\";\nimport { MessageStream } from \"../../lib/MessageStream.js\";\n\nexport { MessageStream } from \"../../lib/MessageStream.js\";\n\nexport class Messages extends APIResource {\n batches: BatchesAPI.Batches = new BatchesAPI.Batches(this._client);\n\n /**\n * Send a structured list of input messages with text and/or image content, and the\n * model will generate the next message in the conversation.\n *\n * The Messages API can be used for either single queries or stateless multi-turn\n * conversations.\n *\n * Learn more about the Messages API in our [user guide](/en/docs/initial-setup)\n */\n create(body: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Message>;\n create(\n body: MessageCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent>>;\n create(\n body: MessageCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent> | Message>;\n create(\n body: MessageCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>> {\n if (body.model in DEPRECATED_MODELS) {\n console.warn(\n `The model '${body.model}' is deprecated and will reach end-of-life on ${\n DEPRECATED_MODELS[body.model]\n }\\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`,\n );\n }\n return this._client.post('/v1/messages', {\n body,\n timeout:\n (this._client as any)._options.timeout ??\n (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)),\n ...options,\n stream: body.stream ?? false,\n }) as APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>>;\n }\n\n /**\n * Create a Message stream\n */\n stream(body: MessageStreamParams, options?: Core.RequestOptions): MessageStream {\n return MessageStream.createMessage(this, body, options);\n }\n\n /**\n * Count the number of tokens in a Message.\n *\n * The Token Count API can be used to count the number of tokens in a Message,\n * including tools, images, and documents, without creating it.\n *\n * Learn more about token counting in our\n * [user guide](/en/docs/build-with-claude/token-counting)\n */\n countTokens(\n body: MessageCountTokensParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<MessageTokensCount> {\n return this._client.post('/v1/messages/count_tokens', { body, ...options });\n }\n}\n\nexport interface Base64ImageSource {\n data: string;\n\n media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';\n\n type: 'base64';\n}\n\nexport interface Base64PDFSource {\n data: string;\n\n media_type: 'application/pdf';\n\n type: 'base64';\n}\n\nexport interface CacheControlEphemeral {\n type: 'ephemeral';\n}\n\nexport interface CitationCharLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface CitationCharLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface CitationContentBlockLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface CitationContentBlockLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface CitationPageLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface CitationPageLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface CitationsConfigParam {\n enabled?: boolean;\n}\n\nexport interface CitationsDelta {\n citation: CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;\n\n type: 'citations_delta';\n}\n\nexport type ContentBlock = TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;\n\nexport type ContentBlockDeltaEvent = RawContentBlockDeltaEvent;\n\nexport type ContentBlockParam =\n | TextBlockParam\n | ImageBlockParam\n | ToolUseBlockParam\n | ToolResultBlockParam\n | DocumentBlockParam\n | ThinkingBlockParam\n | RedactedThinkingBlockParam;\n\nexport interface ContentBlockSource {\n content: string | Array<ContentBlockSourceContent>;\n\n type: 'content';\n}\n\nexport type ContentBlockSourceContent = TextBlockParam | ImageBlockParam;\n\nexport type ContentBlockStartEvent = RawContentBlockStartEvent;\n\nexport type ContentBlockStopEvent = RawContentBlockStopEvent;\n\nexport interface DocumentBlockParam {\n source: Base64PDFSource | PlainTextSource | ContentBlockSource | URLPDFSource;\n\n type: 'document';\n\n cache_control?: CacheControlEphemeral | null;\n\n citations?: CitationsConfigParam;\n\n context?: string | null;\n\n title?: string | null;\n}\n\nexport interface ImageBlockParam {\n source: Base64ImageSource | URLImageSource;\n\n type: 'image';\n\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport type InputJsonDelta = InputJSONDelta;\n\nexport interface InputJSONDelta {\n partial_json: string;\n\n type: 'input_json_delta';\n}\n\nexport interface Message {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * Content generated by the model.\n *\n * This is an array of content blocks, each of which has a `type` that determines\n * its shape.\n *\n * Example:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"Hi, I'm Claude.\" }]\n * ```\n *\n * If the request input `messages` ended with an `assistant` turn, then the\n * response `content` will continue directly from that last turn. You can use this\n * to constrain the model's output.\n *\n * For example, if the input `messages` were:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Then the response `content` might be:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"B)\" }]\n * ```\n */\n content: Array<ContentBlock>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: Model;\n\n /**\n * Conversational role of the generated message.\n *\n * This will always be `\"assistant\"`.\n */\n role: 'assistant';\n\n /**\n * The reason that we stopped.\n *\n * This may be one the following values:\n *\n * - `\"end_turn\"`: the model reached a natural stopping point\n * - `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n * - `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n * - `\"tool_use\"`: the model invoked one or more tools\n *\n * In non-streaming mode this value is always non-null. In streaming mode, it is\n * null in the `message_start` event and non-null otherwise.\n */\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;\n\n /**\n * Which custom stop sequence was generated, if any.\n *\n * This value will be a non-null string if one of your custom stop sequences was\n * generated.\n */\n stop_sequence: string | null;\n\n /**\n * Object type.\n *\n * For Messages, this is always `\"message\"`.\n */\n type: 'message';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: Usage;\n}\n\nexport type MessageCountTokensTool = Tool | ToolBash20250124 | ToolTextEditor20250124;\n\nexport type MessageDeltaEvent = RawMessageDeltaEvent;\n\nexport interface MessageDeltaUsage {\n /**\n * The cumulative number of output tokens which were used.\n */\n output_tokens: number;\n}\n\nexport interface MessageParam {\n content: string | Array<ContentBlockParam>;\n\n role: 'user' | 'assistant';\n}\n\nexport type MessageStartEvent = RawMessageStartEvent;\n\nexport type MessageStopEvent = RawMessageStopEvent;\n\nexport type MessageStreamEvent = RawMessageStreamEvent;\n\nexport interface MessageTokensCount {\n /**\n * The total number of tokens across the provided list of messages, system prompt,\n * and tools.\n */\n input_tokens: number;\n}\n\nexport interface Metadata {\n /**\n * An external identifier for the user who is associated with the request.\n *\n * This should be a uuid, hash value, or other opaque identifier. Anthropic may use\n * this id to help detect abuse. Do not include any identifying information such as\n * name, email address, or phone number.\n */\n user_id?: string | null;\n}\n\n/**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\nexport type Model =\n | 'claude-3-7-sonnet-latest'\n | 'claude-3-7-sonnet-20250219'\n | 'claude-3-5-haiku-latest'\n | 'claude-3-5-haiku-20241022'\n | 'claude-3-5-sonnet-latest'\n | 'claude-3-5-sonnet-20241022'\n | 'claude-3-5-sonnet-20240620'\n | 'claude-3-opus-latest'\n | 'claude-3-opus-20240229'\n | 'claude-3-sonnet-20240229'\n | 'claude-3-haiku-20240307'\n | 'claude-2.1'\n | 'claude-2.0'\n | (string & {});\n\nconst DEPRECATED_MODELS: {\n [K in Model]?: string;\n} = {\n 'claude-1.3': 'November 6th, 2024',\n 'claude-1.3-100k': 'November 6th, 2024',\n 'claude-instant-1.1': 'November 6th, 2024',\n 'claude-instant-1.1-100k': 'November 6th, 2024',\n 'claude-instant-1.2': 'November 6th, 2024',\n 'claude-3-sonnet-20240229': 'July 21st, 2025',\n 'claude-2.1': 'July 21st, 2025',\n 'claude-2.0': 'July 21st, 2025',\n};\n\nexport interface PlainTextSource {\n data: string;\n\n media_type: 'text/plain';\n\n type: 'text';\n}\n\nexport interface RawContentBlockDeltaEvent {\n delta: TextDelta | InputJSONDelta | CitationsDelta | ThinkingDelta | SignatureDelta;\n\n index: number;\n\n type: 'content_block_delta';\n}\n\nexport interface RawContentBlockStartEvent {\n content_block: TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;\n\n index: number;\n\n type: 'content_block_start';\n}\n\nexport interface RawContentBlockStopEvent {\n index: number;\n\n type: 'content_block_stop';\n}\n\nexport interface RawMessageDeltaEvent {\n delta: RawMessageDeltaEvent.Delta;\n\n type: 'message_delta';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: MessageDeltaUsage;\n}\n\nexport namespace RawMessageDeltaEvent {\n export interface Delta {\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;\n\n stop_sequence: string | null;\n }\n}\n\nexport interface RawMessageStartEvent {\n message: Message;\n\n type: 'message_start';\n}\n\nexport interface RawMessageStopEvent {\n type: 'message_stop';\n}\n\nexport type RawMessageStreamEvent =\n | RawMessageStartEvent\n | RawMessageDeltaEvent\n | RawMessageStopEvent\n | RawContentBlockStartEvent\n | RawContentBlockDeltaEvent\n | RawContentBlockStopEvent;\n\nexport interface RedactedThinkingBlock {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface RedactedThinkingBlockParam {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface SignatureDelta {\n signature: string;\n\n type: 'signature_delta';\n}\n\nexport interface TextBlock {\n /**\n * Citations supporting the text block.\n *\n * The type of citation returned will depend on the type of document being cited.\n * Citing a PDF results in `page_location`, plain text results in `char_location`,\n * and content document results in `content_block_location`.\n */\n citations: Array<TextCitation> | null;\n\n text: string;\n\n type: 'text';\n}\n\nexport interface TextBlockParam {\n text: string;\n\n type: 'text';\n\n cache_control?: CacheControlEphemeral | null;\n\n citations?: Array<TextCitationParam> | null;\n}\n\nexport type TextCitation = CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;\n\nexport type TextCitationParam =\n | CitationCharLocationParam\n | CitationPageLocationParam\n | CitationContentBlockLocationParam;\n\nexport interface TextDelta {\n text: string;\n\n type: 'text_delta';\n}\n\nexport interface ThinkingBlock {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface ThinkingBlockParam {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface ThinkingConfigDisabled {\n type: 'disabled';\n}\n\nexport interface ThinkingConfigEnabled {\n /**\n * Determines how many tokens Claude can use for its internal reasoning process.\n * Larger budgets can enable more thorough analysis for complex problems, improving\n * response quality.\n *\n * Must be \u22651024 and less than `max_tokens`.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n budget_tokens: number;\n\n type: 'enabled';\n}\n\n/**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\nexport type ThinkingConfigParam = ThinkingConfigEnabled | ThinkingConfigDisabled;\n\nexport interface ThinkingDelta {\n thinking: string;\n\n type: 'thinking_delta';\n}\n\nexport interface Tool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n input_schema: Tool.InputSchema;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: string;\n\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Description of what this tool does.\n *\n * Tool descriptions should be as detailed as possible. The more information that\n * the model has about what the tool is and how to use it, the better it will\n * perform. You can use natural language descriptions to reinforce important\n * aspects of the tool input JSON schema.\n */\n description?: string;\n}\n\nexport namespace Tool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n export interface InputSchema {\n type: 'object';\n\n properties?: unknown | null;\n [k: string]: unknown;\n }\n}\n\nexport interface ToolBash20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'bash';\n\n type: 'bash_20250124';\n\n cache_control?: CacheControlEphemeral | null;\n}\n\n/**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\nexport type ToolChoice = ToolChoiceAuto | ToolChoiceAny | ToolChoiceTool | ToolChoiceNone;\n\n/**\n * The model will use any available tools.\n */\nexport interface ToolChoiceAny {\n type: 'any';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will automatically decide whether to use tools.\n */\nexport interface ToolChoiceAuto {\n type: 'auto';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output at most one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will not be allowed to use tools.\n */\nexport interface ToolChoiceNone {\n type: 'none';\n}\n\n/**\n * The model will use the specified tool with `tool_choice.name`.\n */\nexport interface ToolChoiceTool {\n /**\n * The name of the tool to use.\n */\n name: string;\n\n type: 'tool';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\nexport interface ToolResultBlockParam {\n tool_use_id: string;\n\n type: 'tool_result';\n\n cache_control?: CacheControlEphemeral | null;\n\n content?: string | Array<TextBlockParam | ImageBlockParam>;\n\n is_error?: boolean;\n}\n\nexport interface ToolTextEditor20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'str_replace_editor';\n\n type: 'text_editor_20250124';\n\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport type ToolUnion = Tool | ToolBash20250124 | ToolTextEditor20250124;\n\nexport interface ToolUseBlock {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n}\n\nexport interface ToolUseBlockParam {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport interface URLImageSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface URLPDFSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface Usage {\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number | null;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number | null;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n}\n\nexport type MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming;\n\nexport interface MessageCreateParamsBase {\n /**\n * The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n *\n * Different models have different maximum values for this parameter. See\n * [models](https://docs.anthropic.com/en/docs/models-overview) for details.\n */\n max_tokens: number;\n\n /**\n * Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * Starting with Claude 3 models, you can also send image content blocks:\n *\n * ```json\n * {\n * \"role\": \"user\",\n * \"content\": [\n * {\n * \"type\": \"image\",\n * \"source\": {\n * \"type\": \"base64\",\n * \"media_type\": \"image/jpeg\",\n * \"data\": \"/9j/4AAQSkZJRg...\"\n * }\n * },\n * { \"type\": \"text\", \"text\": \"What is in this image?\" }\n * ]\n * }\n * ```\n *\n * We currently support the `base64` source type for images, and the `image/jpeg`,\n * `image/png`, `image/gif`, and `image/webp` media types.\n *\n * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for\n * more input examples.\n *\n * Note that if you want to include a\n * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use\n * the top-level `system` parameter \u2014 there is no `\"system\"` role for input\n * messages in the Messages API.\n */\n messages: Array<MessageParam>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: Model;\n\n /**\n * An object describing metadata about the request.\n */\n metadata?: Metadata;\n\n /**\n * Custom text sequences that will cause the model to stop generating.\n *\n * Our models will normally stop when they have naturally completed their turn,\n * which will result in a response `stop_reason` of `\"end_turn\"`.\n *\n * If you want the model to stop generating when it encounters custom strings of\n * text, you can use the `stop_sequences` parameter. If the model encounters one of\n * the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"`\n * and the response `stop_sequence` value will contain the matched stop sequence.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream?: boolean;\n\n /**\n * System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).\n */\n system?: string | Array<TextBlockParam>;\n\n /**\n * Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\n */\n temperature?: number;\n\n /**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: ThinkingConfigParam;\n\n /**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: ToolChoice;\n\n /**\n * Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.\n */\n tools?: Array<ToolUnion>;\n\n /**\n * Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_p?: number;\n}\n\nexport namespace MessageCreateParams {\n /**\n * @deprecated use `Anthropic.Messages.ToolChoiceAuto` instead\n */\n export type Metadata = MessagesAPI.Metadata;\n\n /**\n * @deprecated use `Anthropic.Messages.ToolChoiceAuto` instead\n */\n export type ToolChoiceAuto = MessagesAPI.ToolChoiceAuto;\n\n /**\n * @deprecated use `Anthropic.Messages.ToolChoiceAny` instead\n */\n export type ToolChoiceAny = MessagesAPI.ToolChoiceAny;\n\n /**\n * @deprecated use `Anthropic.Messages.ToolChoiceTool` instead\n */\n export type ToolChoiceTool = MessagesAPI.ToolChoiceTool;\n\n export type MessageCreateParamsNonStreaming = MessagesAPI.MessageCreateParamsNonStreaming;\n export type MessageCreateParamsStreaming = MessagesAPI.MessageCreateParamsStreaming;\n}\n\nexport interface MessageCreateParamsNonStreaming extends MessageCreateParamsBase {\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream?: false;\n}\n\nexport interface MessageCreateParamsStreaming extends MessageCreateParamsBase {\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream: true;\n}\n\nexport type MessageStreamParams = MessageCreateParamsBase;\n\nexport interface MessageCountTokensParams {\n /**\n * Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * Starting with Claude 3 models, you can also send image content blocks:\n *\n * ```json\n * {\n * \"role\": \"user\",\n * \"content\": [\n * {\n * \"type\": \"image\",\n * \"source\": {\n * \"type\": \"base64\",\n * \"media_type\": \"image/jpeg\",\n * \"data\": \"/9j/4AAQSkZJRg...\"\n * }\n * },\n * { \"type\": \"text\", \"text\": \"What is in this image?\" }\n * ]\n * }\n * ```\n *\n * We currently support the `base64` source type for images, and the `image/jpeg`,\n * `image/png`, `image/gif`, and `image/webp` media types.\n *\n * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for\n * more input examples.\n *\n * Note that if you want to include a\n * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use\n * the top-level `system` parameter \u2014 there is no `\"system\"` role for input\n * messages in the Messages API.\n */\n messages: Array<MessageParam>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: Model;\n\n /**\n * System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).\n */\n system?: string | Array<TextBlockParam>;\n\n /**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: ThinkingConfigParam;\n\n /**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: ToolChoice;\n\n /**\n * Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.\n */\n tools?: Array<MessageCountTokensTool>;\n}\n\nMessages.Batches = Batches;\nMessages.MessageBatchesPage = MessageBatchesPage;\n\nexport declare namespace Messages {\n export {\n type Base64ImageSource as Base64ImageSource,\n type Base64PDFSource as Base64PDFSource,\n type CacheControlEphemeral as CacheControlEphemeral,\n type CitationCharLocation as CitationCharLocation,\n type CitationCharLocationParam as CitationCharLocationParam,\n type CitationContentBlockLocation as CitationContentBlockLocation,\n type CitationContentBlockLocationParam as CitationContentBlockLocationParam,\n type CitationPageLocation as CitationPageLocation,\n type CitationPageLocationParam as CitationPageLocationParam,\n type CitationsConfigParam as CitationsConfigParam,\n type CitationsDelta as CitationsDelta,\n type ContentBlock as ContentBlock,\n type ContentBlockDeltaEvent as ContentBlockDeltaEvent,\n type ContentBlockParam as ContentBlockParam,\n type ContentBlockSource as ContentBlockSource,\n type ContentBlockSourceContent as ContentBlockSourceContent,\n type ContentBlockStartEvent as ContentBlockStartEvent,\n type ContentBlockStopEvent as ContentBlockStopEvent,\n type DocumentBlockParam as DocumentBlockParam,\n type ImageBlockParam as ImageBlockParam,\n type InputJsonDelta as InputJsonDelta,\n type InputJSONDelta as InputJSONDelta,\n type Message as Message,\n type MessageCountTokensTool as MessageCountTokensTool,\n type MessageDeltaEvent as MessageDeltaEvent,\n type MessageDeltaUsage as MessageDeltaUsage,\n type MessageParam as MessageParam,\n type MessageStartEvent as MessageStartEvent,\n type MessageStopEvent as MessageStopEvent,\n type MessageStreamEvent as MessageStreamEvent,\n type MessageTokensCount as MessageTokensCount,\n type Metadata as Metadata,\n type Model as Model,\n type PlainTextSource as PlainTextSource,\n type RawContentBlockDeltaEvent as RawContentBlockDeltaEvent,\n type RawContentBlockStartEvent as RawContentBlockStartEvent,\n type RawContentBlockStopEvent as RawContentBlockStopEvent,\n type RawMessageDeltaEvent as RawMessageDeltaEvent,\n type RawMessageStartEvent as RawMessageStartEvent,\n type RawMessageStopEvent as RawMessageStopEvent,\n type RawMessageStreamEvent as RawMessageStreamEvent,\n type RedactedThinkingBlock as RedactedThinkingBlock,\n type RedactedThinkingBlockParam as RedactedThinkingBlockParam,\n type SignatureDelta as SignatureDelta,\n type TextBlock as TextBlock,\n type TextBlockParam as TextBlockParam,\n type TextCitation as TextCitation,\n type TextCitationParam as TextCitationParam,\n type TextDelta as TextDelta,\n type ThinkingBlock as ThinkingBlock,\n type ThinkingBlockParam as ThinkingBlockParam,\n type ThinkingConfigDisabled as ThinkingConfigDisabled,\n type ThinkingConfigEnabled as ThinkingConfigEnabled,\n type ThinkingConfigParam as ThinkingConfigParam,\n type ThinkingDelta as ThinkingDelta,\n type Tool as Tool,\n type ToolBash20250124 as ToolBash20250124,\n type ToolChoice as ToolChoice,\n type ToolChoiceAny as ToolChoiceAny,\n type ToolChoiceAuto as ToolChoiceAuto,\n type ToolChoiceNone as ToolChoiceNone,\n type ToolChoiceTool as ToolChoiceTool,\n type ToolResultBlockParam as ToolResultBlockParam,\n type ToolTextEditor20250124 as ToolTextEditor20250124,\n type ToolUnion as ToolUnion,\n type ToolUseBlock as ToolUseBlock,\n type ToolUseBlockParam as ToolUseBlockParam,\n type URLImageSource as URLImageSource,\n type URLPDFSource as URLPDFSource,\n type Usage as Usage,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageStreamParams as MessageStreamParams,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export {\n Batches as Batches,\n type DeletedMessageBatch as DeletedMessageBatch,\n type MessageBatch as MessageBatch,\n type MessageBatchCanceledResult as MessageBatchCanceledResult,\n type MessageBatchErroredResult as MessageBatchErroredResult,\n type MessageBatchExpiredResult as MessageBatchExpiredResult,\n type MessageBatchIndividualResponse as MessageBatchIndividualResponse,\n type MessageBatchRequestCounts as MessageBatchRequestCounts,\n type MessageBatchResult as MessageBatchResult,\n type MessageBatchSucceededResult as MessageBatchSucceededResult,\n MessageBatchesPage as MessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchListParams as BatchListParams,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../resource.js\";\nimport { isRequestOptions } from \"../core.js\";\nimport * as Core from \"../core.js\";\nimport { Page, type PageParams } from \"../pagination.js\";\n\nexport class Models extends APIResource {\n /**\n * Get a specific model.\n *\n * The Models API response can be used to determine information about a specific\n * model or resolve a model alias to a model ID.\n */\n retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo> {\n return this._client.get(`/v1/models/${modelId}`, options);\n }\n\n /**\n * List available models.\n *\n * The Models API response can be used to determine which models are available for\n * use in the API. More recently released models are listed first.\n */\n list(query?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;\n list(options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;\n list(\n query: ModelListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<ModelInfosPage, ModelInfo> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/v1/models', ModelInfosPage, { query, ...options });\n }\n}\n\nexport class ModelInfosPage extends Page<ModelInfo> {}\n\nexport interface ModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the model was released.\n * May be set to an epoch value if the release date is unknown.\n */\n created_at: string;\n\n /**\n * A human-readable name for the model.\n */\n display_name: string;\n\n /**\n * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\n}\n\nexport interface ModelListParams extends PageParams {}\n\nModels.ModelInfosPage = ModelInfosPage;\n\nexport declare namespace Models {\n export {\n type ModelInfo as ModelInfo,\n ModelInfosPage as ModelInfosPage,\n type ModelListParams as ModelListParams,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { type Agent } from \"./_shims/index.js\";\nimport * as Core from \"./core.js\";\nimport * as Errors from \"./error.js\";\nimport * as Pagination from \"./pagination.js\";\nimport { type PageParams, PageResponse } from \"./pagination.js\";\nimport * as Uploads from \"./uploads.js\";\nimport * as API from \"./resources/index.js\";\nimport {\n Completion,\n CompletionCreateParams,\n CompletionCreateParamsNonStreaming,\n CompletionCreateParamsStreaming,\n Completions,\n} from \"./resources/completions.js\";\nimport { ModelInfo, ModelInfosPage, ModelListParams, Models } from \"./resources/models.js\";\nimport {\n AnthropicBeta,\n Beta,\n BetaAPIError,\n BetaAuthenticationError,\n BetaBillingError,\n BetaError,\n BetaErrorResponse,\n BetaGatewayTimeoutError,\n BetaInvalidRequestError,\n BetaNotFoundError,\n BetaOverloadedError,\n BetaPermissionError,\n BetaRateLimitError,\n} from \"./resources/beta/beta.js\";\nimport {\n Base64ImageSource,\n Base64PDFSource,\n CacheControlEphemeral,\n CitationCharLocation,\n CitationCharLocationParam,\n CitationContentBlockLocation,\n CitationContentBlockLocationParam,\n CitationPageLocation,\n CitationPageLocationParam,\n CitationsConfigParam,\n CitationsDelta,\n ContentBlock,\n ContentBlockDeltaEvent,\n ContentBlockParam,\n ContentBlockSource,\n ContentBlockSourceContent,\n ContentBlockStartEvent,\n ContentBlockStopEvent,\n DocumentBlockParam,\n ImageBlockParam,\n InputJSONDelta,\n Message,\n MessageCountTokensParams,\n MessageCountTokensTool,\n MessageCreateParams,\n MessageCreateParamsNonStreaming,\n MessageCreateParamsStreaming,\n MessageDeltaEvent,\n MessageDeltaUsage,\n MessageParam,\n MessageStartEvent,\n MessageStopEvent,\n MessageStreamEvent,\n MessageStreamParams,\n MessageTokensCount,\n Messages,\n Metadata,\n Model,\n PlainTextSource,\n RawContentBlockDeltaEvent,\n RawContentBlockStartEvent,\n RawContentBlockStopEvent,\n RawMessageDeltaEvent,\n RawMessageStartEvent,\n RawMessageStopEvent,\n RawMessageStreamEvent,\n RedactedThinkingBlock,\n RedactedThinkingBlockParam,\n SignatureDelta,\n TextBlock,\n TextBlockParam,\n TextCitation,\n TextCitationParam,\n TextDelta,\n ThinkingBlock,\n ThinkingBlockParam,\n ThinkingConfigDisabled,\n ThinkingConfigEnabled,\n ThinkingConfigParam,\n ThinkingDelta,\n Tool,\n ToolBash20250124,\n ToolChoice,\n ToolChoiceAny,\n ToolChoiceAuto,\n ToolChoiceNone,\n ToolChoiceTool,\n ToolResultBlockParam,\n ToolTextEditor20250124,\n ToolUnion,\n ToolUseBlock,\n ToolUseBlockParam,\n URLImageSource,\n URLPDFSource,\n Usage,\n} from \"./resources/messages/messages.js\";\n\nexport interface ClientOptions {\n /**\n * Defaults to process.env['ANTHROPIC_API_KEY'].\n */\n apiKey?: string | null | undefined;\n\n /**\n * Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].\n */\n authToken?: string | null | undefined;\n\n /**\n * Override the default base URL for the API, e.g., \"https://api.example.com/v2/\"\n *\n * Defaults to process.env['ANTHROPIC_BASE_URL'].\n */\n baseURL?: string | null | undefined;\n\n /**\n * The maximum amount of time (in milliseconds) that the client should wait for a response\n * from the server before timing out a single request.\n *\n * Note that request timeouts are retried by default, so in a worst-case scenario you may wait\n * much longer than this timeout before the promise succeeds or fails.\n */\n timeout?: number | undefined;\n\n /**\n * An HTTP agent used to manage HTTP(S) connections.\n *\n * If not provided, an agent will be constructed by default in the Node.js environment,\n * otherwise no agent is used.\n */\n httpAgent?: Agent | undefined;\n\n /**\n * Specify a custom `fetch` function implementation.\n *\n * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is\n * defined globally.\n */\n fetch?: Core.Fetch | undefined;\n\n /**\n * The maximum number of times that the client will retry a request in case of a\n * temporary failure, like a network error or a 5XX error from the server.\n *\n * @default 2\n */\n maxRetries?: number | undefined;\n\n /**\n * Default headers to include with every request to the API.\n *\n * These can be removed in individual requests by explicitly setting the\n * header to `undefined` or `null` in request options.\n */\n defaultHeaders?: Core.Headers | undefined;\n\n /**\n * Default query parameters to include with every request to the API.\n *\n * These can be removed in individual requests by explicitly setting the\n * param to `undefined` in request options.\n */\n defaultQuery?: Core.DefaultQuery | undefined;\n\n /**\n * By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n * Only set this option to `true` if you understand the risks and have appropriate mitigations in place.\n */\n dangerouslyAllowBrowser?: boolean | undefined;\n}\n\n/**\n * API Client for interfacing with the Anthropic API.\n */\nexport class Anthropic extends Core.APIClient {\n apiKey: string | null;\n authToken: string | null;\n\n private _options: ClientOptions;\n\n /**\n * API Client for interfacing with the Anthropic API.\n *\n * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]\n * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]\n * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.\n * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @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.\n */\n constructor({\n baseURL = Core.readEnv('ANTHROPIC_BASE_URL'),\n apiKey = Core.readEnv('ANTHROPIC_API_KEY') ?? null,\n authToken = Core.readEnv('ANTHROPIC_AUTH_TOKEN') ?? null,\n ...opts\n }: ClientOptions = {}) {\n const options: ClientOptions = {\n apiKey,\n authToken,\n ...opts,\n baseURL: baseURL || `https://api.anthropic.com`,\n };\n\n if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {\n throw new Errors.AnthropicError(\n \"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\",\n );\n }\n\n super({\n baseURL: options.baseURL!,\n timeout: options.timeout ?? 600000 /* 10 minutes */,\n httpAgent: options.httpAgent,\n maxRetries: options.maxRetries,\n fetch: options.fetch,\n });\n\n this._options = options;\n\n this.apiKey = apiKey;\n this.authToken = authToken;\n }\n\n completions: API.Completions = new API.Completions(this);\n messages: API.Messages = new API.Messages(this);\n models: API.Models = new API.Models(this);\n beta: API.Beta = new API.Beta(this);\n\n protected override defaultQuery(): Core.DefaultQuery | undefined {\n return this._options.defaultQuery;\n }\n\n protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {\n return {\n ...super.defaultHeaders(opts),\n ...(this._options.dangerouslyAllowBrowser ?\n { 'anthropic-dangerous-direct-browser-access': 'true' }\n : undefined),\n 'anthropic-version': '2023-06-01',\n ...this._options.defaultHeaders,\n };\n }\n\n protected override validateHeaders(headers: Core.Headers, customHeaders: Core.Headers) {\n if (this.apiKey && headers['x-api-key']) {\n return;\n }\n if (customHeaders['x-api-key'] === null) {\n return;\n }\n\n if (this.authToken && headers['authorization']) {\n return;\n }\n if (customHeaders['authorization'] === null) {\n return;\n }\n\n throw new Error(\n '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',\n );\n }\n\n protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {\n const apiKeyAuth = this.apiKeyAuth(opts);\n const bearerAuth = this.bearerAuth(opts);\n\n if (apiKeyAuth != null && !Core.isEmptyObj(apiKeyAuth)) {\n return apiKeyAuth;\n }\n\n if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {\n return bearerAuth;\n }\n return {};\n }\n\n protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {\n if (this.apiKey == null) {\n return {};\n }\n return { 'X-Api-Key': this.apiKey };\n }\n\n protected bearerAuth(opts: Core.FinalRequestOptions): Core.Headers {\n if (this.authToken == null) {\n return {};\n }\n return { Authorization: `Bearer ${this.authToken}` };\n }\n\n static Anthropic = this;\n static HUMAN_PROMPT = '\\n\\nHuman:';\n static AI_PROMPT = '\\n\\nAssistant:';\n static DEFAULT_TIMEOUT = 600000; // 10 minutes\n\n static AnthropicError = Errors.AnthropicError;\n static APIError = Errors.APIError;\n static APIConnectionError = Errors.APIConnectionError;\n static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;\n static APIUserAbortError = Errors.APIUserAbortError;\n static NotFoundError = Errors.NotFoundError;\n static ConflictError = Errors.ConflictError;\n static RateLimitError = Errors.RateLimitError;\n static BadRequestError = Errors.BadRequestError;\n static AuthenticationError = Errors.AuthenticationError;\n static InternalServerError = Errors.InternalServerError;\n static PermissionDeniedError = Errors.PermissionDeniedError;\n static UnprocessableEntityError = Errors.UnprocessableEntityError;\n\n static toFile = Uploads.toFile;\n static fileFromPath = Uploads.fileFromPath;\n}\n\nAnthropic.Completions = Completions;\nAnthropic.Messages = Messages;\nAnthropic.Models = Models;\nAnthropic.ModelInfosPage = ModelInfosPage;\nAnthropic.Beta = Beta;\nexport declare namespace Anthropic {\n export type RequestOptions = Core.RequestOptions;\n\n export import Page = Pagination.Page;\n export { type PageParams as PageParams, type PageResponse as PageResponse };\n\n export {\n Completions as Completions,\n type Completion as Completion,\n type CompletionCreateParams as CompletionCreateParams,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n };\n\n export {\n Messages as Messages,\n type Base64ImageSource as Base64ImageSource,\n type Base64PDFSource as Base64PDFSource,\n type CacheControlEphemeral as CacheControlEphemeral,\n type CitationCharLocation as CitationCharLocation,\n type CitationCharLocationParam as CitationCharLocationParam,\n type CitationContentBlockLocation as CitationContentBlockLocation,\n type CitationContentBlockLocationParam as CitationContentBlockLocationParam,\n type CitationPageLocation as CitationPageLocation,\n type CitationPageLocationParam as CitationPageLocationParam,\n type CitationsConfigParam as CitationsConfigParam,\n type CitationsDelta as CitationsDelta,\n type ContentBlock as ContentBlock,\n type ContentBlockDeltaEvent as ContentBlockDeltaEvent,\n type ContentBlockParam as ContentBlockParam,\n type ContentBlockSource as ContentBlockSource,\n type ContentBlockSourceContent as ContentBlockSourceContent,\n type ContentBlockStartEvent as ContentBlockStartEvent,\n type ContentBlockStopEvent as ContentBlockStopEvent,\n type DocumentBlockParam as DocumentBlockParam,\n type ImageBlockParam as ImageBlockParam,\n type InputJSONDelta as InputJSONDelta,\n type Message as Message,\n type MessageCountTokensTool as MessageCountTokensTool,\n type MessageDeltaEvent as MessageDeltaEvent,\n type MessageDeltaUsage as MessageDeltaUsage,\n type MessageParam as MessageParam,\n type MessageStartEvent as MessageStartEvent,\n type MessageStopEvent as MessageStopEvent,\n type MessageStreamEvent as MessageStreamEvent,\n type MessageTokensCount as MessageTokensCount,\n type Metadata as Metadata,\n type Model as Model,\n type PlainTextSource as PlainTextSource,\n type RawContentBlockDeltaEvent as RawContentBlockDeltaEvent,\n type RawContentBlockStartEvent as RawContentBlockStartEvent,\n type RawContentBlockStopEvent as RawContentBlockStopEvent,\n type RawMessageDeltaEvent as RawMessageDeltaEvent,\n type RawMessageStartEvent as RawMessageStartEvent,\n type RawMessageStopEvent as RawMessageStopEvent,\n type RawMessageStreamEvent as RawMessageStreamEvent,\n type RedactedThinkingBlock as RedactedThinkingBlock,\n type RedactedThinkingBlockParam as RedactedThinkingBlockParam,\n type SignatureDelta as SignatureDelta,\n type TextBlock as TextBlock,\n type TextBlockParam as TextBlockParam,\n type TextCitation as TextCitation,\n type TextCitationParam as TextCitationParam,\n type TextDelta as TextDelta,\n type ThinkingBlock as ThinkingBlock,\n type ThinkingBlockParam as ThinkingBlockParam,\n type ThinkingConfigDisabled as ThinkingConfigDisabled,\n type ThinkingConfigEnabled as ThinkingConfigEnabled,\n type ThinkingConfigParam as ThinkingConfigParam,\n type ThinkingDelta as ThinkingDelta,\n type Tool as Tool,\n type ToolBash20250124 as ToolBash20250124,\n type ToolChoice as ToolChoice,\n type ToolChoiceAny as ToolChoiceAny,\n type ToolChoiceAuto as ToolChoiceAuto,\n type ToolChoiceNone as ToolChoiceNone,\n type ToolChoiceTool as ToolChoiceTool,\n type ToolResultBlockParam as ToolResultBlockParam,\n type ToolTextEditor20250124 as ToolTextEditor20250124,\n type ToolUnion as ToolUnion,\n type ToolUseBlock as ToolUseBlock,\n type ToolUseBlockParam as ToolUseBlockParam,\n type URLImageSource as URLImageSource,\n type URLPDFSource as URLPDFSource,\n type Usage as Usage,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageStreamParams as MessageStreamParams,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export {\n Models as Models,\n type ModelInfo as ModelInfo,\n ModelInfosPage as ModelInfosPage,\n type ModelListParams as ModelListParams,\n };\n\n export {\n Beta as Beta,\n type AnthropicBeta as AnthropicBeta,\n type BetaAPIError as BetaAPIError,\n type BetaAuthenticationError as BetaAuthenticationError,\n type BetaBillingError as BetaBillingError,\n type BetaError as BetaError,\n type BetaErrorResponse as BetaErrorResponse,\n type BetaGatewayTimeoutError as BetaGatewayTimeoutError,\n type BetaInvalidRequestError as BetaInvalidRequestError,\n type BetaNotFoundError as BetaNotFoundError,\n type BetaOverloadedError as BetaOverloadedError,\n type BetaPermissionError as BetaPermissionError,\n type BetaRateLimitError as BetaRateLimitError,\n };\n\n export type APIErrorObject = API.APIErrorObject;\n export type AuthenticationError = API.AuthenticationError;\n export type BillingError = API.BillingError;\n export type ErrorObject = API.ErrorObject;\n export type ErrorResponse = API.ErrorResponse;\n export type GatewayTimeoutError = API.GatewayTimeoutError;\n export type InvalidRequestError = API.InvalidRequestError;\n export type NotFoundError = API.NotFoundError;\n export type OverloadedError = API.OverloadedError;\n export type PermissionError = API.PermissionError;\n export type RateLimitError = API.RateLimitError;\n}\nexport const { HUMAN_PROMPT, AI_PROMPT } = Anthropic;\n\nexport { toFile, fileFromPath } from \"./uploads.js\";\nexport {\n AnthropicError,\n APIError,\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n NotFoundError,\n ConflictError,\n RateLimitError,\n BadRequestError,\n AuthenticationError,\n InternalServerError,\n PermissionDeniedError,\n UnprocessableEntityError,\n} from \"./error.js\";\n\nexport default Anthropic;\n", "import type Anthropic from '@anthropic-ai/sdk';\n\nexport const DEFAULT_ANTHROPIC_PARAMS = {\n // model: 'claude-3-5-sonnet-20241022',\n model: 'claude-3-7-sonnet-20250219',\n max_tokens: 8192,\n temperature: 0.1\n};\n\nexport const DEFAULT_ANTHROPIC_OPTIONS = {\n headers: {\n 'x-api-key': null, // Ensuring headers are omitted\n authorization: null\n }\n};\n\nasync function sendPrompt(\n anthropic: Anthropic,\n config: {\n proxyUrl: string;\n\n model?: string;\n maxTokens?: number;\n temperature?: number;\n },\n prompt: string,\n signal: AbortSignal\n): Promise<AsyncGenerator<string, void, unknown>> {\n const customOptions: Partial<typeof DEFAULT_ANTHROPIC_PARAMS> = {};\n if (config.model) customOptions.model = config.model;\n if (config.maxTokens) customOptions.max_tokens = config.maxTokens;\n if (config.temperature) customOptions.temperature = config.temperature;\n\n const msg = await anthropic.messages.create(\n {\n ...DEFAULT_ANTHROPIC_PARAMS,\n ...customOptions,\n stream: true,\n messages: [\n {\n role: 'user',\n content: [\n {\n type: 'text',\n text: prompt\n }\n ]\n }\n ]\n },\n {\n signal,\n ...DEFAULT_ANTHROPIC_OPTIONS\n }\n );\n\n // Return an async generator that yields only the text chunks\n async function* textStreamGenerator() {\n try {\n for await (const chunk of msg) {\n if (\n chunk.type === 'content_block_delta' &&\n chunk.delta.type === 'text_delta'\n ) {\n yield chunk.delta.text;\n }\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Stream error:', error);\n throw error; // Re-throw to allow consumer to handle\n }\n }\n\n return textStreamGenerator();\n}\n\nexport default sendPrompt;\n", "function improve(text: string): string {\n return `\nYou are an AI writing assistant tasked with improving a given text based on a specific type of improvement requested. Your goal is to enhance the text while maintaining its original meaning and intent.\n\nHere is the original text you will be working with:\n\n<original_text>\n${text}\n</original_text>\n\nPlease follow these steps to improve the text:\n\n1. Carefully read and analyze the original text.\n2. Consider the specific improvement type requested and how it applies to the given text.\n3. Make the necessary changes to improve the text according to the requested improvement type. This may include:\n - Rephrasing sentences\n - Adjusting vocabulary\n - Restructuring paragraphs\n - Adding or removing content as appropriate\n4. Ensure that the improved version maintains the original meaning and intent of the text.\n5. Return the improved text without any additional commentary or explanation.\n6. If there is nothing to improve, simply return the original text without any changes.\n7. If you cannot make any meaningful improvements, return the original text as is.\n\nOnce you have made the improvements, only return the improved text and nothing else.\n`;\n}\n\nexport default improve;\n", "function shorter(text: string): string {\n return `\nYou will be given a text to shorten. Your task is to reduce the length of the text by 30% to 50% while maintaining its original voice, perspective, and key information. This is not a summary - you should preserve the style and tone of the original text.\n\nHere is the original text:\n\n<original_text>\n${text}\n</original_text>\n\nTo complete this task, follow these steps:\n\n1. Carefully read and analyze the text, paying attention to its style, tone, and main points.\n\n2. Identify areas where the text can be condensed without losing essential information or altering the author's voice.\n\n3. Begin shortening the text by:\n - Removing redundant or repetitive information\n - Simplifying complex sentences\n - Eliminating unnecessary examples or elaborations\n - Combining related ideas into more concise statements\n\n4. As you shorten, continuously check that you are:\n - Maintaining the original voice and perspective\n - Keeping all crucial information\n - Preserving the flow and coherence of the text\n\n5. Aim to reduce the length by 30% to 50% of the original. If you find yourself shortening less than 30%, look for additional opportunities to condense. If you're reducing more than 50%, ensure you haven't cut too much important content.\n\n6. Once you've finished shortening, review the text to ensure it still reads smoothly and retains the essence of the original.\n\nProvide only the shortened version of the text in your response, without any additional comments, tags or explanations.\n`;\n}\n\nexport default shorter;\n", "function longer(text: string): string {\n return `\nYou are tasked with expanding a given text to make it longer. Here's how to proceed:\n\nFirst, you will be provided with the original text:\n\n<original_text>\n${text}\n</original_text>\n\nTo expand the text:\n\n1. Analyze the original text to understand its main ideas, tone, and style.\n2. Identify areas where you can add more detail, examples, or explanations.\n3. Expand on these areas by:\n - Providing more context or background information\n - Adding relevant examples or anecdotes\n - Elaborating on key points\n - Introducing related concepts or ideas\n - Explaining implications or consequences of the main ideas\n4. Ensure that the expanded text length is not exceeding the original text by more than 50%.\n5. Always expand the text, even if it is a single word. Explain the word with a few short sentences in that case. If the text is empty, make up a short sentence.\n\nGuidelines:\n\n- Maintain the original tone and style of the text.\n- Ensure all additions are relevant to the main topic.\n- Keep the flow of the text natural and coherent.\n- Do not contradict any information in the original text.\n\nOnly return the longer text and nothing else.\n\nMake sure to only return the expanded text and nothing else. Do not include any additional information or comments in your response about what you have done.\n\nDo not add the original text or the original_text tags to the response.\n`;\n}\n\nexport default longer;\n", "function fix(text: string): string {\n return `\nYou are tasked with fixing spelling and grammar errors in a given text. Your goal is to improve the text while maintaining its original meaning and style. Here is the text you need to correct:\n\n<original_text>\n${text}\n</original_text>\n\nPlease follow these steps to complete the task:\n\n1. Carefully read through the text and identify any spelling or grammatical errors.\n\n2. Correct all spelling mistakes, including typos and incorrectly spelled words.\n\n3. Fix grammatical errors, including:\n - Incorrect verb tenses\n - Subject-verb agreement issues\n - Improper use of articles (a, an, the)\n - Incorrect word usage\n - Run-on sentences or sentence fragments\n - Punctuation errors\n\n4. Ensure proper capitalization, especially at the beginning of sentences and for proper nouns.\n\n5. Maintain the original meaning and tone of the text. Do not add or remove information, or change the author's intended message.\n\n6. Make sure the corrected text flows naturally and is easy to read.\n\nAfter making the necessary corrections, please provide only the improved output and nothing else.\n\nRemember to preserve the original structure and formatting of the text as much as possible while making your corrections.\n`;\n}\n\nexport default fix;\n", "function generateTextForSpeech(text: string): string {\n return `\n Your task is to create a new text based on a given prompt. The text should be short enough that it can be read aloud in no more than 5 seconds.\n\nFollow these guidelines when generating the text:\n1. Keep the text concise and to the point.\n2. Use simple words and sentence structures.\n3. Aim for approximately 20-25 words.\n4. Ensure the text is coherent and meaningful.\n5. Stay relevant to the given prompt.\n\nHere is the prompt to base your text on:\n<prompt>\n${text}\n</prompt>\n\nGenerate a short text based on this prompt. Output only the generated text, without any additional explanation or commentary. Do not include any XML tags in your response.\n`;\n}\n\nexport default generateTextForSpeech;\n", "export const LANGUAGES = {\n en_US: 'English (US)',\n en_UK: 'English (UK)',\n es: 'Spanish',\n fr: 'French',\n de: 'German',\n pt: 'Portuguese',\n it: 'Italian',\n ru: 'Russian',\n zh: 'Mandarin Chinese',\n ja: 'Japanese'\n} as const;\n\nexport const LOCALES = Object.keys(LANGUAGES) as Locale[];\n\nexport type Locale = keyof typeof LANGUAGES;\n\nfunction translate(text: string, locale: Locale): string {\n const language = LANGUAGES[locale] || locale;\n\n return `\nYou are a translation AI. Your task is to translate the given text into the specified target language. Follow these steps:\n\n1. Here is the source text to be translated:\n<source_text>\n${text}\n</source_text>\n\n2. The target language for translation is:\n<target_language>\n${language}\n</target_language>\n\n3. Translate the source text into the target language. Ensure that you maintain the original meaning, tone, and style as closely as possible while adapting to the linguistic and cultural norms of the target language.\n\n4. Return only the translated text, without any additional comments, explanations, or metadata. Do not include the original text or any other information in your response.\n`;\n}\n\nexport default translate;\n", "function changeTone(text: string, type: string): string {\n const prompt = `\nYou will be given a piece of text and a desired tone. Your task is to rewrite the text to match the desired tone while preserving the original meaning and key information. Here's how to proceed:\n\nFirst, you will be provided with the original text:\n<original_text>\n${text}\n</original_text>\n\nThe desired tone for the rewritten text is:\n<desired_tone>\n${type}\n</desired_tone>\n\nTo change the tone of the text:\n1. Analyze the current tone and style of the original text.\n2. Identify the key information and main ideas in the original text.\n3. Consider the characteristics of the desired tone (e.g., formal, casual, humorous, professional, etc.).\n4. Rewrite the text, adapting the language, vocabulary, and sentence structure to match the desired tone while maintaining the original meaning and key information.\n5. Ensure that the rewritten text flows naturally and coherently.\n6. Only return the rewritten text without any additional commentary, tags or explanation.\n\nNow, rewrite the text to match the desired tone. Your response should contain only the rewritten text, without any additional explanations or comments. Do not use any tags in your response.\n`;\n\n return prompt;\n}\n\nexport default changeTone;\n", "function changeTextTo(text: string, customPrompt: string): string {\n return `\nYou will be given an original text and a custom prompt addition that specifies how to change the text. Your task is to modify the original text according to the prompt and return only the new, modified text.\n\nHere is the original text:\n<original_text>\n${text}\n</original_text>\n\nThe custom prompt addition is:\n<change_text_to>\n${customPrompt}\n</change_text_to>\n\nPlease modify the original text according to the \"Change Text to...\" prompt. Only return the new, modified text without any additional commentary or explanation. Your entire response should be the modified text itself, with no other content.\n`;\n}\n\nexport default changeTextTo;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport {\n Middleware,\n Provider,\n QuickAction\n} from '@imgly/plugin-ai-generation-web';\nimport Anthropic from '@anthropic-ai/sdk';\nimport sendPrompt from './sendPrompt';\nimport improve from './prompts/improve';\nimport shorter from './prompts/shorter';\nimport longer from './prompts/longer';\nimport fix from './prompts/fix';\nimport generateTextForSpeech from './prompts/generateTextForSpeech';\nimport translate, { LANGUAGES, LOCALES } from './prompts/translate';\nimport changeTone from './prompts/changeTone';\nimport changeTextTo from './prompts/changeTextTo';\n\ntype ProviderConfiguration = {\n proxyUrl: string;\n debug?: boolean;\n middleware?: Middleware<AnthropicInput, AnthropicOutput>[];\n};\n\ntype AnthropicInput = {\n prompt: string;\n temperature?: number;\n maxTokens?: number;\n\n blockId?: number;\n initialText?: string;\n};\n\ntype AnthropicOutput = {\n kind: 'text';\n text: string;\n};\n\nexport function AnthropicProvider(\n config: ProviderConfiguration\n): (context: {\n cesdk: CreativeEditorSDK;\n}) => Promise<Provider<'text', AnthropicInput, AnthropicOutput>> {\n return (context: { cesdk: CreativeEditorSDK }) => {\n context.cesdk.i18n.setTranslations({\n en: {\n ...Object.entries(LANGUAGES).reduce(\n (acc: Record<string, string>, [locale, langauge]) => {\n acc[`ly.img.ai.inference.translate.type.${locale}`] = langauge;\n return acc;\n },\n {}\n )\n }\n });\n\n let anthropic: Anthropic | null = null;\n const provider: Provider<'text', AnthropicInput, AnthropicOutput> = {\n kind: 'text',\n id: 'anthropic',\n initialize: async () => {\n anthropic = new Anthropic({\n dangerouslyAllowBrowser: true,\n baseURL: config.proxyUrl,\n // Will be injected by the proxy\n apiKey: null,\n authToken: null\n });\n },\n input: {\n quickActions: {\n actions: [\n ImproveQuickAction(),\n FixQuickAction(),\n ShorterQuickAction(),\n LongerQuickAction(),\n SpeechQuickAction(),\n ChangeToneQuickAction(),\n TranslateQuickAction(),\n ChangeTextToQuickAction()\n ]\n }\n },\n output: {\n middleware: config.middleware,\n generate: async (\n { prompt, blockId },\n { engine, abortSignal }\n ): Promise<AsyncGenerator<AnthropicOutput, AnthropicOutput>> => {\n if (anthropic == null)\n throw new Error('Anthropic SDK is not initialized');\n\n if (\n blockId != null &&\n engine.block.getType(blockId) !== '//ly.img.ubq/text'\n ) {\n throw new Error(\n 'If a block is provided to this generation, it most be a text block'\n );\n }\n\n if (config.debug)\n // eslint-disable-next-line no-console\n console.log(\n 'Sending prompt to Anthropic:',\n JSON.stringify(prompt, undefined, 2)\n );\n\n const stream = await sendPrompt(\n anthropic,\n {\n proxyUrl: config.proxyUrl\n },\n prompt,\n abortSignal\n );\n\n // Create a new AsyncGenerator that yields AnthropicOutput objects\n async function* outputGenerator(): AsyncGenerator<\n AnthropicOutput,\n AnthropicOutput\n > {\n let inferredText: string = '';\n for await (const chunk of stream) {\n if (abortSignal.aborted) {\n break;\n }\n inferredText += chunk;\n yield {\n kind: 'text',\n text: inferredText\n };\n }\n // Return the final result\n return {\n kind: 'text',\n text: inferredText\n };\n }\n\n return outputGenerator();\n }\n }\n };\n\n return Promise.resolve(provider);\n };\n}\n\ntype Parameter = {\n id: string;\n label: string;\n icon?: string;\n};\n\n// Define a type that can handle different prompt function signatures\ntype PromptFunction =\n | ((text: string) => string)\n | ((text: string, param: string) => string)\n | ((text: string, param: any) => string);\n\ntype QuickActionOptions = {\n id: string;\n label: string;\n icon: string;\n promptFn: PromptFunction;\n parameters?: Parameter[];\n // Optional custom renderExpanded function for complex quick actions\n renderExpanded?: QuickAction<\n AnthropicInput,\n AnthropicOutput\n >['renderExpanded'];\n};\n\n/**\n * Creates a Quick Action for text operations\n * Supports both simple actions and ones with parameter selection via popover menus\n */\nfunction createTextQuickAction(\n options: QuickActionOptions\n): QuickAction<AnthropicInput, AnthropicOutput> {\n const { id, label, icon, promptFn, parameters, renderExpanded } = options;\n\n // Common enable function for all quick actions\n const enableFn = ({ engine }: { engine: any }) => {\n const blockIds = engine.block.findAllSelected();\n if (blockIds == null || blockIds.length !== 1) return false;\n\n const [blockId] = blockIds;\n return engine.block.getType(blockId) === '//ly.img.ubq/text';\n };\n\n // Base configuration shared by all types of quick actions\n type BaseQuickAction = Pick<\n QuickAction<AnthropicInput, AnthropicOutput>,\n 'id' | 'version' | 'confirmation' | 'enable'\n >;\n\n const baseConfig: BaseQuickAction = {\n id,\n version: '1',\n confirmation: true,\n enable: enableFn\n };\n\n // If a custom renderExpanded function is provided, create an expandable quick action\n if (renderExpanded) {\n return {\n ...baseConfig,\n render: ({ builder }, { toggleExpand }) => {\n builder.Button(`${id}.button`, {\n label,\n icon,\n labelAlignment: 'left',\n variant: 'plain',\n onClick: toggleExpand\n });\n },\n renderExpanded\n };\n }\n\n // For simple actions without parameters\n if (!parameters || parameters.length === 0) {\n return {\n ...baseConfig,\n render: ({ builder, engine }, { generate, closeMenu }) => {\n builder.Button(id, {\n label,\n icon,\n labelAlignment: 'left',\n variant: 'plain',\n onClick: () => {\n closeMenu();\n const [blockId] = engine.block.findAllSelected();\n const initialText = engine.block.getString(blockId, 'text/text');\n\n // Type assertion to handle the simpler function signature\n const simpleFn = promptFn as (text: string) => string;\n generate({\n prompt: simpleFn(initialText),\n blockId,\n initialText\n });\n }\n });\n }\n };\n }\n\n // For actions with parameters displayed in a popover menu\n return {\n ...baseConfig,\n render: ({ builder, engine, experimental }, { generate, closeMenu }) => {\n experimental.builder.Popover(`${id}.popover`, {\n label,\n icon,\n labelAlignment: 'left',\n variant: 'plain',\n trailingIcon: '@imgly/ChevronRight',\n placement: 'right',\n children: () => {\n builder.Section(`${id}.popover.section`, {\n children: () => {\n experimental.builder.Menu(`${id}.popover.menu`, {\n children: () => {\n parameters.forEach((param) => {\n builder.Button(`${id}.popover.menu.${param.id}`, {\n label: param.label,\n icon: param.icon,\n labelAlignment: 'left',\n variant: 'plain',\n onClick: () => {\n closeMenu();\n const [blockId] = engine.block.findAllSelected();\n const initialText = engine.block.getString(\n blockId,\n 'text/text'\n );\n\n // Type assertion to handle the parameterized function signature\n const paramFn = promptFn as (\n text: string,\n param: any\n ) => string;\n generate({\n prompt: paramFn(initialText, param.id),\n blockId,\n initialText\n });\n }\n });\n });\n }\n });\n }\n });\n }\n });\n }\n };\n}\n\nfunction ImproveQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'improve',\n label: 'Improve',\n icon: '@imgly/MagicWand',\n promptFn: improve\n });\n}\n\nfunction ShorterQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'shorter',\n label: 'Make Shorter',\n icon: '@imgly/TextShorter',\n promptFn: shorter\n });\n}\n\nfunction LongerQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'longer',\n label: 'Make Longer',\n icon: '@imgly/TextLonger',\n promptFn: longer\n });\n}\n\nfunction FixQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'fix',\n label: 'Fix Spelling & Grammar',\n icon: '@imgly/CheckmarkAll',\n promptFn: fix\n });\n}\n\nfunction SpeechQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'speech',\n label: 'Generate Speech Text',\n icon: '@imgly/Microphone',\n promptFn: generateTextForSpeech\n });\n}\n\nconst TONE_TYPES = [\n 'professional',\n 'casual',\n 'friendly',\n 'serious',\n 'humorous',\n 'optimistic'\n];\n\nfunction ChangeToneQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'changeTone',\n label: 'Change Tone',\n icon: '@imgly/Microphone',\n promptFn: changeTone,\n parameters: TONE_TYPES.map((tone) => ({\n id: tone,\n label: tone.charAt(0).toUpperCase() + tone.slice(1)\n }))\n });\n}\n\nfunction TranslateQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'translate',\n label: 'Translate',\n icon: '@imgly/Language',\n promptFn: translate,\n parameters: LOCALES.map((locale) => ({\n id: locale,\n label: LANGUAGES[locale]\n }))\n });\n}\n\nfunction ChangeTextToQuickAction(): QuickAction<\n AnthropicInput,\n AnthropicOutput\n> {\n return createTextQuickAction({\n id: 'changeTextTo',\n label: 'Change Text to...',\n icon: '@imgly/Rename',\n promptFn: changeTextTo,\n renderExpanded: (\n { builder, engine, experimental, state },\n { generate, toggleExpand }\n ) => {\n const customPromptState = state('changeTextTo.prompt', '');\n\n builder.TextArea('changeTextTo.textarea', {\n inputLabel: 'Change text to...',\n ...customPromptState\n });\n\n builder.Separator('changeTextTo.separator');\n\n experimental.builder.ButtonRow('changeTextTo.footer', {\n justifyContent: 'space-between',\n children: () => {\n builder.Button('changeTextTo.footer.cancel', {\n label: 'Back',\n icon: '@imgly/ChevronLeft',\n onClick: toggleExpand\n });\n\n builder.Button('changeTextTo.footer.apply', {\n label: 'Rewrite',\n icon: '@imgly/MagicWand',\n color: 'accent',\n onClick: () => {\n const customPrompt = customPromptState.value;\n if (!customPrompt) return;\n\n const [blockId] = engine.block.findAllSelected();\n const initialText = engine.block.getString(blockId, 'text/text');\n\n generate({\n prompt: changeTextTo(initialText, customPrompt),\n blockId,\n initialText\n });\n\n toggleExpand();\n }\n });\n }\n });\n }\n });\n}\n", "import { AnthropicProvider } from './AnthropicProvider';\n\nconst Anthropic = {\n AnthropicProvider\n};\n\nexport default Anthropic;\n"],
|
|
5
|
-
"mappings": "AAAO,IAAMA,EAAU,SC0BhB,IAAIC,GAAO,GACPC,EACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GAEL,SAAUC,GAASC,EAAcC,EAA6B,CAAE,KAAM,EAAK,EAAE,CACjF,GAAIhB,GACF,MAAM,IAAI,MACR,8CAA8Ce,EAAM,IAAI,2DAA2D,EAGvH,GAAId,EACF,MAAM,IAAI,MACR,2CAA2Cc,EAAM,IAAI,+CAA+Cd,CAAI,KAAK,EAGjHD,GAAOgB,EAAQ,K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,eAAgB,gBAChB,SAAU,IAAM,CACdL,EAAQ,OAAO,6BAA8B,CAC3C,MAAO,OACP,KAAM,qBACN,QAASC,CACX,CAAC,EAEDD,EAAQ,OAAO,4BAA6B,CAC1C,MAAO,UACP,KAAM,mBACN,MAAO,SACP,QAAS,IAAM,CACb,IAAMoB,EAAeD,EAAkB,MACvC,GAAI,CAACC,EAAc,OAEnB,GAAM,CAACtC,CAAO,EAAIC,EAAO,MAAM,gBAAgB,EACzCqB,EAAcrB,EAAO,MAAM,UAAUD,EAAS,WAAW,EAE/DoB,EAAS,CACP,OAAQe,GAAab,EAAagB,CAAY,EAC9C,QAAAtC,EACA,YAAAsB,CACF,CAAC,EAEDH,EAAa,CACf,CACF,CAAC,CACH,CACF,CAAC,CACH,CACF,CAAC,CACH,CCnbA,IAAMoB,GAAY,CAChB,kBAAAC,EACF,EAEOC,GAAQF",
|
|
4
|
+
"sourcesContent": ["export const VERSION = '0.39.0'; // x-release-please-version\n", "/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport { type RequestOptions } from \"../core.js\";\n\nexport interface Shims {\n kind: string;\n fetch: any;\n Request: any;\n Response: any;\n Headers: any;\n FormData: any;\n Blob: any;\n File: any;\n ReadableStream: any;\n getMultipartRequestOptions: <T = Record<string, unknown>>(\n form: Shims['FormData'],\n opts: RequestOptions<T>,\n ) => Promise<RequestOptions<T>>;\n getDefaultAgent: (url: string) => any;\n fileFromPath:\n | ((path: string, filename?: string, options?: {}) => Promise<Shims['File']>)\n | ((path: string, options?: {}) => Promise<Shims['File']>);\n isFsReadStream: (value: any) => boolean;\n}\n\nexport let auto = false;\nexport let kind: Shims['kind'] | undefined = undefined;\nexport let fetch: Shims['fetch'] | undefined = undefined;\nexport let Request: Shims['Request'] | undefined = undefined;\nexport let Response: Shims['Response'] | undefined = undefined;\nexport let Headers: Shims['Headers'] | undefined = undefined;\nexport let FormData: Shims['FormData'] | undefined = undefined;\nexport let Blob: Shims['Blob'] | undefined = undefined;\nexport let File: Shims['File'] | undefined = undefined;\nexport let ReadableStream: Shims['ReadableStream'] | undefined = undefined;\nexport let getMultipartRequestOptions: Shims['getMultipartRequestOptions'] | undefined = undefined;\nexport let getDefaultAgent: Shims['getDefaultAgent'] | undefined = undefined;\nexport let fileFromPath: Shims['fileFromPath'] | undefined = undefined;\nexport let isFsReadStream: Shims['isFsReadStream'] | undefined = undefined;\n\nexport function setShims(shims: Shims, options: { auto: boolean } = { auto: false }) {\n if (auto) {\n throw new Error(\n `you must \\`import '@anthropic-ai/sdk/shims/${shims.kind}'\\` before importing anything else from @anthropic-ai/sdk`,\n );\n }\n if (kind) {\n throw new Error(\n `can't \\`import '@anthropic-ai/sdk/shims/${shims.kind}'\\` after \\`import '@anthropic-ai/sdk/shims/${kind}'\\``,\n );\n }\n auto = options.auto;\n kind = shims.kind;\n fetch = shims.fetch;\n Request = shims.Request;\n Response = shims.Response;\n Headers = shims.Headers;\n FormData = shims.FormData;\n Blob = shims.Blob;\n File = shims.File;\n ReadableStream = shims.ReadableStream;\n getMultipartRequestOptions = shims.getMultipartRequestOptions;\n getDefaultAgent = shims.getDefaultAgent;\n fileFromPath = shims.fileFromPath;\n isFsReadStream = shims.isFsReadStream;\n}\n", "/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nexport class MultipartBody {\n constructor(public body: any) {}\n get [Symbol.toStringTag](): string {\n return 'MultipartBody';\n }\n}\n", "/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport { MultipartBody } from \"./MultipartBody.js\";\nimport { type RequestOptions } from \"../core.js\";\nimport { type Shims } from \"./registry.js\";\n\nexport function getRuntime({ manuallyImported }: { manuallyImported?: boolean } = {}): Shims {\n const recommendation =\n manuallyImported ?\n `You may need to use polyfills`\n : `Add one of these imports before your first \\`import \u2026 from '@anthropic-ai/sdk'\\`:\n- \\`import '@anthropic-ai/sdk/shims/node'\\` (if you're running on Node)\n- \\`import '@anthropic-ai/sdk/shims/web'\\` (otherwise)\n`;\n\n let _fetch, _Request, _Response, _Headers;\n try {\n // @ts-ignore\n _fetch = fetch;\n // @ts-ignore\n _Request = Request;\n // @ts-ignore\n _Response = Response;\n // @ts-ignore\n _Headers = Headers;\n } catch (error) {\n throw new Error(\n `this environment is missing the following Web Fetch API type: ${\n (error as any).message\n }. ${recommendation}`,\n );\n }\n\n return {\n kind: 'web',\n fetch: _fetch,\n Request: _Request,\n Response: _Response,\n Headers: _Headers,\n FormData:\n // @ts-ignore\n typeof FormData !== 'undefined' ? FormData : (\n class FormData {\n // @ts-ignore\n constructor() {\n throw new Error(\n `file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`,\n );\n }\n }\n ),\n Blob:\n typeof Blob !== 'undefined' ? Blob : (\n class Blob {\n constructor() {\n throw new Error(\n `file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`,\n );\n }\n }\n ),\n File:\n // @ts-ignore\n typeof File !== 'undefined' ? File : (\n class File {\n // @ts-ignore\n constructor() {\n throw new Error(\n `file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`,\n );\n }\n }\n ),\n ReadableStream:\n // @ts-ignore\n typeof ReadableStream !== 'undefined' ? ReadableStream : (\n class ReadableStream {\n // @ts-ignore\n constructor() {\n throw new Error(\n `streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`,\n );\n }\n }\n ),\n getMultipartRequestOptions: async <T = Record<string, unknown>>(\n // @ts-ignore\n form: FormData,\n opts: RequestOptions<T>,\n ): Promise<RequestOptions<T>> => ({\n ...opts,\n body: new MultipartBody(form) as any,\n }),\n getDefaultAgent: (url: string) => undefined,\n fileFromPath: () => {\n throw new Error(\n 'The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads',\n );\n },\n isFsReadStream: (value: any) => false,\n };\n}\n", "/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport * as shims from './registry.mjs';\nimport * as auto from '@anthropic-ai/sdk/_shims/auto/runtime';\nif (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true });\nexport * from './registry.mjs';\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { castToError, Headers } from \"./core.js\";\n\nexport class AnthropicError extends Error {}\n\nexport class APIError<\n TStatus extends number | undefined = number | undefined,\n THeaders extends Headers | undefined = Headers | undefined,\n TError extends Object | undefined = Object | undefined,\n> extends AnthropicError {\n /** HTTP status for the response that caused the error */\n readonly status: TStatus;\n /** HTTP headers for the response that caused the error */\n readonly headers: THeaders;\n /** JSON body of the response that caused the error */\n readonly error: TError;\n\n readonly request_id: string | null | undefined;\n\n constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) {\n super(`${APIError.makeMessage(status, error, message)}`);\n this.status = status;\n this.headers = headers;\n this.request_id = headers?.['request-id'];\n this.error = error;\n }\n\n private static makeMessage(status: number | undefined, error: any, message: string | undefined) {\n const msg =\n error?.message ?\n typeof error.message === 'string' ?\n error.message\n : JSON.stringify(error.message)\n : error ? JSON.stringify(error)\n : message;\n\n if (status && msg) {\n return `${status} ${msg}`;\n }\n if (status) {\n return `${status} status code (no body)`;\n }\n if (msg) {\n return msg;\n }\n return '(no status code or body)';\n }\n\n static generate(\n status: number | undefined,\n errorResponse: Object | undefined,\n message: string | undefined,\n headers: Headers | undefined,\n ): APIError {\n if (!status || !headers) {\n return new APIConnectionError({ message, cause: castToError(errorResponse) });\n }\n\n const error = errorResponse as Record<string, any>;\n\n if (status === 400) {\n return new BadRequestError(status, error, message, headers);\n }\n\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers);\n }\n\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers);\n }\n\n if (status === 404) {\n return new NotFoundError(status, error, message, headers);\n }\n\n if (status === 409) {\n return new ConflictError(status, error, message, headers);\n }\n\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers);\n }\n\n if (status === 429) {\n return new RateLimitError(status, error, message, headers);\n }\n\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers);\n }\n\n return new APIError(status, error, message, headers);\n }\n}\n\nexport class APIUserAbortError extends APIError<undefined, undefined, undefined> {\n constructor({ message }: { message?: string } = {}) {\n super(undefined, undefined, message || 'Request was aborted.', undefined);\n }\n}\n\nexport class APIConnectionError extends APIError<undefined, undefined, undefined> {\n constructor({ message, cause }: { message?: string | undefined; cause?: Error | undefined }) {\n super(undefined, undefined, message || 'Connection error.', undefined);\n // in some environments the 'cause' property is already declared\n // @ts-ignore\n if (cause) this.cause = cause;\n }\n}\n\nexport class APIConnectionTimeoutError extends APIConnectionError {\n constructor({ message }: { message?: string } = {}) {\n super({ message: message ?? 'Request timed out.' });\n }\n}\n\nexport class BadRequestError extends APIError<400, Headers> {}\n\nexport class AuthenticationError extends APIError<401, Headers> {}\n\nexport class PermissionDeniedError extends APIError<403, Headers> {}\n\nexport class NotFoundError extends APIError<404, Headers> {}\n\nexport class ConflictError extends APIError<409, Headers> {}\n\nexport class UnprocessableEntityError extends APIError<422, Headers> {}\n\nexport class RateLimitError extends APIError<429, Headers> {}\n\nexport class InternalServerError extends APIError<number, Headers> {}\n", "import { AnthropicError } from \"../../error.js\";\n\nexport type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;\n\n/**\n * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally\n * reading lines from text.\n *\n * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258\n */\nexport class LineDecoder {\n // prettier-ignore\n static NEWLINE_CHARS = new Set(['\\n', '\\r']);\n static NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\n\n buffer: Uint8Array;\n #carriageReturnIndex: number | null;\n textDecoder: any; // TextDecoder found in browsers; not typed to avoid pulling in either \"dom\" or \"node\" types.\n\n constructor() {\n this.buffer = new Uint8Array();\n this.#carriageReturnIndex = null;\n }\n\n decode(chunk: Bytes): string[] {\n if (chunk == null) {\n return [];\n }\n\n const binaryChunk =\n chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? new TextEncoder().encode(chunk)\n : chunk;\n\n let newData = new Uint8Array(this.buffer.length + binaryChunk.length);\n newData.set(this.buffer);\n newData.set(binaryChunk, this.buffer.length);\n this.buffer = newData;\n\n const lines: string[] = [];\n let patternIndex;\n while ((patternIndex = findNewlineIndex(this.buffer, this.#carriageReturnIndex)) != null) {\n if (patternIndex.carriage && this.#carriageReturnIndex == null) {\n // skip until we either get a corresponding `\\n`, a new `\\r` or nothing\n this.#carriageReturnIndex = patternIndex.index;\n continue;\n }\n\n // we got double \\r or \\rtext\\n\n if (\n this.#carriageReturnIndex != null &&\n (patternIndex.index !== this.#carriageReturnIndex + 1 || patternIndex.carriage)\n ) {\n lines.push(this.decodeText(this.buffer.slice(0, this.#carriageReturnIndex - 1)));\n this.buffer = this.buffer.slice(this.#carriageReturnIndex);\n this.#carriageReturnIndex = null;\n continue;\n }\n\n const endIndex =\n this.#carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;\n\n const line = this.decodeText(this.buffer.slice(0, endIndex));\n lines.push(line);\n\n this.buffer = this.buffer.slice(patternIndex.index);\n this.#carriageReturnIndex = null;\n }\n\n return lines;\n }\n\n decodeText(bytes: Bytes): string {\n if (bytes == null) return '';\n if (typeof bytes === 'string') return bytes;\n\n // Node:\n if (typeof Buffer !== 'undefined') {\n if (bytes instanceof Buffer) {\n return bytes.toString();\n }\n if (bytes instanceof Uint8Array) {\n return Buffer.from(bytes).toString();\n }\n\n throw new AnthropicError(\n `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global \"Buffer\" defined, which this library assumes to be Node. Please report this error.`,\n );\n }\n\n // Browser\n if (typeof TextDecoder !== 'undefined') {\n if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {\n this.textDecoder ??= new TextDecoder('utf8');\n return this.textDecoder.decode(bytes);\n }\n\n throw new AnthropicError(\n `Unexpected: received non-Uint8Array/ArrayBuffer (${\n (bytes as any).constructor.name\n }) in a web platform. Please report this error.`,\n );\n }\n\n throw new AnthropicError(\n `Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`,\n );\n }\n\n flush(): string[] {\n if (!this.buffer.length) {\n return [];\n }\n return this.decode('\\n');\n }\n}\n\n/**\n * This function searches the buffer for the end patterns, (\\r or \\n)\n * and returns an object with the index preceding the matched newline and the\n * index after the newline char. `null` is returned if no new line is found.\n *\n * ```ts\n * findNewLineIndex('abc\\ndef') -> { preceding: 2, index: 3 }\n * ```\n */\nfunction findNewlineIndex(\n buffer: Uint8Array,\n startIndex: number | null,\n): { preceding: number; index: number; carriage: boolean } | null {\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n\n for (let i = startIndex ?? 0; i < buffer.length; i++) {\n if (buffer[i] === newline) {\n return { preceding: i, index: i + 1, carriage: false };\n }\n\n if (buffer[i] === carriage) {\n return { preceding: i, index: i + 1, carriage: true };\n }\n }\n\n return null;\n}\n\nexport function findDoubleNewlineIndex(buffer: Uint8Array): number {\n // This function searches the buffer for the end patterns (\\r\\r, \\n\\n, \\r\\n\\r\\n)\n // and returns the index right after the first occurrence of any pattern,\n // or -1 if none of the patterns are found.\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n\n for (let i = 0; i < buffer.length - 1; i++) {\n if (buffer[i] === newline && buffer[i + 1] === newline) {\n // \\n\\n\n return i + 2;\n }\n if (buffer[i] === carriage && buffer[i + 1] === carriage) {\n // \\r\\r\n return i + 2;\n }\n if (\n buffer[i] === carriage &&\n buffer[i + 1] === newline &&\n i + 3 < buffer.length &&\n buffer[i + 2] === carriage &&\n buffer[i + 3] === newline\n ) {\n // \\r\\n\\r\\n\n return i + 4;\n }\n }\n\n return -1;\n}\n", "/**\n * Most browsers don't yet have async iterable support for ReadableStream,\n * and Node has a very different way of reading bytes from its \"ReadableStream\".\n *\n * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nexport function ReadableStreamToAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {\n if (stream[Symbol.asyncIterator]) return stream;\n\n const reader = stream.getReader();\n return {\n async next() {\n try {\n const result = await reader.read();\n if (result?.done) reader.releaseLock(); // release lock when stream becomes closed\n return result;\n } catch (e) {\n reader.releaseLock(); // release lock when stream becomes errored\n throw e;\n }\n },\n async return() {\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n return { done: true, value: undefined };\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n", "import { ReadableStream, type Response } from \"./_shims/index.js\";\nimport { AnthropicError } from \"./error.js\";\nimport { findDoubleNewlineIndex, LineDecoder } from \"./internal/decoders/line.js\";\nimport { ReadableStreamToAsyncIterable } from \"./internal/stream-utils.js\";\n\nimport { createResponseHeaders } from \"./core.js\";\nimport { APIError } from \"./error.js\";\n\ntype Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;\n\nexport type ServerSentEvent = {\n event: string | null;\n data: string;\n raw: string[];\n};\n\nexport class Stream<Item> implements AsyncIterable<Item> {\n controller: AbortController;\n\n constructor(\n private iterator: () => AsyncIterator<Item>,\n controller: AbortController,\n ) {\n this.controller = controller;\n }\n\n static fromSSEResponse<Item>(response: Response, controller: AbortController): Stream<Item> {\n let consumed = false;\n\n async function* iterator(): AsyncIterator<Item, any, undefined> {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const sse of _iterSSEMessages(response, controller)) {\n if (sse.event === 'completion') {\n try {\n yield JSON.parse(sse.data);\n } catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n }\n\n if (\n sse.event === 'message_start' ||\n sse.event === 'message_delta' ||\n sse.event === 'message_stop' ||\n sse.event === 'content_block_start' ||\n sse.event === 'content_block_delta' ||\n sse.event === 'content_block_stop'\n ) {\n try {\n yield JSON.parse(sse.data);\n } catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n }\n\n if (sse.event === 'ping') {\n continue;\n }\n\n if (sse.event === 'error') {\n throw APIError.generate(\n undefined,\n `SSE Error: ${sse.data}`,\n sse.data,\n createResponseHeaders(response.headers),\n );\n }\n }\n done = true;\n } catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError') return;\n throw e;\n } finally {\n // If the user `break`s, abort the ongoing request.\n if (!done) controller.abort();\n }\n }\n\n return new Stream(iterator, controller);\n }\n\n /**\n * Generates a Stream from a newline-separated ReadableStream\n * where each item is a JSON value.\n */\n static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController): Stream<Item> {\n let consumed = false;\n\n async function* iterLines(): AsyncGenerator<string, void, unknown> {\n const lineDecoder = new LineDecoder();\n\n const iter = ReadableStreamToAsyncIterable<Bytes>(readableStream);\n for await (const chunk of iter) {\n for (const line of lineDecoder.decode(chunk)) {\n yield line;\n }\n }\n\n for (const line of lineDecoder.flush()) {\n yield line;\n }\n }\n\n async function* iterator(): AsyncIterator<Item, any, undefined> {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const line of iterLines()) {\n if (done) continue;\n if (line) yield JSON.parse(line);\n }\n done = true;\n } catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError') return;\n throw e;\n } finally {\n // If the user `break`s, abort the ongoing request.\n if (!done) controller.abort();\n }\n }\n\n return new Stream(iterator, controller);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Item> {\n return this.iterator();\n }\n\n /**\n * Splits the stream into two streams which can be\n * independently read from at different speeds.\n */\n tee(): [Stream<Item>, Stream<Item>] {\n const left: Array<Promise<IteratorResult<Item>>> = [];\n const right: Array<Promise<IteratorResult<Item>>> = [];\n const iterator = this.iterator();\n\n const teeIterator = (queue: Array<Promise<IteratorResult<Item>>>): AsyncIterator<Item> => {\n return {\n next: () => {\n if (queue.length === 0) {\n const result = iterator.next();\n left.push(result);\n right.push(result);\n }\n return queue.shift()!;\n },\n };\n };\n\n return [\n new Stream(() => teeIterator(left), this.controller),\n new Stream(() => teeIterator(right), this.controller),\n ];\n }\n\n /**\n * Converts this stream to a newline-separated ReadableStream of\n * JSON stringified values in the stream\n * which can be turned back into a Stream with `Stream.fromReadableStream()`.\n */\n toReadableStream(): ReadableStream {\n const self = this;\n let iter: AsyncIterator<Item>;\n const encoder = new TextEncoder();\n\n return new ReadableStream({\n async start() {\n iter = self[Symbol.asyncIterator]();\n },\n async pull(ctrl: any) {\n try {\n const { value, done } = await iter.next();\n if (done) return ctrl.close();\n\n const bytes = encoder.encode(JSON.stringify(value) + '\\n');\n\n ctrl.enqueue(bytes);\n } catch (err) {\n ctrl.error(err);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n }\n}\n\nexport async function* _iterSSEMessages(\n response: Response,\n controller: AbortController,\n): AsyncGenerator<ServerSentEvent, void, unknown> {\n if (!response.body) {\n controller.abort();\n throw new AnthropicError(`Attempted to iterate over a response with no body`);\n }\n\n const sseDecoder = new SSEDecoder();\n const lineDecoder = new LineDecoder();\n\n const iter = ReadableStreamToAsyncIterable<Bytes>(response.body);\n for await (const sseChunk of iterSSEChunks(iter)) {\n for (const line of lineDecoder.decode(sseChunk)) {\n const sse = sseDecoder.decode(line);\n if (sse) yield sse;\n }\n }\n\n for (const line of lineDecoder.flush()) {\n const sse = sseDecoder.decode(line);\n if (sse) yield sse;\n }\n}\n\n/**\n * Given an async iterable iterator, iterates over it and yields full\n * SSE chunks, i.e. yields when a double new-line is encountered.\n */\nasync function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> {\n let data = new Uint8Array();\n\n for await (const chunk of iterator) {\n if (chunk == null) {\n continue;\n }\n\n const binaryChunk =\n chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? new TextEncoder().encode(chunk)\n : chunk;\n\n let newData = new Uint8Array(data.length + binaryChunk.length);\n newData.set(data);\n newData.set(binaryChunk, data.length);\n data = newData;\n\n let patternIndex;\n while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {\n yield data.slice(0, patternIndex);\n data = data.slice(patternIndex);\n }\n }\n\n if (data.length > 0) {\n yield data;\n }\n}\n\nclass SSEDecoder {\n private data: string[];\n private event: string | null;\n private chunks: string[];\n\n constructor() {\n this.event = null;\n this.data = [];\n this.chunks = [];\n }\n\n decode(line: string) {\n if (line.endsWith('\\r')) {\n line = line.substring(0, line.length - 1);\n }\n\n if (!line) {\n // empty line and we didn't previously encounter any messages\n if (!this.event && !this.data.length) return null;\n\n const sse: ServerSentEvent = {\n event: this.event,\n data: this.data.join('\\n'),\n raw: this.chunks,\n };\n\n this.event = null;\n this.data = [];\n this.chunks = [];\n\n return sse;\n }\n\n this.chunks.push(line);\n\n if (line.startsWith(':')) {\n return null;\n }\n\n let [fieldname, _, value] = partition(line, ':');\n\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n\n if (fieldname === 'event') {\n this.event = value;\n } else if (fieldname === 'data') {\n this.data.push(value);\n }\n\n return null;\n }\n}\n\nfunction partition(str: string, delimiter: string): [string, string, string] {\n const index = str.indexOf(delimiter);\n if (index !== -1) {\n return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\n }\n\n return [str, '', ''];\n}\n", "import { type RequestOptions } from \"./core.js\";\nimport {\n FormData,\n File,\n type Blob,\n type FilePropertyBag,\n getMultipartRequestOptions,\n type FsReadStream,\n isFsReadStream,\n} from \"./_shims/index.js\";\nimport { MultipartBody } from \"./_shims/MultipartBody.js\";\nexport { fileFromPath } from \"./_shims/index.js\";\n\ntype BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView;\nexport type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | Uint8Array | DataView;\n\n/**\n * Typically, this is a native \"File\" class.\n *\n * We provide the {@link toFile} utility to convert a variety of objects\n * into the File class.\n *\n * For convenience, you can also pass a fetch Response, or in Node,\n * the result of fs.createReadStream().\n */\nexport type Uploadable = FileLike | ResponseLike | FsReadStream;\n\n/**\n * Intended to match web.Blob, node.Blob, node-fetch.Blob, etc.\n */\nexport interface BlobLike {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */\n readonly size: number;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */\n readonly type: string;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */\n text(): Promise<string>;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */\n slice(start?: number, end?: number): BlobLike;\n // unfortunately @types/node-fetch@^2.6.4 doesn't type the arrayBuffer method\n}\n\n/**\n * Intended to match web.File, node.File, node-fetch.File, etc.\n */\nexport interface FileLike extends BlobLike {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */\n readonly lastModified: number;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */\n readonly name: string;\n}\n\n/**\n * Intended to match web.Response, node.Response, node-fetch.Response, etc.\n */\nexport interface ResponseLike {\n url: string;\n blob(): Promise<BlobLike>;\n}\n\nexport const isResponseLike = (value: any): value is ResponseLike =>\n value != null &&\n typeof value === 'object' &&\n typeof value.url === 'string' &&\n typeof value.blob === 'function';\n\nexport const isFileLike = (value: any): value is FileLike =>\n value != null &&\n typeof value === 'object' &&\n typeof value.name === 'string' &&\n typeof value.lastModified === 'number' &&\n isBlobLike(value);\n\n/**\n * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check\n * adds the arrayBuffer() method type because it is available and used at runtime\n */\nexport const isBlobLike = (value: any): value is BlobLike & { arrayBuffer(): Promise<ArrayBuffer> } =>\n value != null &&\n typeof value === 'object' &&\n typeof value.size === 'number' &&\n typeof value.type === 'string' &&\n typeof value.text === 'function' &&\n typeof value.slice === 'function' &&\n typeof value.arrayBuffer === 'function';\n\nexport const isUploadable = (value: any): value is Uploadable => {\n return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);\n};\n\nexport type ToFileInput = Uploadable | Exclude<BlobLikePart, string> | AsyncIterable<BlobLikePart>;\n\n/**\n * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats\n * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s\n * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible\n * @param {Object=} options additional properties\n * @param {string=} options.type the MIME type of the content\n * @param {number=} options.lastModified the last modified timestamp\n * @returns a {@link File} with the given properties\n */\nexport async function toFile(\n value: ToFileInput | PromiseLike<ToFileInput>,\n name?: string | null | undefined,\n options?: FilePropertyBag | undefined,\n): Promise<FileLike> {\n // If it's a promise, resolve it.\n value = await value;\n\n // If we've been given a `File` we don't need to do anything\n if (isFileLike(value)) {\n return value;\n }\n\n if (isResponseLike(value)) {\n const blob = await value.blob();\n name ||= new URL(value.url).pathname.split(/[\\\\/]/).pop() ?? 'unknown_file';\n\n // we need to convert the `Blob` into an array buffer because the `Blob` class\n // that `node-fetch` defines is incompatible with the web standard which results\n // in `new File` interpreting it as a string instead of binary data.\n const data = isBlobLike(blob) ? [(await blob.arrayBuffer()) as any] : [blob];\n\n return new File(data, name, options);\n }\n\n const bits = await getBytes(value);\n\n name ||= getName(value) ?? 'unknown_file';\n\n if (!options?.type) {\n const type = (bits[0] as any)?.type;\n if (typeof type === 'string') {\n options = { ...options, type };\n }\n }\n\n return new File(bits, name, options);\n}\n\nasync function getBytes(value: ToFileInput): Promise<Array<BlobPart>> {\n let parts: Array<BlobPart> = [];\n if (\n typeof value === 'string' ||\n ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\n value instanceof ArrayBuffer\n ) {\n parts.push(value);\n } else if (isBlobLike(value)) {\n parts.push(await value.arrayBuffer());\n } else if (\n isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc.\n ) {\n for await (const chunk of value) {\n parts.push(chunk as BlobPart); // TODO, consider validating?\n }\n } else {\n throw new Error(\n `Unexpected data type: ${typeof value}; constructor: ${value?.constructor\n ?.name}; props: ${propsForError(value)}`,\n );\n }\n\n return parts;\n}\n\nfunction propsForError(value: any): string {\n const props = Object.getOwnPropertyNames(value);\n return `[${props.map((p) => `\"${p}\"`).join(', ')}]`;\n}\n\nfunction getName(value: any): string | undefined {\n return (\n getStringFromMaybeBuffer(value.name) ||\n getStringFromMaybeBuffer(value.filename) ||\n // For fs.ReadStream\n getStringFromMaybeBuffer(value.path)?.split(/[\\\\/]/).pop()\n );\n}\n\nconst getStringFromMaybeBuffer = (x: string | Buffer | unknown): string | undefined => {\n if (typeof x === 'string') return x;\n if (typeof Buffer !== 'undefined' && x instanceof Buffer) return String(x);\n return undefined;\n};\n\nconst isAsyncIterableIterator = (value: any): value is AsyncIterableIterator<unknown> =>\n value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';\n\nexport const isMultipartBody = (body: any): body is MultipartBody =>\n body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';\n\n/**\n * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.\n * Otherwise returns the request as is.\n */\nexport const maybeMultipartFormRequestOptions = async <T = Record<string, unknown>>(\n opts: RequestOptions<T>,\n): Promise<RequestOptions<T | MultipartBody>> => {\n if (!hasUploadableValue(opts.body)) return opts;\n\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\n\nexport const multipartFormRequestOptions = async <T = Record<string, unknown>>(\n opts: RequestOptions<T>,\n): Promise<RequestOptions<T | MultipartBody>> => {\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\n\nexport const createForm = async <T = Record<string, unknown>>(body: T | undefined): Promise<FormData> => {\n const form = new FormData();\n await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));\n return form;\n};\n\nconst hasUploadableValue = (value: unknown): boolean => {\n if (isUploadable(value)) return true;\n if (Array.isArray(value)) return value.some(hasUploadableValue);\n if (value && typeof value === 'object') {\n for (const k in value) {\n if (hasUploadableValue((value as any)[k])) return true;\n }\n }\n return false;\n};\n\nconst addFormValue = async (form: FormData, key: string, value: unknown): Promise<void> => {\n if (value === undefined) return;\n if (value == null) {\n throw new TypeError(\n `Received null for \"${key}\"; to pass null in FormData, you must use the string 'null'`,\n );\n }\n\n // TODO: make nested formats configurable\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n form.append(key, String(value));\n } else if (isUploadable(value)) {\n const file = await toFile(value);\n form.append(key, file as File);\n } else if (Array.isArray(value)) {\n await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));\n } else if (typeof value === 'object') {\n await Promise.all(\n Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)),\n );\n } else {\n throw new TypeError(\n `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`,\n );\n }\n};\n", "import { VERSION } from \"./version.js\";\nimport { Stream } from \"./streaming.js\";\nimport {\n AnthropicError,\n APIError,\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n} from \"./error.js\";\nimport {\n kind as shimsKind,\n type Readable,\n getDefaultAgent,\n type Agent,\n fetch,\n type RequestInfo,\n type RequestInit,\n type Response,\n type HeadersInit,\n} from \"./_shims/index.js\";\nexport { type Response };\nimport { BlobLike, isBlobLike, isMultipartBody } from \"./uploads.js\";\nexport {\n maybeMultipartFormRequestOptions,\n multipartFormRequestOptions,\n createForm,\n type Uploadable,\n} from \"./uploads.js\";\n\nexport type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\ntype APIResponseProps = {\n response: Response;\n options: FinalRequestOptions;\n controller: AbortController;\n};\n\nasync function defaultParseResponse<T>(props: APIResponseProps): Promise<WithRequestID<T>> {\n const { response } = props;\n if (props.options.stream) {\n debug('response', response.status, response.url, response.headers, response.body);\n\n // Note: there is an invariant here that isn't represented in the type system\n // that if you set `stream: true` the response type must also be `Stream<T>`\n\n if (props.options.__streamClass) {\n return props.options.__streamClass.fromSSEResponse(response, props.controller) as any;\n }\n\n return Stream.fromSSEResponse(response, props.controller) as any;\n }\n\n // fetch refuses to read the body when the status code is 204.\n if (response.status === 204) {\n return null as WithRequestID<T>;\n }\n\n if (props.options.__binaryResponse) {\n return response as unknown as WithRequestID<T>;\n }\n\n const contentType = response.headers.get('content-type');\n const isJSON =\n contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');\n if (isJSON) {\n const json = await response.json();\n\n debug('response', response.status, response.url, response.headers, json);\n\n return _addRequestID(json as T, response);\n }\n\n const text = await response.text();\n debug('response', response.status, response.url, response.headers, text);\n\n // TODO handle blob, arraybuffer, other content types, etc.\n return text as unknown as WithRequestID<T>;\n}\n\ntype WithRequestID<T> =\n T extends Array<any> | Response | AbstractPage<any> ? T\n : T extends Record<string, any> ? T & { _request_id?: string | null }\n : T;\n\nfunction _addRequestID<T>(value: T, response: Response): WithRequestID<T> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value as WithRequestID<T>;\n }\n\n return Object.defineProperty(value, '_request_id', {\n value: response.headers.get('request-id'),\n enumerable: false,\n }) as WithRequestID<T>;\n}\n\n/**\n * A subclass of `Promise` providing additional helper methods\n * for interacting with the SDK.\n */\nexport class APIPromise<T> extends Promise<WithRequestID<T>> {\n private parsedPromise: Promise<WithRequestID<T>> | undefined;\n\n constructor(\n private responsePromise: Promise<APIResponseProps>,\n private parseResponse: (\n props: APIResponseProps,\n ) => PromiseOrValue<WithRequestID<T>> = defaultParseResponse,\n ) {\n super((resolve) => {\n // this is maybe a bit weird but this has to be a no-op to not implicitly\n // parse the response body; instead .then, .catch, .finally are overridden\n // to parse the response\n resolve(null as any);\n });\n }\n\n _thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U> {\n return new APIPromise(this.responsePromise, async (props) =>\n _addRequestID(transform(await this.parseResponse(props), props), props.response),\n );\n }\n\n /**\n * Gets the raw `Response` instance instead of parsing the response\n * data.\n *\n * If you want to parse the response body but still get the `Response`\n * instance, you can use {@link withResponse()}.\n *\n * \uD83D\uDC4B Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n * - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n * - `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n */\n asResponse(): Promise<Response> {\n return this.responsePromise.then((p) => p.response);\n }\n\n /**\n * Gets the parsed response data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * If you just want to get the raw `Response` instance without parsing it,\n * you can use {@link asResponse()}.\n *\n * \uD83D\uDC4B Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n * - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n * - `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n */\n async withResponse(): Promise<{ data: T; response: Response; request_id: string | null | undefined }> {\n const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\n return { data, response, request_id: response.headers.get('request-id') };\n }\n\n private parse(): Promise<WithRequestID<T>> {\n if (!this.parsedPromise) {\n this.parsedPromise = this.responsePromise.then(this.parseResponse) as any as Promise<WithRequestID<T>>;\n }\n return this.parsedPromise;\n }\n\n override then<TResult1 = WithRequestID<T>, TResult2 = never>(\n onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): Promise<TResult1 | TResult2> {\n return this.parse().then(onfulfilled, onrejected);\n }\n\n override catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,\n ): Promise<WithRequestID<T> | TResult> {\n return this.parse().catch(onrejected);\n }\n\n override finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<T>> {\n return this.parse().finally(onfinally);\n }\n}\n\nexport abstract class APIClient {\n baseURL: string;\n maxRetries: number;\n timeout: number;\n httpAgent: Agent | undefined;\n\n private fetch: Fetch;\n protected idempotencyHeader?: string;\n\n constructor({\n baseURL,\n maxRetries = 2,\n timeout = 600000, // 10 minutes\n httpAgent,\n fetch: overriddenFetch,\n }: {\n baseURL: string;\n maxRetries?: number | undefined;\n timeout: number | undefined;\n httpAgent: Agent | undefined;\n fetch: Fetch | undefined;\n }) {\n this.baseURL = baseURL;\n this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);\n this.timeout = validatePositiveInteger('timeout', timeout);\n this.httpAgent = httpAgent;\n\n this.fetch = overriddenFetch ?? fetch;\n }\n\n protected authHeaders(opts: FinalRequestOptions): Headers {\n return {};\n }\n\n /**\n * Override this to add your own default headers, for example:\n *\n * {\n * ...super.defaultHeaders(),\n * Authorization: 'Bearer 123',\n * }\n */\n protected defaultHeaders(opts: FinalRequestOptions): Headers {\n return {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': this.getUserAgent(),\n ...getPlatformHeaders(),\n ...this.authHeaders(opts),\n };\n }\n\n protected abstract defaultQuery(): DefaultQuery | undefined;\n\n /**\n * Override this to add your own headers validation:\n */\n protected validateHeaders(headers: Headers, customHeaders: Headers) {}\n\n protected defaultIdempotencyKey(): string {\n return `stainless-node-retry-${uuid4()}`;\n }\n\n get<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('get', path, opts);\n }\n\n post<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('post', path, opts);\n }\n\n patch<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('patch', path, opts);\n }\n\n put<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('put', path, opts);\n }\n\n delete<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('delete', path, opts);\n }\n\n private methodRequest<Req, Rsp>(\n method: HTTPMethod,\n path: string,\n opts?: PromiseOrValue<RequestOptions<Req>>,\n ): APIPromise<Rsp> {\n return this.request(\n Promise.resolve(opts).then(async (opts) => {\n const body =\n opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer())\n : opts?.body instanceof DataView ? opts.body\n : opts?.body instanceof ArrayBuffer ? new DataView(opts.body)\n : opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)\n : opts?.body;\n return { method, path, ...opts, body };\n }),\n );\n }\n\n getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(\n path: string,\n Page: new (...args: any[]) => PageClass,\n opts?: RequestOptions<any>,\n ): PagePromise<PageClass, Item> {\n return this.requestAPIList(Page, { method: 'get', path, ...opts });\n }\n\n private calculateContentLength(body: unknown): string | null {\n if (typeof body === 'string') {\n if (typeof Buffer !== 'undefined') {\n return Buffer.byteLength(body, 'utf8').toString();\n }\n\n if (typeof TextEncoder !== 'undefined') {\n const encoder = new TextEncoder();\n const encoded = encoder.encode(body);\n return encoded.length.toString();\n }\n } else if (ArrayBuffer.isView(body)) {\n return body.byteLength.toString();\n }\n\n return null;\n }\n\n buildRequest<Req>(\n options: FinalRequestOptions<Req>,\n { retryCount = 0 }: { retryCount?: number } = {},\n ): { req: RequestInit; url: string; timeout: number } {\n options = { ...options };\n const { method, path, query, headers: headers = {} } = options;\n\n const body =\n ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?\n options.body\n : isMultipartBody(options.body) ? options.body.body\n : options.body ? JSON.stringify(options.body, null, 2)\n : null;\n const contentLength = this.calculateContentLength(body);\n\n const url = this.buildURL(path!, query);\n if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);\n options.timeout = options.timeout ?? this.timeout;\n const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);\n const minAgentTimeout = options.timeout + 1000;\n if (\n typeof (httpAgent as any)?.options?.timeout === 'number' &&\n minAgentTimeout > ((httpAgent as any).options.timeout ?? 0)\n ) {\n // Allow any given request to bump our agent active socket timeout.\n // This may seem strange, but leaking active sockets should be rare and not particularly problematic,\n // and without mutating agent we would need to create more of them.\n // This tradeoff optimizes for performance.\n (httpAgent as any).options.timeout = minAgentTimeout;\n }\n\n if (this.idempotencyHeader && method !== 'get') {\n if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();\n headers[this.idempotencyHeader] = options.idempotencyKey;\n }\n\n const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });\n\n const req: RequestInit = {\n method,\n ...(body && { body: body as any }),\n headers: reqHeaders,\n ...(httpAgent && { agent: httpAgent }),\n // @ts-ignore node-fetch uses a custom AbortSignal type that is\n // not compatible with standard web types\n signal: options.signal ?? null,\n };\n\n return { req, url, timeout: options.timeout };\n }\n\n private buildHeaders({\n options,\n headers,\n contentLength,\n retryCount,\n }: {\n options: FinalRequestOptions;\n headers: Record<string, string | null | undefined>;\n contentLength: string | null | undefined;\n retryCount: number;\n }): Record<string, string> {\n const reqHeaders: Record<string, string> = {};\n if (contentLength) {\n reqHeaders['content-length'] = contentLength;\n }\n\n const defaultHeaders = this.defaultHeaders(options);\n applyHeadersMut(reqHeaders, defaultHeaders);\n applyHeadersMut(reqHeaders, headers);\n\n // let builtin fetch set the Content-Type for multipart bodies\n if (isMultipartBody(options.body) && shimsKind !== 'node') {\n delete reqHeaders['content-type'];\n }\n\n // Don't set theses headers if they were already set or removed through default headers or by the caller.\n // We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account\n // for the removal case.\n if (\n getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&\n getHeader(headers, 'x-stainless-retry-count') === undefined\n ) {\n reqHeaders['x-stainless-retry-count'] = String(retryCount);\n }\n if (\n getHeader(defaultHeaders, 'x-stainless-timeout') === undefined &&\n getHeader(headers, 'x-stainless-timeout') === undefined &&\n options.timeout\n ) {\n reqHeaders['x-stainless-timeout'] = String(options.timeout);\n }\n\n this.validateHeaders(reqHeaders, headers);\n\n return reqHeaders;\n }\n\n _calculateNonstreamingTimeout(maxTokens: number): number {\n const defaultTimeout = 10 * 60;\n const expectedTimeout = (60 * 60 * maxTokens) / 128_000;\n if (expectedTimeout > defaultTimeout) {\n throw new AnthropicError(\n 'Streaming is strongly recommended for operations that may take longer than 10 minutes. ' +\n 'See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details',\n );\n }\n return defaultTimeout * 1000;\n }\n\n /**\n * Used as a callback for mutating the given `FinalRequestOptions` object.\n */\n protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}\n\n /**\n * Used as a callback for mutating the given `RequestInit` object.\n *\n * This is useful for cases where you want to add certain headers based off of\n * the request properties, e.g. `method` or `url`.\n */\n protected async prepareRequest(\n request: RequestInit,\n { url, options }: { url: string; options: FinalRequestOptions },\n ): Promise<void> {}\n\n protected parseHeaders(headers: HeadersInit | null | undefined): Record<string, string> {\n return (\n !headers ? {}\n : Symbol.iterator in headers ?\n Object.fromEntries(Array.from(headers as Iterable<string[]>).map((header) => [...header]))\n : { ...headers }\n );\n }\n\n protected makeStatusError(\n status: number | undefined,\n error: Object | undefined,\n message: string | undefined,\n headers: Headers | undefined,\n ): APIError {\n return APIError.generate(status, error, message, headers);\n }\n\n request<Req, Rsp>(\n options: PromiseOrValue<FinalRequestOptions<Req>>,\n remainingRetries: number | null = null,\n ): APIPromise<Rsp> {\n return new APIPromise(this.makeRequest(options, remainingRetries));\n }\n\n private async makeRequest<Req>(\n optionsInput: PromiseOrValue<FinalRequestOptions<Req>>,\n retriesRemaining: number | null,\n ): Promise<APIResponseProps> {\n const options = await optionsInput;\n const maxRetries = options.maxRetries ?? this.maxRetries;\n if (retriesRemaining == null) {\n retriesRemaining = maxRetries;\n }\n\n await this.prepareOptions(options);\n\n const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });\n\n await this.prepareRequest(req, { url, options });\n\n debug('request', url, options, req.headers);\n\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n\n const controller = new AbortController();\n const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);\n\n if (response instanceof Error) {\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n if (retriesRemaining) {\n return this.retryRequest(options, retriesRemaining);\n }\n if (response.name === 'AbortError') {\n throw new APIConnectionTimeoutError();\n }\n throw new APIConnectionError({ cause: response });\n }\n\n const responseHeaders = createResponseHeaders(response.headers);\n\n if (!response.ok) {\n if (retriesRemaining && this.shouldRetry(response)) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);\n return this.retryRequest(options, retriesRemaining, responseHeaders);\n }\n\n const errText = await response.text().catch((e) => castToError(e).message);\n const errJSON = safeJSON(errText);\n const errMessage = errJSON ? undefined : errText;\n const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;\n\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);\n\n const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);\n throw err;\n }\n\n return { response, options, controller };\n }\n\n requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(\n Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,\n options: FinalRequestOptions,\n ): PagePromise<PageClass, Item> {\n const request = this.makeRequest(options, null);\n return new PagePromise<PageClass, Item>(this, request, Page);\n }\n\n buildURL<Req>(path: string, query: Req | null | undefined): string {\n const url =\n isAbsoluteURL(path) ?\n new URL(path)\n : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));\n\n const defaultQuery = this.defaultQuery();\n if (!isEmptyObj(defaultQuery)) {\n query = { ...defaultQuery, ...query } as Req;\n }\n\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query as Record<string, unknown>);\n }\n\n return url.toString();\n }\n\n protected stringifyQuery(query: Record<string, unknown>): string {\n return Object.entries(query)\n .filter(([_, value]) => typeof value !== 'undefined')\n .map(([key, value]) => {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n }\n if (value === null) {\n return `${encodeURIComponent(key)}=`;\n }\n throw new AnthropicError(\n `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.`,\n );\n })\n .join('&');\n }\n\n async fetchWithTimeout(\n url: RequestInfo,\n init: RequestInit | undefined,\n ms: number,\n controller: AbortController,\n ): Promise<Response> {\n const { signal, ...options } = init || {};\n if (signal) signal.addEventListener('abort', () => controller.abort());\n\n const timeout = setTimeout(() => controller.abort(), ms);\n\n const fetchOptions = {\n signal: controller.signal as any,\n ...options,\n };\n if (fetchOptions.method) {\n // Custom methods like 'patch' need to be uppercased\n // See https://github.com/nodejs/undici/issues/2294\n fetchOptions.method = fetchOptions.method.toUpperCase();\n }\n\n // turn on TCP keep-alive for the sockets, if the runtime supports it\n const socketKeepAliveInterval = 60 * 1000;\n const keepAliveTimeout = setTimeout(() => {\n if (fetchOptions && (fetchOptions as any)?.agent?.sockets) {\n for (const socket of Object.values((fetchOptions as any)?.agent?.sockets).flat()) {\n if ((socket as any)?.setKeepAlive) {\n (socket as any).setKeepAlive(true, socketKeepAliveInterval);\n }\n }\n }\n }, socketKeepAliveInterval);\n\n return (\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n this.fetch.call(undefined, url, fetchOptions).finally(() => {\n clearTimeout(timeout);\n clearTimeout(keepAliveTimeout);\n })\n );\n }\n\n private shouldRetry(response: Response): boolean {\n // Note this is not a standard header.\n const shouldRetryHeader = response.headers.get('x-should-retry');\n\n // If the server explicitly says whether or not to retry, obey.\n if (shouldRetryHeader === 'true') return true;\n if (shouldRetryHeader === 'false') return false;\n\n // Retry on request timeouts.\n if (response.status === 408) return true;\n\n // Retry on lock timeouts.\n if (response.status === 409) return true;\n\n // Retry on rate limits.\n if (response.status === 429) return true;\n\n // Retry internal errors.\n if (response.status >= 500) return true;\n\n return false;\n }\n\n private async retryRequest(\n options: FinalRequestOptions,\n retriesRemaining: number,\n responseHeaders?: Headers | undefined,\n ): Promise<APIResponseProps> {\n let timeoutMillis: number | undefined;\n\n // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.\n const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];\n if (retryAfterMillisHeader) {\n const timeoutMs = parseFloat(retryAfterMillisHeader);\n if (!Number.isNaN(timeoutMs)) {\n timeoutMillis = timeoutMs;\n }\n }\n\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfterHeader = responseHeaders?.['retry-after'];\n if (retryAfterHeader && !timeoutMillis) {\n const timeoutSeconds = parseFloat(retryAfterHeader);\n if (!Number.isNaN(timeoutSeconds)) {\n timeoutMillis = timeoutSeconds * 1000;\n } else {\n timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\n }\n }\n\n // If the API asks us to wait a certain amount of time (and it's a reasonable amount),\n // just do what it says, but otherwise calculate a default\n if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\n const maxRetries = options.maxRetries ?? this.maxRetries;\n timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\n }\n await sleep(timeoutMillis);\n\n return this.makeRequest(options, retriesRemaining - 1);\n }\n\n private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {\n const initialRetryDelay = 0.5;\n const maxRetryDelay = 8.0;\n\n const numRetries = maxRetries - retriesRemaining;\n\n // Apply exponential backoff, but not more than the max.\n const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\n\n // Apply some jitter, take up to at most 25 percent of the retry time.\n const jitter = 1 - Math.random() * 0.25;\n\n return sleepSeconds * jitter * 1000;\n }\n\n private getUserAgent(): string {\n return `${this.constructor.name}/JS ${VERSION}`;\n }\n}\n\nexport type PageInfo = { url: URL } | { params: Record<string, unknown> | null };\n\nexport abstract class AbstractPage<Item> implements AsyncIterable<Item> {\n #client: APIClient;\n protected options: FinalRequestOptions;\n\n protected response: Response;\n protected body: unknown;\n\n constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions) {\n this.#client = client;\n this.options = options;\n this.response = response;\n this.body = body;\n }\n\n /**\n * @deprecated Use nextPageInfo instead\n */\n abstract nextPageParams(): Partial<Record<string, unknown>> | null;\n abstract nextPageInfo(): PageInfo | null;\n\n abstract getPaginatedItems(): Item[];\n\n hasNextPage(): boolean {\n const items = this.getPaginatedItems();\n if (!items.length) return false;\n return this.nextPageInfo() != null;\n }\n\n async getNextPage(): Promise<this> {\n const nextInfo = this.nextPageInfo();\n if (!nextInfo) {\n throw new AnthropicError(\n 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',\n );\n }\n const nextOptions = { ...this.options };\n if ('params' in nextInfo && typeof nextOptions.query === 'object') {\n nextOptions.query = { ...nextOptions.query, ...nextInfo.params };\n } else if ('url' in nextInfo) {\n const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];\n for (const [key, value] of params) {\n nextInfo.url.searchParams.set(key, value as any);\n }\n nextOptions.query = undefined;\n nextOptions.path = nextInfo.url.toString();\n }\n return await this.#client.requestAPIList(this.constructor as any, nextOptions);\n }\n\n async *iterPages(): AsyncGenerator<this> {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let page: this = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<Item> {\n for await (const page of this.iterPages()) {\n for (const item of page.getPaginatedItems()) {\n yield item;\n }\n }\n }\n}\n\n/**\n * This subclass of Promise will resolve to an instantiated Page once the request completes.\n *\n * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\nexport class PagePromise<\n PageClass extends AbstractPage<Item>,\n Item = ReturnType<PageClass['getPaginatedItems']>[number],\n >\n extends APIPromise<PageClass>\n implements AsyncIterable<Item>\n{\n constructor(\n client: APIClient,\n request: Promise<APIResponseProps>,\n Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,\n ) {\n super(\n request,\n async (props) =>\n new Page(\n client,\n props.response,\n await defaultParseResponse(props),\n props.options,\n ) as WithRequestID<PageClass>,\n );\n }\n\n /**\n * Allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<Item> {\n const page = await this;\n for await (const item of page) {\n yield item;\n }\n }\n}\n\nexport const createResponseHeaders = (\n headers: Awaited<ReturnType<Fetch>>['headers'],\n): Record<string, string> => {\n return new Proxy(\n Object.fromEntries(\n // @ts-ignore\n headers.entries(),\n ),\n {\n get(target, name) {\n const key = name.toString();\n return target[key.toLowerCase()] || target[key];\n },\n },\n );\n};\n\ntype HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport type RequestClient = { fetch: Fetch };\nexport type Headers = Record<string, string | null | undefined>;\nexport type DefaultQuery = Record<string, string | undefined>;\nexport type KeysEnum<T> = { [P in keyof Required<T>]: true };\n\nexport type RequestOptions<\n Req = unknown | Record<string, unknown> | Readable | BlobLike | ArrayBufferView | ArrayBuffer,\n> = {\n method?: HTTPMethod;\n path?: string;\n query?: Req | undefined;\n body?: Req | null | undefined;\n headers?: Headers | undefined;\n\n maxRetries?: number;\n stream?: boolean | undefined;\n timeout?: number;\n httpAgent?: Agent;\n signal?: AbortSignal | undefined | null;\n idempotencyKey?: string;\n\n __binaryRequest?: boolean | undefined;\n __binaryResponse?: boolean | undefined;\n __streamClass?: typeof Stream;\n};\n\n// This is required so that we can determine if a given object matches the RequestOptions\n// type at runtime. While this requires duplication, it is enforced by the TypeScript\n// compiler such that any missing / extraneous keys will cause an error.\nconst requestOptionsKeys: KeysEnum<RequestOptions> = {\n method: true,\n path: true,\n query: true,\n body: true,\n headers: true,\n\n maxRetries: true,\n stream: true,\n timeout: true,\n httpAgent: true,\n signal: true,\n idempotencyKey: true,\n\n __binaryRequest: true,\n __binaryResponse: true,\n __streamClass: true,\n};\n\nexport const isRequestOptions = (obj: unknown): obj is RequestOptions => {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n !isEmptyObj(obj) &&\n Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))\n );\n};\n\nexport type FinalRequestOptions<Req = unknown | Record<string, unknown> | Readable | DataView> =\n RequestOptions<Req> & {\n method: HTTPMethod;\n path: string;\n };\n\ndeclare const Deno: any;\ndeclare const EdgeRuntime: any;\ntype Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown';\ntype PlatformName =\n | 'MacOS'\n | 'Linux'\n | 'Windows'\n | 'FreeBSD'\n | 'OpenBSD'\n | 'iOS'\n | 'Android'\n | `Other:${string}`\n | 'Unknown';\ntype Browser = 'ie' | 'edge' | 'chrome' | 'firefox' | 'safari';\ntype PlatformProperties = {\n 'X-Stainless-Lang': 'js';\n 'X-Stainless-Package-Version': string;\n 'X-Stainless-OS': PlatformName;\n 'X-Stainless-Arch': Arch;\n 'X-Stainless-Runtime': 'node' | 'deno' | 'edge' | `browser:${Browser}` | 'unknown';\n 'X-Stainless-Runtime-Version': string;\n};\nconst getPlatformProperties = (): PlatformProperties => {\n if (typeof Deno !== 'undefined' && Deno.build != null) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(Deno.build.os),\n 'X-Stainless-Arch': normalizeArch(Deno.build.arch),\n 'X-Stainless-Runtime': 'deno',\n 'X-Stainless-Runtime-Version':\n typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',\n };\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': `other:${EdgeRuntime}`,\n 'X-Stainless-Runtime': 'edge',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n // Check if Node.js\n if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(process.platform),\n 'X-Stainless-Arch': normalizeArch(process.arch),\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n\n const browserInfo = getBrowserInfo();\n if (browserInfo) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,\n 'X-Stainless-Runtime-Version': browserInfo.version,\n };\n }\n\n // TODO add support for Cloudflare workers, etc.\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': 'unknown',\n 'X-Stainless-Runtime-Version': 'unknown',\n };\n};\n\ntype BrowserInfo = {\n browser: Browser;\n version: string;\n};\n\ndeclare const navigator: { userAgent: string } | undefined;\n\n// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts\nfunction getBrowserInfo(): BrowserInfo | null {\n if (typeof navigator === 'undefined' || !navigator) {\n return null;\n }\n\n // NOTE: The order matters here!\n const browserPatterns = [\n { key: 'edge' as const, pattern: /Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie' as const, pattern: /MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie' as const, pattern: /Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'chrome' as const, pattern: /Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'firefox' as const, pattern: /Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'safari' as const, pattern: /(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/ },\n ];\n\n // Find the FIRST matching browser\n for (const { key, pattern } of browserPatterns) {\n const match = pattern.exec(navigator.userAgent);\n if (match) {\n const major = match[1] || 0;\n const minor = match[2] || 0;\n const patch = match[3] || 0;\n\n return { browser: key, version: `${major}.${minor}.${patch}` };\n }\n }\n\n return null;\n}\n\nconst normalizeArch = (arch: string): Arch => {\n // Node docs:\n // - https://nodejs.org/api/process.html#processarch\n // Deno docs:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n if (arch === 'x32') return 'x32';\n if (arch === 'x86_64' || arch === 'x64') return 'x64';\n if (arch === 'arm') return 'arm';\n if (arch === 'aarch64' || arch === 'arm64') return 'arm64';\n if (arch) return `other:${arch}`;\n return 'unknown';\n};\n\nconst normalizePlatform = (platform: string): PlatformName => {\n // Node platforms:\n // - https://nodejs.org/api/process.html#processplatform\n // Deno platforms:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n // - https://github.com/denoland/deno/issues/14799\n\n platform = platform.toLowerCase();\n\n // NOTE: this iOS check is untested and may not work\n // Node does not work natively on IOS, there is a fork at\n // https://github.com/nodejs-mobile/nodejs-mobile\n // however it is unknown at the time of writing how to detect if it is running\n if (platform.includes('ios')) return 'iOS';\n if (platform === 'android') return 'Android';\n if (platform === 'darwin') return 'MacOS';\n if (platform === 'win32') return 'Windows';\n if (platform === 'freebsd') return 'FreeBSD';\n if (platform === 'openbsd') return 'OpenBSD';\n if (platform === 'linux') return 'Linux';\n if (platform) return `Other:${platform}`;\n return 'Unknown';\n};\n\nlet _platformHeaders: PlatformProperties;\nconst getPlatformHeaders = () => {\n return (_platformHeaders ??= getPlatformProperties());\n};\n\nexport const safeJSON = (text: string) => {\n try {\n return JSON.parse(text);\n } catch (err) {\n return undefined;\n }\n};\n\n// https://url.spec.whatwg.org/#url-scheme-string\nconst startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\nconst isAbsoluteURL = (url: string): boolean => {\n return startsWithSchemeRegexp.test(url);\n};\n\nexport const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst validatePositiveInteger = (name: string, n: unknown): number => {\n if (typeof n !== 'number' || !Number.isInteger(n)) {\n throw new AnthropicError(`${name} must be an integer`);\n }\n if (n < 0) {\n throw new AnthropicError(`${name} must be a positive integer`);\n }\n return n;\n};\n\nexport const castToError = (err: any): Error => {\n if (err instanceof Error) return err;\n if (typeof err === 'object' && err !== null) {\n try {\n return new Error(JSON.stringify(err));\n } catch {}\n }\n return new Error(String(err));\n};\n\nexport const ensurePresent = <T>(value: T | null | undefined): T => {\n if (value == null) throw new AnthropicError(`Expected a value to be given but received ${value} instead.`);\n return value;\n};\n\n/**\n * Read an environment variable.\n *\n * Trims beginning and trailing whitespace.\n *\n * Will return undefined if the environment variable doesn't exist or cannot be accessed.\n */\nexport const readEnv = (env: string): string | undefined => {\n if (typeof process !== 'undefined') {\n return process.env?.[env]?.trim() ?? undefined;\n }\n if (typeof Deno !== 'undefined') {\n return Deno.env?.get?.(env)?.trim();\n }\n return undefined;\n};\n\nexport const coerceInteger = (value: unknown): number => {\n if (typeof value === 'number') return Math.round(value);\n if (typeof value === 'string') return parseInt(value, 10);\n\n throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceFloat = (value: unknown): number => {\n if (typeof value === 'number') return value;\n if (typeof value === 'string') return parseFloat(value);\n\n throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceBoolean = (value: unknown): boolean => {\n if (typeof value === 'boolean') return value;\n if (typeof value === 'string') return value === 'true';\n return Boolean(value);\n};\n\nexport const maybeCoerceInteger = (value: unknown): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n return coerceInteger(value);\n};\n\nexport const maybeCoerceFloat = (value: unknown): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n return coerceFloat(value);\n};\n\nexport const maybeCoerceBoolean = (value: unknown): boolean | undefined => {\n if (value === undefined) {\n return undefined;\n }\n return coerceBoolean(value);\n};\n\n// https://stackoverflow.com/a/34491287\nexport function isEmptyObj(obj: Object | null | undefined): boolean {\n if (!obj) return true;\n for (const _k in obj) return false;\n return true;\n}\n\n// https://eslint.org/docs/latest/rules/no-prototype-builtins\nexport function hasOwn(obj: Object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Copies headers from \"newHeaders\" onto \"targetHeaders\",\n * using lower-case for all properties,\n * ignoring any keys with undefined values,\n * and deleting any keys with null values.\n */\nfunction applyHeadersMut(targetHeaders: Headers, newHeaders: Headers): void {\n for (const k in newHeaders) {\n if (!hasOwn(newHeaders, k)) continue;\n const lowerKey = k.toLowerCase();\n if (!lowerKey) continue;\n\n const val = newHeaders[k];\n\n if (val === null) {\n delete targetHeaders[lowerKey];\n } else if (val !== undefined) {\n targetHeaders[lowerKey] = val;\n }\n }\n}\n\nexport function debug(action: string, ...args: any[]) {\n if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {\n console.log(`Anthropic:DEBUG:${action}`, ...args);\n }\n}\n\n/**\n * https://stackoverflow.com/a/2117523\n */\nconst uuid4 = () => {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n\nexport const isRunningInBrowser = () => {\n return (\n // @ts-ignore\n typeof window !== 'undefined' &&\n // @ts-ignore\n typeof window.document !== 'undefined' &&\n // @ts-ignore\n typeof navigator !== 'undefined'\n );\n};\n\nexport interface HeadersProtocol {\n get: (header: string) => string | null | undefined;\n}\nexport type HeadersLike = Record<string, string | string[] | undefined> | HeadersProtocol;\n\nexport const isHeadersProtocol = (headers: any): headers is HeadersProtocol => {\n return typeof headers?.get === 'function';\n};\n\nexport const getRequiredHeader = (headers: HeadersLike | Headers, header: string): string => {\n const foundHeader = getHeader(headers, header);\n if (foundHeader === undefined) {\n throw new Error(`Could not find ${header} header`);\n }\n return foundHeader;\n};\n\nexport const getHeader = (headers: HeadersLike | Headers, header: string): string | undefined => {\n const lowerCasedHeader = header.toLowerCase();\n if (isHeadersProtocol(headers)) {\n // to deal with the case where the header looks like Stainless-Event-Id\n const intercapsHeader =\n header[0]?.toUpperCase() +\n header.substring(1).replace(/([^\\w])(\\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());\n for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {\n const value = headers.get(key);\n if (value) {\n return value;\n }\n }\n }\n\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === lowerCasedHeader) {\n if (Array.isArray(value)) {\n if (value.length <= 1) return value[0];\n console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);\n return value[0];\n }\n return value;\n }\n }\n\n return undefined;\n};\n\n/**\n * Encodes a string to Base64 format.\n */\nexport const toBase64 = (str: string | null | undefined): string => {\n if (!str) return '';\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str).toString('base64');\n }\n\n if (typeof btoa !== 'undefined') {\n return btoa(str);\n }\n\n throw new AnthropicError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');\n};\n\nexport function isObj(obj: unknown): obj is Record<string, unknown> {\n return obj != null && typeof obj === 'object' && !Array.isArray(obj);\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { AbstractPage, Response, APIClient, FinalRequestOptions, PageInfo } from \"./core.js\";\n\nexport interface PageResponse<Item> {\n data: Array<Item>;\n\n has_more: boolean;\n\n first_id: string | null;\n\n last_id: string | null;\n}\n\nexport interface PageParams {\n /**\n * Number of items per page.\n */\n limit?: number;\n\n before_id?: string;\n\n after_id?: string;\n}\n\nexport class Page<Item> extends AbstractPage<Item> implements PageResponse<Item> {\n data: Array<Item>;\n\n has_more: boolean;\n\n first_id: string | null;\n\n last_id: string | null;\n\n constructor(client: APIClient, response: Response, body: PageResponse<Item>, options: FinalRequestOptions) {\n super(client, response, body, options);\n\n this.data = body.data || [];\n this.has_more = body.has_more || false;\n this.first_id = body.first_id || null;\n this.last_id = body.last_id || null;\n }\n\n getPaginatedItems(): Item[] {\n return this.data ?? [];\n }\n\n override hasNextPage(): boolean {\n if (this.has_more === false) {\n return false;\n }\n\n return super.hasNextPage();\n }\n\n // @deprecated Please use `nextPageInfo()` instead\n nextPageParams(): Partial<PageParams> | null {\n const info = this.nextPageInfo();\n if (!info) return null;\n if ('params' in info) return info.params;\n const params = Object.fromEntries(info.url.searchParams);\n if (!Object.keys(params).length) return null;\n return params;\n }\n\n nextPageInfo(): PageInfo | null {\n if ((this.options.query as Record<string, unknown>)?.['before_id']) {\n // in reverse\n const firstId = this.first_id;\n if (!firstId) {\n return null;\n }\n\n return {\n params: {\n before_id: firstId,\n },\n };\n }\n\n const cursor = this.last_id;\n if (!cursor) {\n return null;\n }\n\n return {\n params: {\n after_id: cursor,\n },\n };\n }\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport * as Core from \"./core.js\";\n\nexport class APIResource {\n protected _client: Core.APIClient;\n\n constructor(client: Core.APIClient) {\n this._client = client;\n }\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../resource.js\";\nimport { isRequestOptions } from \"../../core.js\";\nimport * as Core from \"../../core.js\";\nimport { Page, type PageParams } from \"../../pagination.js\";\n\nexport class Models extends APIResource {\n /**\n * Get a specific model.\n *\n * The Models API response can be used to determine information about a specific\n * model or resolve a model alias to a model ID.\n */\n retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo> {\n return this._client.get(`/v1/models/${modelId}?beta=true`, options);\n }\n\n /**\n * List available models.\n *\n * The Models API response can be used to determine which models are available for\n * use in the API. More recently released models are listed first.\n */\n list(\n query?: ModelListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;\n list(options?: Core.RequestOptions): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;\n list(\n query: ModelListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<BetaModelInfosPage, BetaModelInfo> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, { query, ...options });\n }\n}\n\nexport class BetaModelInfosPage extends Page<BetaModelInfo> {}\n\nexport interface BetaModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the model was released.\n * May be set to an epoch value if the release date is unknown.\n */\n created_at: string;\n\n /**\n * A human-readable name for the model.\n */\n display_name: string;\n\n /**\n * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\n}\n\nexport interface ModelListParams extends PageParams {}\n\nModels.BetaModelInfosPage = BetaModelInfosPage;\n\nexport declare namespace Models {\n export {\n type BetaModelInfo as BetaModelInfo,\n BetaModelInfosPage as BetaModelInfosPage,\n type ModelListParams as ModelListParams,\n };\n}\n", "import { AnthropicError } from \"../../error.js\";\nimport { ReadableStreamToAsyncIterable } from \"../stream-utils.js\";\nimport { type Response } from \"../../_shims/index.js\";\nimport { LineDecoder, type Bytes } from \"./line.js\";\n\nexport class JSONLDecoder<T> {\n controller: AbortController;\n\n constructor(\n private iterator: AsyncIterableIterator<Bytes>,\n controller: AbortController,\n ) {\n this.controller = controller;\n }\n\n private async *decoder(): AsyncIterator<T, any, undefined> {\n const lineDecoder = new LineDecoder();\n for await (const chunk of this.iterator) {\n for (const line of lineDecoder.decode(chunk)) {\n yield JSON.parse(line);\n }\n }\n\n for (const line of lineDecoder.flush()) {\n yield JSON.parse(line);\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this.decoder();\n }\n\n static fromResponse<T>(response: Response, controller: AbortController): JSONLDecoder<T> {\n if (!response.body) {\n controller.abort();\n throw new AnthropicError(`Attempted to iterate over a response with no body`);\n }\n\n return new JSONLDecoder(ReadableStreamToAsyncIterable<Bytes>(response.body), controller);\n }\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../../resource.js\";\nimport { isRequestOptions } from \"../../../core.js\";\nimport * as Core from \"../../../core.js\";\nimport * as BetaAPI from \"../beta.js\";\nimport * as BetaMessagesAPI from \"./messages.js\";\nimport { Page, type PageParams } from \"../../../pagination.js\";\nimport { JSONLDecoder } from \"../../../internal/decoders/jsonl.js\";\nimport { AnthropicError } from \"../../../error.js\";\n\nexport class Batches extends APIResource {\n /**\n * Send a batch of Message creation requests.\n *\n * The Message Batches API can be used to process multiple Messages API requests at\n * once. Once a Message Batch is created, it begins processing immediately. Batches\n * can take up to 24 hours to complete.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n create(params: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch> {\n const { betas, ...body } = params;\n return this._client.post('/v1/messages/batches?beta=true', {\n body,\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * This endpoint is idempotent and can be used to poll for Message Batch\n * completion. To access the results of a Message Batch, make a request to the\n * `results_url` field in the response.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n retrieve(\n messageBatchId: string,\n params?: BatchRetrieveParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageBatch>;\n retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;\n retrieve(\n messageBatchId: string,\n params: BatchRetrieveParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageBatch> {\n if (isRequestOptions(params)) {\n return this.retrieve(messageBatchId, {}, params);\n }\n const { betas } = params;\n return this._client.get(`/v1/messages/batches/${messageBatchId}?beta=true`, {\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * List all Message Batches within a Workspace. Most recently created batches are\n * returned first.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n list(\n params?: BatchListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;\n list(options?: Core.RequestOptions): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;\n list(\n params: BatchListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<BetaMessageBatchesPage, BetaMessageBatch> {\n if (isRequestOptions(params)) {\n return this.list({}, params);\n }\n const { betas, ...query } = params;\n return this._client.getAPIList('/v1/messages/batches?beta=true', BetaMessageBatchesPage, {\n query,\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * Delete a Message Batch.\n *\n * Message Batches can only be deleted once they've finished processing. If you'd\n * like to delete an in-progress batch, you must first cancel it.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n delete(\n messageBatchId: string,\n params?: BatchDeleteParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaDeletedMessageBatch>;\n delete(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaDeletedMessageBatch>;\n delete(\n messageBatchId: string,\n params: BatchDeleteParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaDeletedMessageBatch> {\n if (isRequestOptions(params)) {\n return this.delete(messageBatchId, {}, params);\n }\n const { betas } = params;\n return this._client.delete(`/v1/messages/batches/${messageBatchId}?beta=true`, {\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * Batches may be canceled any time before processing ends. Once cancellation is\n * initiated, the batch enters a `canceling` state, at which time the system may\n * complete any in-progress, non-interruptible requests before finalizing\n * cancellation.\n *\n * The number of canceled requests is specified in `request_counts`. To determine\n * which requests were canceled, check the individual results within the batch.\n * Note that cancellation may not result in any canceled requests if they were\n * non-interruptible.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n cancel(\n messageBatchId: string,\n params?: BatchCancelParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageBatch>;\n cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch>;\n cancel(\n messageBatchId: string,\n params: BatchCancelParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageBatch> {\n if (isRequestOptions(params)) {\n return this.cancel(messageBatchId, {}, params);\n }\n const { betas } = params;\n return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel?beta=true`, {\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...options?.headers,\n },\n });\n }\n\n /**\n * Streams the results of a Message Batch as a `.jsonl` file.\n *\n * Each line in the file is a JSON object containing the result of a single request\n * in the Message Batch. Results are not guaranteed to be in the same order as\n * requests. Use the `custom_id` field to match results to requests.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n async results(\n messageBatchId: string,\n params?: BatchResultsParams,\n options?: Core.RequestOptions,\n ): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;\n async results(\n messageBatchId: string,\n options?: Core.RequestOptions,\n ): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;\n async results(\n messageBatchId: string,\n params: BatchResultsParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>> {\n if (isRequestOptions(params)) {\n return this.results(messageBatchId, {}, params);\n }\n\n const batch = await this.retrieve(messageBatchId);\n if (!batch.results_url) {\n throw new AnthropicError(\n `No batch \\`results_url\\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`,\n );\n }\n\n const { betas } = params;\n return this._client\n .get(batch.results_url, {\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n Accept: 'application/binary',\n ...options?.headers,\n },\n __binaryResponse: true,\n })\n ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));\n }\n}\n\nexport class BetaMessageBatchesPage extends Page<BetaMessageBatch> {}\n\nexport interface BetaDeletedMessageBatch {\n /**\n * ID of the Message Batch.\n */\n id: string;\n\n /**\n * Deleted object type.\n *\n * For Message Batches, this is always `\"message_batch_deleted\"`.\n */\n type: 'message_batch_deleted';\n}\n\nexport interface BetaMessageBatch {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * archived and its results became unavailable.\n */\n archived_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which cancellation was\n * initiated for the Message Batch. Specified only if cancellation was initiated.\n */\n cancel_initiated_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * created.\n */\n created_at: string;\n\n /**\n * RFC 3339 datetime string representing the time at which processing for the\n * Message Batch ended. Specified only once processing ends.\n *\n * Processing ends when every request in a Message Batch has either succeeded,\n * errored, canceled, or expired.\n */\n ended_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch will\n * expire and end processing, which is 24 hours after creation.\n */\n expires_at: string;\n\n /**\n * Processing status of the Message Batch.\n */\n processing_status: 'in_progress' | 'canceling' | 'ended';\n\n /**\n * Tallies requests within the Message Batch, categorized by their status.\n *\n * Requests start as `processing` and move to one of the other statuses only once\n * processing of the entire batch ends. The sum of all values always matches the\n * total number of requests in the batch.\n */\n request_counts: BetaMessageBatchRequestCounts;\n\n /**\n * URL to a `.jsonl` file containing the results of the Message Batch requests.\n * Specified only once processing ends.\n *\n * Results in the file are not guaranteed to be in the same order as requests. Use\n * the `custom_id` field to match results to requests.\n */\n results_url: string | null;\n\n /**\n * Object type.\n *\n * For Message Batches, this is always `\"message_batch\"`.\n */\n type: 'message_batch';\n}\n\nexport interface BetaMessageBatchCanceledResult {\n type: 'canceled';\n}\n\nexport interface BetaMessageBatchErroredResult {\n error: BetaAPI.BetaErrorResponse;\n\n type: 'errored';\n}\n\nexport interface BetaMessageBatchExpiredResult {\n type: 'expired';\n}\n\n/**\n * This is a single line in the response `.jsonl` file and does not represent the\n * response as a whole.\n */\nexport interface BetaMessageBatchIndividualResponse {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\n result: BetaMessageBatchResult;\n}\n\nexport interface BetaMessageBatchRequestCounts {\n /**\n * Number of requests in the Message Batch that have been canceled.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n canceled: number;\n\n /**\n * Number of requests in the Message Batch that encountered an error.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n errored: number;\n\n /**\n * Number of requests in the Message Batch that have expired.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n expired: number;\n\n /**\n * Number of requests in the Message Batch that are processing.\n */\n processing: number;\n\n /**\n * Number of requests in the Message Batch that have completed successfully.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n succeeded: number;\n}\n\n/**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\nexport type BetaMessageBatchResult =\n | BetaMessageBatchSucceededResult\n | BetaMessageBatchErroredResult\n | BetaMessageBatchCanceledResult\n | BetaMessageBatchExpiredResult;\n\nexport interface BetaMessageBatchSucceededResult {\n message: BetaMessagesAPI.BetaMessage;\n\n type: 'succeeded';\n}\n\nexport interface BatchCreateParams {\n /**\n * Body param: List of requests for prompt completion. Each is an individual\n * request to create a Message.\n */\n requests: Array<BatchCreateParams.Request>;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport namespace BatchCreateParams {\n export interface Request {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Messages API creation parameters for the individual request.\n *\n * See the [Messages API reference](/en/api/messages) for full documentation on\n * available parameters.\n */\n params: Omit<BetaMessagesAPI.MessageCreateParamsNonStreaming, 'betas'>;\n }\n}\n\nexport interface BatchRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchListParams extends PageParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchDeleteParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchCancelParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchResultsParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nBatches.BetaMessageBatchesPage = BetaMessageBatchesPage;\n\nexport declare namespace Batches {\n export {\n type BetaDeletedMessageBatch as BetaDeletedMessageBatch,\n type BetaMessageBatch as BetaMessageBatch,\n type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult,\n type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult,\n type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult,\n type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse,\n type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts,\n type BetaMessageBatchResult as BetaMessageBatchResult,\n type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult,\n BetaMessageBatchesPage as BetaMessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchRetrieveParams as BatchRetrieveParams,\n type BatchListParams as BatchListParams,\n type BatchDeleteParams as BatchDeleteParams,\n type BatchCancelParams as BatchCancelParams,\n type BatchResultsParams as BatchResultsParams,\n };\n}\n", "type Token = {\n type: string;\n value: string;\n};\n\nconst tokenize = (input: string): Token[] => {\n let current = 0;\n let tokens: Token[] = [];\n\n while (current < input.length) {\n let char = input[current];\n\n if (char === '\\\\') {\n current++;\n continue;\n }\n\n if (char === '{') {\n tokens.push({\n type: 'brace',\n value: '{',\n });\n\n current++;\n continue;\n }\n\n if (char === '}') {\n tokens.push({\n type: 'brace',\n value: '}',\n });\n\n current++;\n continue;\n }\n\n if (char === '[') {\n tokens.push({\n type: 'paren',\n value: '[',\n });\n\n current++;\n continue;\n }\n\n if (char === ']') {\n tokens.push({\n type: 'paren',\n value: ']',\n });\n\n current++;\n continue;\n }\n\n if (char === ':') {\n tokens.push({\n type: 'separator',\n value: ':',\n });\n\n current++;\n continue;\n }\n\n if (char === ',') {\n tokens.push({\n type: 'delimiter',\n value: ',',\n });\n\n current++;\n continue;\n }\n\n if (char === '\"') {\n let value = '';\n let danglingQuote = false;\n\n char = input[++current];\n\n while (char !== '\"') {\n if (current === input.length) {\n danglingQuote = true;\n break;\n }\n\n if (char === '\\\\') {\n current++;\n if (current === input.length) {\n danglingQuote = true;\n break;\n }\n value += char + input[current];\n char = input[++current];\n } else {\n value += char;\n char = input[++current];\n }\n }\n\n char = input[++current];\n\n if (!danglingQuote) {\n tokens.push({\n type: 'string',\n value,\n });\n }\n continue;\n }\n\n let WHITESPACE = /\\s/;\n if (char && WHITESPACE.test(char)) {\n current++;\n continue;\n }\n\n let NUMBERS = /[0-9]/;\n if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {\n let value = '';\n\n if (char === '-') {\n value += char;\n char = input[++current];\n }\n\n while ((char && NUMBERS.test(char)) || char === '.') {\n value += char;\n char = input[++current];\n }\n\n tokens.push({\n type: 'number',\n value,\n });\n continue;\n }\n\n let LETTERS = /[a-z]/i;\n if (char && LETTERS.test(char)) {\n let value = '';\n\n while (char && LETTERS.test(char)) {\n if (current === input.length) {\n break;\n }\n value += char;\n char = input[++current];\n }\n\n if (value == 'true' || value == 'false' || value === 'null') {\n tokens.push({\n type: 'name',\n value,\n });\n } else {\n // unknown token, e.g. `nul` which isn't quite `null`\n current++;\n continue;\n }\n continue;\n }\n\n current++;\n }\n\n return tokens;\n },\n strip = (tokens: Token[]): Token[] => {\n if (tokens.length === 0) {\n return tokens;\n }\n\n let lastToken = tokens[tokens.length - 1]!;\n\n switch (lastToken.type) {\n case 'separator':\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n break;\n case 'number':\n let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];\n if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n }\n case 'string':\n let tokenBeforeTheLastToken = tokens[tokens.length - 2];\n if (tokenBeforeTheLastToken?.type === 'delimiter') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n } else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n }\n break;\n case 'delimiter':\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n break;\n }\n\n return tokens;\n },\n unstrip = (tokens: Token[]): Token[] => {\n let tail: string[] = [];\n\n tokens.map((token) => {\n if (token.type === 'brace') {\n if (token.value === '{') {\n tail.push('}');\n } else {\n tail.splice(tail.lastIndexOf('}'), 1);\n }\n }\n if (token.type === 'paren') {\n if (token.value === '[') {\n tail.push(']');\n } else {\n tail.splice(tail.lastIndexOf(']'), 1);\n }\n }\n });\n\n if (tail.length > 0) {\n tail.reverse().map((item) => {\n if (item === '}') {\n tokens.push({\n type: 'brace',\n value: '}',\n });\n } else if (item === ']') {\n tokens.push({\n type: 'paren',\n value: ']',\n });\n }\n });\n }\n\n return tokens;\n },\n generate = (tokens: Token[]): string => {\n let output = '';\n\n tokens.map((token) => {\n switch (token.type) {\n case 'string':\n output += '\"' + token.value + '\"';\n break;\n default:\n output += token.value;\n break;\n }\n });\n\n return output;\n },\n partialParse = (input: string): unknown => JSON.parse(generate(unstrip(strip(tokenize(input)))));\n\nexport { partialParse };\n", "import * as Core from \"../core.js\";\nimport { AnthropicError, APIUserAbortError } from \"../error.js\";\nimport {\n type BetaContentBlock,\n Messages as BetaMessages,\n type BetaMessage,\n type BetaRawMessageStreamEvent as BetaMessageStreamEvent,\n type BetaMessageParam,\n type MessageCreateParams as BetaMessageCreateParams,\n type MessageCreateParamsBase as BetaMessageCreateParamsBase,\n type BetaTextBlock,\n type BetaTextCitation,\n} from \"../resources/beta/messages/messages.js\";\nimport { type ReadableStream, type Response } from \"../_shims/index.js\";\nimport { Stream } from \"../streaming.js\";\nimport { partialParse } from \"../_vendor/partial-json-parser/parser.js\";\n\nexport interface MessageStreamEvents {\n connect: () => void;\n streamEvent: (event: BetaMessageStreamEvent, snapshot: BetaMessage) => void;\n text: (textDelta: string, textSnapshot: string) => void;\n citation: (citation: BetaTextCitation, citationsSnapshot: BetaTextCitation[]) => void;\n inputJson: (partialJson: string, jsonSnapshot: unknown) => void;\n thinking: (thinkingDelta: string, thinkingSnapshot: string) => void;\n signature: (signature: string) => void;\n message: (message: BetaMessage) => void;\n contentBlock: (content: BetaContentBlock) => void;\n finalMessage: (message: BetaMessage) => void;\n error: (error: AnthropicError) => void;\n abort: (error: APIUserAbortError) => void;\n end: () => void;\n}\n\ntype MessageStreamEventListeners<Event extends keyof MessageStreamEvents> = {\n listener: MessageStreamEvents[Event];\n once?: boolean;\n}[];\n\nconst JSON_BUF_PROPERTY = '__json_buf';\n\nexport class BetaMessageStream implements AsyncIterable<BetaMessageStreamEvent> {\n messages: BetaMessageParam[] = [];\n receivedMessages: BetaMessage[] = [];\n #currentMessageSnapshot: BetaMessage | undefined;\n\n controller: AbortController = new AbortController();\n\n #connectedPromise: Promise<Response | null>;\n #resolveConnectedPromise: (response: Response | null) => void = () => {};\n #rejectConnectedPromise: (error: AnthropicError) => void = () => {};\n\n #endPromise: Promise<void>;\n #resolveEndPromise: () => void = () => {};\n #rejectEndPromise: (error: AnthropicError) => void = () => {};\n\n #listeners: { [Event in keyof MessageStreamEvents]?: MessageStreamEventListeners<Event> } = {};\n\n #ended = false;\n #errored = false;\n #aborted = false;\n #catchingPromiseCreated = false;\n #response: Response | null | undefined;\n #request_id: string | null | undefined;\n\n constructor() {\n this.#connectedPromise = new Promise<Response | null>((resolve, reject) => {\n this.#resolveConnectedPromise = resolve;\n this.#rejectConnectedPromise = reject;\n });\n\n this.#endPromise = new Promise<void>((resolve, reject) => {\n this.#resolveEndPromise = resolve;\n this.#rejectEndPromise = reject;\n });\n\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n this.#connectedPromise.catch(() => {});\n this.#endPromise.catch(() => {});\n }\n\n get response(): Response | null | undefined {\n return this.#response;\n }\n\n get request_id(): string | null | undefined {\n return this.#request_id;\n }\n\n /**\n * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * This is the same as the `APIPromise.withResponse()` method.\n *\n * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`\n * as no `Response` is available.\n */\n async withResponse(): Promise<{\n data: BetaMessageStream;\n response: Response;\n request_id: string | null | undefined;\n }> {\n const response = await this.#connectedPromise;\n if (!response) {\n throw new Error('Could not resolve a `Response` object');\n }\n\n return {\n data: this,\n response,\n request_id: response.headers.get('request-id'),\n };\n }\n\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream: ReadableStream): BetaMessageStream {\n const runner = new BetaMessageStream();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n\n static createMessage(\n messages: BetaMessages,\n params: BetaMessageCreateParamsBase,\n options?: Core.RequestOptions,\n ): BetaMessageStream {\n const runner = new BetaMessageStream();\n for (const message of params.messages) {\n runner._addMessageParam(message);\n }\n runner._run(() =>\n runner._createMessage(\n messages,\n { ...params, stream: true },\n { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } },\n ),\n );\n return runner;\n }\n\n protected _run(executor: () => Promise<any>) {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, this.#handleError);\n }\n\n protected _addMessageParam(message: BetaMessageParam) {\n this.messages.push(message);\n }\n\n protected _addMessage(message: BetaMessage, emit = true) {\n this.receivedMessages.push(message);\n if (emit) {\n this._emit('message', message);\n }\n }\n\n protected async _createMessage(\n messages: BetaMessages,\n params: BetaMessageCreateParams,\n options?: Core.RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n const { response, data: stream } = await messages\n .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })\n .withResponse();\n this._connected(response);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n }\n\n protected _connected(response: Response | null) {\n if (this.ended) return;\n this.#response = response;\n this.#request_id = response?.headers.get('request-id');\n this.#resolveConnectedPromise(response);\n this._emit('connect');\n }\n\n get ended(): boolean {\n return this.#ended;\n }\n\n get errored(): boolean {\n return this.#errored;\n }\n\n get aborted(): boolean {\n return this.#aborted;\n }\n\n abort() {\n this.controller.abort();\n }\n\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this MessageStream, so that calls can be chained\n */\n on<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener });\n return this;\n }\n\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this MessageStream, so that calls can be chained\n */\n off<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners = this.#listeners[event];\n if (!listeners) return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0) listeners.splice(index, 1);\n return this;\n }\n\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this MessageStream, so that calls can be chained\n */\n once<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted<Event extends keyof MessageStreamEvents>(\n event: Event,\n ): Promise<\n Parameters<MessageStreamEvents[Event]> extends [infer Param] ? Param\n : Parameters<MessageStreamEvents[Event]> extends [] ? void\n : Parameters<MessageStreamEvents[Event]>\n > {\n return new Promise((resolve, reject) => {\n this.#catchingPromiseCreated = true;\n if (event !== 'error') this.once('error', reject);\n this.once(event, resolve as any);\n });\n }\n\n async done(): Promise<void> {\n this.#catchingPromiseCreated = true;\n await this.#endPromise;\n }\n\n get currentMessage(): BetaMessage | undefined {\n return this.#currentMessageSnapshot;\n }\n\n #getFinalMessage(): BetaMessage {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n return this.receivedMessages.at(-1)!;\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message response,\n * or rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalMessage(): Promise<BetaMessage> {\n await this.done();\n return this.#getFinalMessage();\n }\n\n #getFinalText(): string {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n const textBlocks = this.receivedMessages\n .at(-1)!\n .content.filter((block): block is BetaTextBlock => block.type === 'text')\n .map((block) => block.text);\n if (textBlocks.length === 0) {\n throw new AnthropicError('stream ended without producing a content block with type=text');\n }\n return textBlocks.join(' ');\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message's text response, concatenated\n * together if there are more than one text blocks.\n * Rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalText(): Promise<string> {\n await this.done();\n return this.#getFinalText();\n }\n\n #handleError = (error: unknown) => {\n this.#errored = true;\n if (error instanceof Error && error.name === 'AbortError') {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n this.#aborted = true;\n return this._emit('abort', error);\n }\n if (error instanceof AnthropicError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const anthropicError: AnthropicError = new AnthropicError(error.message);\n // @ts-ignore\n anthropicError.cause = error;\n return this._emit('error', anthropicError);\n }\n return this._emit('error', new AnthropicError(String(error)));\n };\n\n protected _emit<Event extends keyof MessageStreamEvents>(\n event: Event,\n ...args: Parameters<MessageStreamEvents[Event]>\n ) {\n // make sure we don't emit any MessageStreamEvents after end\n if (this.#ended) return;\n\n if (event === 'end') {\n this.#ended = true;\n this.#resolveEndPromise();\n }\n\n const listeners: MessageStreamEventListeners<Event> | undefined = this.#listeners[event];\n if (listeners) {\n this.#listeners[event] = listeners.filter((l) => !l.once) as any;\n listeners.forEach(({ listener }: any) => listener(...args));\n }\n\n if (event === 'abort') {\n const error = args[0] as APIUserAbortError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n return;\n }\n\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n\n const error = args[0] as AnthropicError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.final...()\n // - etc.\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n }\n }\n\n protected _emitFinal() {\n const finalMessage = this.receivedMessages.at(-1);\n if (finalMessage) {\n this._emit('finalMessage', this.#getFinalMessage());\n }\n }\n\n #beginRequest() {\n if (this.ended) return;\n this.#currentMessageSnapshot = undefined;\n }\n #addStreamEvent(event: BetaMessageStreamEvent) {\n if (this.ended) return;\n const messageSnapshot = this.#accumulateMessage(event);\n this._emit('streamEvent', event, messageSnapshot);\n\n switch (event.type) {\n case 'content_block_delta': {\n const content = messageSnapshot.content.at(-1)!;\n switch (event.delta.type) {\n case 'text_delta': {\n if (content.type === 'text') {\n this._emit('text', event.delta.text, content.text || '');\n }\n break;\n }\n case 'citations_delta': {\n if (content.type === 'text') {\n this._emit('citation', event.delta.citation, content.citations ?? []);\n }\n break;\n }\n case 'input_json_delta': {\n if (content.type === 'tool_use' && content.input) {\n this._emit('inputJson', event.delta.partial_json, content.input);\n }\n break;\n }\n case 'thinking_delta': {\n if (content.type === 'thinking') {\n this._emit('thinking', event.delta.thinking, content.thinking);\n }\n break;\n }\n case 'signature_delta': {\n if (content.type === 'thinking') {\n this._emit('signature', content.signature);\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n break;\n }\n case 'message_stop': {\n this._addMessageParam(messageSnapshot);\n this._addMessage(messageSnapshot, true);\n break;\n }\n case 'content_block_stop': {\n this._emit('contentBlock', messageSnapshot.content.at(-1)!);\n break;\n }\n case 'message_start': {\n this.#currentMessageSnapshot = messageSnapshot;\n break;\n }\n case 'content_block_start':\n case 'message_delta':\n break;\n }\n }\n #endRequest(): BetaMessage {\n if (this.ended) {\n throw new AnthropicError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = this.#currentMessageSnapshot;\n if (!snapshot) {\n throw new AnthropicError(`request ended without sending any chunks`);\n }\n this.#currentMessageSnapshot = undefined;\n return snapshot;\n }\n\n protected async _fromReadableStream(\n readableStream: ReadableStream,\n options?: Core.RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n this._connected(null);\n const stream = Stream.fromReadableStream<BetaMessageStreamEvent>(readableStream, this.controller);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n }\n\n /**\n * Mutates this.#currentMessage with the current event. Handling the accumulation of multiple messages\n * will be needed to be handled by the caller, this method will throw if you try to accumulate for multiple\n * messages.\n */\n #accumulateMessage(event: BetaMessageStreamEvent): BetaMessage {\n let snapshot = this.#currentMessageSnapshot;\n\n if (event.type === 'message_start') {\n if (snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving \"message_stop\"`);\n }\n return event.message;\n }\n\n if (!snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before \"message_start\"`);\n }\n\n switch (event.type) {\n case 'message_stop':\n return snapshot;\n case 'message_delta':\n snapshot.stop_reason = event.delta.stop_reason;\n snapshot.stop_sequence = event.delta.stop_sequence;\n snapshot.usage.output_tokens = event.usage.output_tokens;\n return snapshot;\n case 'content_block_start':\n snapshot.content.push(event.content_block);\n return snapshot;\n case 'content_block_delta': {\n const snapshotContent = snapshot.content.at(event.index);\n\n switch (event.delta.type) {\n case 'text_delta': {\n if (snapshotContent?.type === 'text') {\n snapshotContent.text += event.delta.text;\n }\n break;\n }\n case 'citations_delta': {\n if (snapshotContent?.type === 'text') {\n snapshotContent.citations ??= [];\n snapshotContent.citations.push(event.delta.citation);\n }\n break;\n }\n case 'input_json_delta': {\n if (snapshotContent?.type === 'tool_use') {\n // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = (snapshotContent as any)[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n\n Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n\n if (jsonBuf) {\n snapshotContent.input = partialParse(jsonBuf);\n }\n }\n break;\n }\n case 'thinking_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshotContent.thinking += event.delta.thinking;\n }\n break;\n }\n case 'signature_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshotContent.signature = event.delta.signature;\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n return snapshot;\n }\n case 'content_block_stop':\n return snapshot;\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<BetaMessageStreamEvent> {\n const pushQueue: BetaMessageStreamEvent[] = [];\n const readQueue: {\n resolve: (chunk: BetaMessageStreamEvent | undefined) => void;\n reject: (error: unknown) => void;\n }[] = [];\n let done = false;\n\n this.on('streamEvent', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n } else {\n pushQueue.push(event);\n }\n });\n\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n return {\n next: async (): Promise<IteratorResult<BetaMessageStreamEvent>> => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise<BetaMessageStreamEvent | undefined>((resolve, reject) =>\n readQueue.push({ resolve, reject }),\n ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift()!;\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n\n toReadableStream(): ReadableStream {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\n\n// used to ensure exhaustive case matching without throwing a runtime error\nfunction checkNever(x: never) {}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../../resource.js\";\nimport { APIPromise } from \"../../../core.js\";\nimport * as Core from \"../../../core.js\";\nimport * as MessagesMessagesAPI from \"./messages.js\";\nimport * as BetaAPI from \"../beta.js\";\nimport * as MessagesAPI from \"../../messages/messages.js\";\nimport * as BatchesAPI from \"./batches.js\";\nimport {\n BatchCancelParams,\n BatchCreateParams,\n BatchDeleteParams,\n BatchListParams,\n BatchResultsParams,\n BatchRetrieveParams,\n Batches,\n BetaDeletedMessageBatch,\n BetaMessageBatch,\n BetaMessageBatchCanceledResult,\n BetaMessageBatchErroredResult,\n BetaMessageBatchExpiredResult,\n BetaMessageBatchIndividualResponse,\n BetaMessageBatchRequestCounts,\n BetaMessageBatchResult,\n BetaMessageBatchSucceededResult,\n BetaMessageBatchesPage,\n} from \"./batches.js\";\nimport { Stream } from \"../../../streaming.js\";\nimport { BetaMessageStream } from \"../../../lib/BetaMessageStream.js\";\nimport type { Model } from \"../../messages/messages.js\";\n\nconst DEPRECATED_MODELS: {\n [K in Model]?: string;\n} = {\n 'claude-1.3': 'November 6th, 2024',\n 'claude-1.3-100k': 'November 6th, 2024',\n 'claude-instant-1.1': 'November 6th, 2024',\n 'claude-instant-1.1-100k': 'November 6th, 2024',\n 'claude-instant-1.2': 'November 6th, 2024',\n 'claude-3-sonnet-20240229': 'July 21st, 2025',\n 'claude-2.1': 'July 21st, 2025',\n 'claude-2.0': 'July 21st, 2025',\n};\n\nexport class Messages extends APIResource {\n batches: BatchesAPI.Batches = new BatchesAPI.Batches(this._client);\n\n /**\n * Send a structured list of input messages with text and/or image content, and the\n * model will generate the next message in the conversation.\n *\n * The Messages API can be used for either single queries or stateless multi-turn\n * conversations.\n *\n * Learn more about the Messages API in our [user guide](/en/docs/initial-setup)\n */\n create(params: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<BetaMessage>;\n create(\n params: MessageCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<BetaRawMessageStreamEvent>>;\n create(\n params: MessageCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<BetaRawMessageStreamEvent> | BetaMessage>;\n create(\n params: MessageCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<BetaMessage> | APIPromise<Stream<BetaRawMessageStreamEvent>> {\n const { betas, ...body } = params;\n\n if (body.model in DEPRECATED_MODELS) {\n console.warn(\n `The model '${body.model}' is deprecated and will reach end-of-life on ${\n DEPRECATED_MODELS[body.model]\n }\\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`,\n );\n }\n\n return this._client.post('/v1/messages?beta=true', {\n body,\n timeout:\n (this._client as any)._options.timeout ??\n (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)),\n ...options,\n headers: {\n ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),\n ...options?.headers,\n },\n stream: params.stream ?? false,\n }) as APIPromise<BetaMessage> | APIPromise<Stream<BetaRawMessageStreamEvent>>;\n }\n\n /**\n * Create a Message stream\n */\n stream(body: BetaMessageStreamParams, options?: Core.RequestOptions): BetaMessageStream {\n return BetaMessageStream.createMessage(this, body, options);\n }\n\n /**\n * Count the number of tokens in a Message.\n *\n * The Token Count API can be used to count the number of tokens in a Message,\n * including tools, images, and documents, without creating it.\n *\n * Learn more about token counting in our\n * [user guide](/en/docs/build-with-claude/token-counting)\n */\n countTokens(\n params: MessageCountTokensParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<BetaMessageTokensCount> {\n const { betas, ...body } = params;\n return this._client.post('/v1/messages/count_tokens?beta=true', {\n body,\n ...options,\n headers: {\n 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString(),\n ...options?.headers,\n },\n });\n }\n}\n\nexport type BetaMessageStreamParams = MessageCreateParamsBase;\n\nexport interface BetaBase64ImageSource {\n data: string;\n\n media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';\n\n type: 'base64';\n}\n\nexport interface BetaBase64PDFBlock {\n source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | BetaURLPDFSource;\n\n type: 'document';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n citations?: BetaCitationsConfigParam;\n\n context?: string | null;\n\n title?: string | null;\n}\n\nexport interface BetaBase64PDFSource {\n data: string;\n\n media_type: 'application/pdf';\n\n type: 'base64';\n}\n\nexport interface BetaCacheControlEphemeral {\n type: 'ephemeral';\n}\n\nexport interface BetaCitationCharLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface BetaCitationCharLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface BetaCitationContentBlockLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface BetaCitationContentBlockLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface BetaCitationPageLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface BetaCitationPageLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface BetaCitationsConfigParam {\n enabled?: boolean;\n}\n\nexport interface BetaCitationsDelta {\n citation: BetaCitationCharLocation | BetaCitationPageLocation | BetaCitationContentBlockLocation;\n\n type: 'citations_delta';\n}\n\nexport type BetaContentBlock =\n | BetaTextBlock\n | BetaToolUseBlock\n | BetaThinkingBlock\n | BetaRedactedThinkingBlock;\n\nexport type BetaContentBlockParam =\n | BetaTextBlockParam\n | BetaImageBlockParam\n | BetaToolUseBlockParam\n | BetaToolResultBlockParam\n | BetaBase64PDFBlock\n | BetaThinkingBlockParam\n | BetaRedactedThinkingBlockParam;\n\nexport interface BetaContentBlockSource {\n content: string | Array<BetaContentBlockSourceContent>;\n\n type: 'content';\n}\n\nexport type BetaContentBlockSourceContent = BetaTextBlockParam | BetaImageBlockParam;\n\nexport interface BetaImageBlockParam {\n source: BetaBase64ImageSource | BetaURLImageSource;\n\n type: 'image';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaInputJSONDelta {\n partial_json: string;\n\n type: 'input_json_delta';\n}\n\nexport interface BetaMessage {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * Content generated by the model.\n *\n * This is an array of content blocks, each of which has a `type` that determines\n * its shape.\n *\n * Example:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"Hi, I'm Claude.\" }]\n * ```\n *\n * If the request input `messages` ended with an `assistant` turn, then the\n * response `content` will continue directly from that last turn. You can use this\n * to constrain the model's output.\n *\n * For example, if the input `messages` were:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Then the response `content` might be:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"B)\" }]\n * ```\n */\n content: Array<BetaContentBlock>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Conversational role of the generated message.\n *\n * This will always be `\"assistant\"`.\n */\n role: 'assistant';\n\n /**\n * The reason that we stopped.\n *\n * This may be one the following values:\n *\n * - `\"end_turn\"`: the model reached a natural stopping point\n * - `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n * - `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n * - `\"tool_use\"`: the model invoked one or more tools\n *\n * In non-streaming mode this value is always non-null. In streaming mode, it is\n * null in the `message_start` event and non-null otherwise.\n */\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;\n\n /**\n * Which custom stop sequence was generated, if any.\n *\n * This value will be a non-null string if one of your custom stop sequences was\n * generated.\n */\n stop_sequence: string | null;\n\n /**\n * Object type.\n *\n * For Messages, this is always `\"message\"`.\n */\n type: 'message';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: BetaUsage;\n}\n\nexport interface BetaMessageDeltaUsage {\n /**\n * The cumulative number of output tokens which were used.\n */\n output_tokens: number;\n}\n\nexport interface BetaMessageParam {\n content: string | Array<BetaContentBlockParam>;\n\n role: 'user' | 'assistant';\n}\n\nexport interface BetaMessageTokensCount {\n /**\n * The total number of tokens across the provided list of messages, system prompt,\n * and tools.\n */\n input_tokens: number;\n}\n\nexport interface BetaMetadata {\n /**\n * An external identifier for the user who is associated with the request.\n *\n * This should be a uuid, hash value, or other opaque identifier. Anthropic may use\n * this id to help detect abuse. Do not include any identifying information such as\n * name, email address, or phone number.\n */\n user_id?: string | null;\n}\n\nexport interface BetaPlainTextSource {\n data: string;\n\n media_type: 'text/plain';\n\n type: 'text';\n}\n\nexport interface BetaRawContentBlockDeltaEvent {\n delta: BetaTextDelta | BetaInputJSONDelta | BetaCitationsDelta | BetaThinkingDelta | BetaSignatureDelta;\n\n index: number;\n\n type: 'content_block_delta';\n}\n\nexport interface BetaRawContentBlockStartEvent {\n content_block: BetaTextBlock | BetaToolUseBlock | BetaThinkingBlock | BetaRedactedThinkingBlock;\n\n index: number;\n\n type: 'content_block_start';\n}\n\nexport interface BetaRawContentBlockStopEvent {\n index: number;\n\n type: 'content_block_stop';\n}\n\nexport interface BetaRawMessageDeltaEvent {\n delta: BetaRawMessageDeltaEvent.Delta;\n\n type: 'message_delta';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: BetaMessageDeltaUsage;\n}\n\nexport namespace BetaRawMessageDeltaEvent {\n export interface Delta {\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;\n\n stop_sequence: string | null;\n }\n}\n\nexport interface BetaRawMessageStartEvent {\n message: BetaMessage;\n\n type: 'message_start';\n}\n\nexport interface BetaRawMessageStopEvent {\n type: 'message_stop';\n}\n\nexport type BetaRawMessageStreamEvent =\n | BetaRawMessageStartEvent\n | BetaRawMessageDeltaEvent\n | BetaRawMessageStopEvent\n | BetaRawContentBlockStartEvent\n | BetaRawContentBlockDeltaEvent\n | BetaRawContentBlockStopEvent;\n\nexport interface BetaRedactedThinkingBlock {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface BetaRedactedThinkingBlockParam {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface BetaSignatureDelta {\n signature: string;\n\n type: 'signature_delta';\n}\n\nexport interface BetaTextBlock {\n /**\n * Citations supporting the text block.\n *\n * The type of citation returned will depend on the type of document being cited.\n * Citing a PDF results in `page_location`, plain text results in `char_location`,\n * and content document results in `content_block_location`.\n */\n citations: Array<BetaTextCitation> | null;\n\n text: string;\n\n type: 'text';\n}\n\nexport interface BetaTextBlockParam {\n text: string;\n\n type: 'text';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n citations?: Array<BetaTextCitationParam> | null;\n}\n\nexport type BetaTextCitation =\n | BetaCitationCharLocation\n | BetaCitationPageLocation\n | BetaCitationContentBlockLocation;\n\nexport type BetaTextCitationParam =\n | BetaCitationCharLocationParam\n | BetaCitationPageLocationParam\n | BetaCitationContentBlockLocationParam;\n\nexport interface BetaTextDelta {\n text: string;\n\n type: 'text_delta';\n}\n\nexport interface BetaThinkingBlock {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface BetaThinkingBlockParam {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface BetaThinkingConfigDisabled {\n type: 'disabled';\n}\n\nexport interface BetaThinkingConfigEnabled {\n /**\n * Determines how many tokens Claude can use for its internal reasoning process.\n * Larger budgets can enable more thorough analysis for complex problems, improving\n * response quality.\n *\n * Must be \u22651024 and less than `max_tokens`.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n budget_tokens: number;\n\n type: 'enabled';\n}\n\n/**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\nexport type BetaThinkingConfigParam = BetaThinkingConfigEnabled | BetaThinkingConfigDisabled;\n\nexport interface BetaThinkingDelta {\n thinking: string;\n\n type: 'thinking_delta';\n}\n\nexport interface BetaTool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n input_schema: BetaTool.InputSchema;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: string;\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Description of what this tool does.\n *\n * Tool descriptions should be as detailed as possible. The more information that\n * the model has about what the tool is and how to use it, the better it will\n * perform. You can use natural language descriptions to reinforce important\n * aspects of the tool input JSON schema.\n */\n description?: string;\n\n type?: 'custom' | null;\n}\n\nexport namespace BetaTool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n export interface InputSchema {\n type: 'object';\n\n properties?: unknown | null;\n [k: string]: unknown;\n }\n}\n\nexport interface BetaToolBash20241022 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'bash';\n\n type: 'bash_20241022';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaToolBash20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'bash';\n\n type: 'bash_20250124';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\n/**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\nexport type BetaToolChoice = BetaToolChoiceAuto | BetaToolChoiceAny | BetaToolChoiceTool | BetaToolChoiceNone;\n\n/**\n * The model will use any available tools.\n */\nexport interface BetaToolChoiceAny {\n type: 'any';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will automatically decide whether to use tools.\n */\nexport interface BetaToolChoiceAuto {\n type: 'auto';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output at most one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will not be allowed to use tools.\n */\nexport interface BetaToolChoiceNone {\n type: 'none';\n}\n\n/**\n * The model will use the specified tool with `tool_choice.name`.\n */\nexport interface BetaToolChoiceTool {\n /**\n * The name of the tool to use.\n */\n name: string;\n\n type: 'tool';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\nexport interface BetaToolComputerUse20241022 {\n /**\n * The height of the display in pixels.\n */\n display_height_px: number;\n\n /**\n * The width of the display in pixels.\n */\n display_width_px: number;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'computer';\n\n type: 'computer_20241022';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * The X11 display number (e.g. 0, 1) for the display.\n */\n display_number?: number | null;\n}\n\nexport interface BetaToolComputerUse20250124 {\n /**\n * The height of the display in pixels.\n */\n display_height_px: number;\n\n /**\n * The width of the display in pixels.\n */\n display_width_px: number;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'computer';\n\n type: 'computer_20250124';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * The X11 display number (e.g. 0, 1) for the display.\n */\n display_number?: number | null;\n}\n\nexport interface BetaToolResultBlockParam {\n tool_use_id: string;\n\n type: 'tool_result';\n\n cache_control?: BetaCacheControlEphemeral | null;\n\n content?: string | Array<BetaTextBlockParam | BetaImageBlockParam>;\n\n is_error?: boolean;\n}\n\nexport interface BetaToolTextEditor20241022 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'str_replace_editor';\n\n type: 'text_editor_20241022';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaToolTextEditor20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'str_replace_editor';\n\n type: 'text_editor_20250124';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport type BetaToolUnion =\n | BetaTool\n | BetaToolComputerUse20241022\n | BetaToolBash20241022\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20250124\n | BetaToolBash20250124\n | BetaToolTextEditor20250124;\n\nexport interface BetaToolUseBlock {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n}\n\nexport interface BetaToolUseBlockParam {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaURLImageSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface BetaURLPDFSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface BetaUsage {\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number | null;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number | null;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n}\n\nexport type MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming;\n\nexport interface MessageCreateParamsBase {\n /**\n * Body param: The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n *\n * Different models have different maximum values for this parameter. See\n * [models](https://docs.anthropic.com/en/docs/models-overview) for details.\n */\n max_tokens: number;\n\n /**\n * Body param: Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * Starting with Claude 3 models, you can also send image content blocks:\n *\n * ```json\n * {\n * \"role\": \"user\",\n * \"content\": [\n * {\n * \"type\": \"image\",\n * \"source\": {\n * \"type\": \"base64\",\n * \"media_type\": \"image/jpeg\",\n * \"data\": \"/9j/4AAQSkZJRg...\"\n * }\n * },\n * { \"type\": \"text\", \"text\": \"What is in this image?\" }\n * ]\n * }\n * ```\n *\n * We currently support the `base64` source type for images, and the `image/jpeg`,\n * `image/png`, `image/gif`, and `image/webp` media types.\n *\n * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for\n * more input examples.\n *\n * Note that if you want to include a\n * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use\n * the top-level `system` parameter \u2014 there is no `\"system\"` role for input\n * messages in the Messages API.\n */\n messages: Array<BetaMessageParam>;\n\n /**\n * Body param: The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Body param: An object describing metadata about the request.\n */\n metadata?: BetaMetadata;\n\n /**\n * Body param: Custom text sequences that will cause the model to stop generating.\n *\n * Our models will normally stop when they have naturally completed their turn,\n * which will result in a response `stop_reason` of `\"end_turn\"`.\n *\n * If you want the model to stop generating when it encounters custom strings of\n * text, you can use the `stop_sequences` parameter. If the model encounters one of\n * the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"`\n * and the response `stop_sequence` value will contain the matched stop sequence.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream?: boolean;\n\n /**\n * Body param: System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).\n */\n system?: string | Array<BetaTextBlockParam>;\n\n /**\n * Body param: Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\n */\n temperature?: number;\n\n /**\n * Body param: Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: BetaThinkingConfigParam;\n\n /**\n * Body param: How the model should use the provided tools. The model can use a\n * specific tool, any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: BetaToolChoice;\n\n /**\n * Body param: Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.\n */\n tools?: Array<BetaToolUnion>;\n\n /**\n * Body param: Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Body param: Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_p?: number;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport namespace MessageCreateParams {\n export type MessageCreateParamsNonStreaming = MessagesMessagesAPI.MessageCreateParamsNonStreaming;\n export type MessageCreateParamsStreaming = MessagesMessagesAPI.MessageCreateParamsStreaming;\n}\n\nexport interface MessageCreateParamsNonStreaming extends MessageCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream?: false;\n}\n\nexport interface MessageCreateParamsStreaming extends MessageCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream: true;\n}\n\nexport interface MessageCountTokensParams {\n /**\n * Body param: Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * Starting with Claude 3 models, you can also send image content blocks:\n *\n * ```json\n * {\n * \"role\": \"user\",\n * \"content\": [\n * {\n * \"type\": \"image\",\n * \"source\": {\n * \"type\": \"base64\",\n * \"media_type\": \"image/jpeg\",\n * \"data\": \"/9j/4AAQSkZJRg...\"\n * }\n * },\n * { \"type\": \"text\", \"text\": \"What is in this image?\" }\n * ]\n * }\n * ```\n *\n * We currently support the `base64` source type for images, and the `image/jpeg`,\n * `image/png`, `image/gif`, and `image/webp` media types.\n *\n * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for\n * more input examples.\n *\n * Note that if you want to include a\n * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use\n * the top-level `system` parameter \u2014 there is no `\"system\"` role for input\n * messages in the Messages API.\n */\n messages: Array<BetaMessageParam>;\n\n /**\n * Body param: The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Body param: System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).\n */\n system?: string | Array<BetaTextBlockParam>;\n\n /**\n * Body param: Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: BetaThinkingConfigParam;\n\n /**\n * Body param: How the model should use the provided tools. The model can use a\n * specific tool, any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: BetaToolChoice;\n\n /**\n * Body param: Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.\n */\n tools?: Array<\n | BetaTool\n | BetaToolComputerUse20241022\n | BetaToolBash20241022\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20250124\n | BetaToolBash20250124\n | BetaToolTextEditor20250124\n >;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nMessages.Batches = Batches;\nMessages.BetaMessageBatchesPage = BetaMessageBatchesPage;\n\nexport declare namespace Messages {\n export {\n type BetaBase64ImageSource as BetaBase64ImageSource,\n type BetaBase64PDFBlock as BetaBase64PDFBlock,\n type BetaBase64PDFSource as BetaBase64PDFSource,\n type BetaCacheControlEphemeral as BetaCacheControlEphemeral,\n type BetaCitationCharLocation as BetaCitationCharLocation,\n type BetaCitationCharLocationParam as BetaCitationCharLocationParam,\n type BetaCitationContentBlockLocation as BetaCitationContentBlockLocation,\n type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,\n type BetaCitationPageLocation as BetaCitationPageLocation,\n type BetaCitationPageLocationParam as BetaCitationPageLocationParam,\n type BetaCitationsConfigParam as BetaCitationsConfigParam,\n type BetaCitationsDelta as BetaCitationsDelta,\n type BetaContentBlock as BetaContentBlock,\n type BetaContentBlockParam as BetaContentBlockParam,\n type BetaContentBlockSource as BetaContentBlockSource,\n type BetaContentBlockSourceContent as BetaContentBlockSourceContent,\n type BetaImageBlockParam as BetaImageBlockParam,\n type BetaInputJSONDelta as BetaInputJSONDelta,\n type BetaMessage as BetaMessage,\n type BetaMessageDeltaUsage as BetaMessageDeltaUsage,\n type BetaMessageParam as BetaMessageParam,\n type BetaMessageTokensCount as BetaMessageTokensCount,\n type BetaMetadata as BetaMetadata,\n type BetaPlainTextSource as BetaPlainTextSource,\n type BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent,\n type BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent,\n type BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent,\n type BetaRawMessageDeltaEvent as BetaRawMessageDeltaEvent,\n type BetaRawMessageStartEvent as BetaRawMessageStartEvent,\n type BetaRawMessageStopEvent as BetaRawMessageStopEvent,\n type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,\n type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,\n type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,\n type BetaSignatureDelta as BetaSignatureDelta,\n type BetaTextBlock as BetaTextBlock,\n type BetaTextBlockParam as BetaTextBlockParam,\n type BetaTextCitation as BetaTextCitation,\n type BetaTextCitationParam as BetaTextCitationParam,\n type BetaTextDelta as BetaTextDelta,\n type BetaThinkingBlock as BetaThinkingBlock,\n type BetaThinkingBlockParam as BetaThinkingBlockParam,\n type BetaThinkingConfigDisabled as BetaThinkingConfigDisabled,\n type BetaThinkingConfigEnabled as BetaThinkingConfigEnabled,\n type BetaThinkingConfigParam as BetaThinkingConfigParam,\n type BetaThinkingDelta as BetaThinkingDelta,\n type BetaTool as BetaTool,\n type BetaToolBash20241022 as BetaToolBash20241022,\n type BetaToolBash20250124 as BetaToolBash20250124,\n type BetaToolChoice as BetaToolChoice,\n type BetaToolChoiceAny as BetaToolChoiceAny,\n type BetaToolChoiceAuto as BetaToolChoiceAuto,\n type BetaToolChoiceNone as BetaToolChoiceNone,\n type BetaToolChoiceTool as BetaToolChoiceTool,\n type BetaToolComputerUse20241022 as BetaToolComputerUse20241022,\n type BetaToolComputerUse20250124 as BetaToolComputerUse20250124,\n type BetaToolResultBlockParam as BetaToolResultBlockParam,\n type BetaToolTextEditor20241022 as BetaToolTextEditor20241022,\n type BetaToolTextEditor20250124 as BetaToolTextEditor20250124,\n type BetaToolUnion as BetaToolUnion,\n type BetaToolUseBlock as BetaToolUseBlock,\n type BetaToolUseBlockParam as BetaToolUseBlockParam,\n type BetaURLImageSource as BetaURLImageSource,\n type BetaURLPDFSource as BetaURLPDFSource,\n type BetaUsage as BetaUsage,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export {\n Batches as Batches,\n type BetaDeletedMessageBatch as BetaDeletedMessageBatch,\n type BetaMessageBatch as BetaMessageBatch,\n type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult,\n type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult,\n type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult,\n type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse,\n type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts,\n type BetaMessageBatchResult as BetaMessageBatchResult,\n type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult,\n BetaMessageBatchesPage as BetaMessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchRetrieveParams as BatchRetrieveParams,\n type BatchListParams as BatchListParams,\n type BatchDeleteParams as BatchDeleteParams,\n type BatchCancelParams as BatchCancelParams,\n type BatchResultsParams as BatchResultsParams,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../resource.js\";\nimport * as ModelsAPI from \"./models.js\";\nimport { BetaModelInfo, BetaModelInfosPage, ModelListParams, Models } from \"./models.js\";\nimport * as MessagesAPI from \"./messages/messages.js\";\nimport {\n BetaBase64ImageSource,\n BetaBase64PDFBlock,\n BetaBase64PDFSource,\n BetaCacheControlEphemeral,\n BetaCitationCharLocation,\n BetaCitationCharLocationParam,\n BetaCitationContentBlockLocation,\n BetaCitationContentBlockLocationParam,\n BetaCitationPageLocation,\n BetaCitationPageLocationParam,\n BetaCitationsConfigParam,\n BetaCitationsDelta,\n BetaContentBlock,\n BetaContentBlockParam,\n BetaContentBlockSource,\n BetaContentBlockSourceContent,\n BetaImageBlockParam,\n BetaInputJSONDelta,\n BetaMessage,\n BetaMessageDeltaUsage,\n BetaMessageParam,\n BetaMessageTokensCount,\n BetaMetadata,\n BetaPlainTextSource,\n BetaRawContentBlockDeltaEvent,\n BetaRawContentBlockStartEvent,\n BetaRawContentBlockStopEvent,\n BetaRawMessageDeltaEvent,\n BetaRawMessageStartEvent,\n BetaRawMessageStopEvent,\n BetaRawMessageStreamEvent,\n BetaRedactedThinkingBlock,\n BetaRedactedThinkingBlockParam,\n BetaSignatureDelta,\n BetaTextBlock,\n BetaTextBlockParam,\n BetaTextCitation,\n BetaTextCitationParam,\n BetaTextDelta,\n BetaThinkingBlock,\n BetaThinkingBlockParam,\n BetaThinkingConfigDisabled,\n BetaThinkingConfigEnabled,\n BetaThinkingConfigParam,\n BetaThinkingDelta,\n BetaTool,\n BetaToolBash20241022,\n BetaToolBash20250124,\n BetaToolChoice,\n BetaToolChoiceAny,\n BetaToolChoiceAuto,\n BetaToolChoiceNone,\n BetaToolChoiceTool,\n BetaToolComputerUse20241022,\n BetaToolComputerUse20250124,\n BetaToolResultBlockParam,\n BetaToolTextEditor20241022,\n BetaToolTextEditor20250124,\n BetaToolUnion,\n BetaToolUseBlock,\n BetaToolUseBlockParam,\n BetaURLImageSource,\n BetaURLPDFSource,\n BetaUsage,\n MessageCountTokensParams,\n MessageCreateParams,\n MessageCreateParamsNonStreaming,\n MessageCreateParamsStreaming,\n Messages,\n} from \"./messages/messages.js\";\n\nexport class Beta extends APIResource {\n models: ModelsAPI.Models = new ModelsAPI.Models(this._client);\n messages: MessagesAPI.Messages = new MessagesAPI.Messages(this._client);\n}\n\nexport type AnthropicBeta =\n | (string & {})\n | 'message-batches-2024-09-24'\n | 'prompt-caching-2024-07-31'\n | 'computer-use-2024-10-22'\n | 'computer-use-2025-01-24'\n | 'pdfs-2024-09-25'\n | 'token-counting-2024-11-01'\n | 'token-efficient-tools-2025-02-19'\n | 'output-128k-2025-02-19';\n\nexport interface BetaAPIError {\n message: string;\n\n type: 'api_error';\n}\n\nexport interface BetaAuthenticationError {\n message: string;\n\n type: 'authentication_error';\n}\n\nexport interface BetaBillingError {\n message: string;\n\n type: 'billing_error';\n}\n\nexport type BetaError =\n | BetaInvalidRequestError\n | BetaAuthenticationError\n | BetaBillingError\n | BetaPermissionError\n | BetaNotFoundError\n | BetaRateLimitError\n | BetaGatewayTimeoutError\n | BetaAPIError\n | BetaOverloadedError;\n\nexport interface BetaErrorResponse {\n error: BetaError;\n\n type: 'error';\n}\n\nexport interface BetaGatewayTimeoutError {\n message: string;\n\n type: 'timeout_error';\n}\n\nexport interface BetaInvalidRequestError {\n message: string;\n\n type: 'invalid_request_error';\n}\n\nexport interface BetaNotFoundError {\n message: string;\n\n type: 'not_found_error';\n}\n\nexport interface BetaOverloadedError {\n message: string;\n\n type: 'overloaded_error';\n}\n\nexport interface BetaPermissionError {\n message: string;\n\n type: 'permission_error';\n}\n\nexport interface BetaRateLimitError {\n message: string;\n\n type: 'rate_limit_error';\n}\n\nBeta.Models = Models;\nBeta.BetaModelInfosPage = BetaModelInfosPage;\nBeta.Messages = Messages;\n\nexport declare namespace Beta {\n export {\n type AnthropicBeta as AnthropicBeta,\n type BetaAPIError as BetaAPIError,\n type BetaAuthenticationError as BetaAuthenticationError,\n type BetaBillingError as BetaBillingError,\n type BetaError as BetaError,\n type BetaErrorResponse as BetaErrorResponse,\n type BetaGatewayTimeoutError as BetaGatewayTimeoutError,\n type BetaInvalidRequestError as BetaInvalidRequestError,\n type BetaNotFoundError as BetaNotFoundError,\n type BetaOverloadedError as BetaOverloadedError,\n type BetaPermissionError as BetaPermissionError,\n type BetaRateLimitError as BetaRateLimitError,\n };\n\n export {\n Models as Models,\n type BetaModelInfo as BetaModelInfo,\n BetaModelInfosPage as BetaModelInfosPage,\n type ModelListParams as ModelListParams,\n };\n\n export {\n Messages as Messages,\n type BetaBase64ImageSource as BetaBase64ImageSource,\n type BetaBase64PDFBlock as BetaBase64PDFBlock,\n type BetaBase64PDFSource as BetaBase64PDFSource,\n type BetaCacheControlEphemeral as BetaCacheControlEphemeral,\n type BetaCitationCharLocation as BetaCitationCharLocation,\n type BetaCitationCharLocationParam as BetaCitationCharLocationParam,\n type BetaCitationContentBlockLocation as BetaCitationContentBlockLocation,\n type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,\n type BetaCitationPageLocation as BetaCitationPageLocation,\n type BetaCitationPageLocationParam as BetaCitationPageLocationParam,\n type BetaCitationsConfigParam as BetaCitationsConfigParam,\n type BetaCitationsDelta as BetaCitationsDelta,\n type BetaContentBlock as BetaContentBlock,\n type BetaContentBlockParam as BetaContentBlockParam,\n type BetaContentBlockSource as BetaContentBlockSource,\n type BetaContentBlockSourceContent as BetaContentBlockSourceContent,\n type BetaImageBlockParam as BetaImageBlockParam,\n type BetaInputJSONDelta as BetaInputJSONDelta,\n type BetaMessage as BetaMessage,\n type BetaMessageDeltaUsage as BetaMessageDeltaUsage,\n type BetaMessageParam as BetaMessageParam,\n type BetaMessageTokensCount as BetaMessageTokensCount,\n type BetaMetadata as BetaMetadata,\n type BetaPlainTextSource as BetaPlainTextSource,\n type BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent,\n type BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent,\n type BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent,\n type BetaRawMessageDeltaEvent as BetaRawMessageDeltaEvent,\n type BetaRawMessageStartEvent as BetaRawMessageStartEvent,\n type BetaRawMessageStopEvent as BetaRawMessageStopEvent,\n type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,\n type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,\n type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,\n type BetaSignatureDelta as BetaSignatureDelta,\n type BetaTextBlock as BetaTextBlock,\n type BetaTextBlockParam as BetaTextBlockParam,\n type BetaTextCitation as BetaTextCitation,\n type BetaTextCitationParam as BetaTextCitationParam,\n type BetaTextDelta as BetaTextDelta,\n type BetaThinkingBlock as BetaThinkingBlock,\n type BetaThinkingBlockParam as BetaThinkingBlockParam,\n type BetaThinkingConfigDisabled as BetaThinkingConfigDisabled,\n type BetaThinkingConfigEnabled as BetaThinkingConfigEnabled,\n type BetaThinkingConfigParam as BetaThinkingConfigParam,\n type BetaThinkingDelta as BetaThinkingDelta,\n type BetaTool as BetaTool,\n type BetaToolBash20241022 as BetaToolBash20241022,\n type BetaToolBash20250124 as BetaToolBash20250124,\n type BetaToolChoice as BetaToolChoice,\n type BetaToolChoiceAny as BetaToolChoiceAny,\n type BetaToolChoiceAuto as BetaToolChoiceAuto,\n type BetaToolChoiceNone as BetaToolChoiceNone,\n type BetaToolChoiceTool as BetaToolChoiceTool,\n type BetaToolComputerUse20241022 as BetaToolComputerUse20241022,\n type BetaToolComputerUse20250124 as BetaToolComputerUse20250124,\n type BetaToolResultBlockParam as BetaToolResultBlockParam,\n type BetaToolTextEditor20241022 as BetaToolTextEditor20241022,\n type BetaToolTextEditor20250124 as BetaToolTextEditor20250124,\n type BetaToolUnion as BetaToolUnion,\n type BetaToolUseBlock as BetaToolUseBlock,\n type BetaToolUseBlockParam as BetaToolUseBlockParam,\n type BetaURLImageSource as BetaURLImageSource,\n type BetaURLPDFSource as BetaURLPDFSource,\n type BetaUsage as BetaUsage,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../resource.js\";\nimport { APIPromise } from \"../core.js\";\nimport * as Core from \"../core.js\";\nimport * as CompletionsAPI from \"./completions.js\";\nimport * as MessagesAPI from \"./messages/messages.js\";\nimport { Stream } from \"../streaming.js\";\n\nexport class Completions extends APIResource {\n /**\n * [Legacy] Create a Text Completion.\n *\n * The Text Completions API is a legacy API. We recommend using the\n * [Messages API](https://docs.anthropic.com/en/api/messages) going forward.\n *\n * Future models and features will not be compatible with Text Completions. See our\n * [migration guide](https://docs.anthropic.com/en/api/migrating-from-text-completions-to-messages)\n * for guidance in migrating from Text Completions to Messages.\n */\n create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;\n create(\n body: CompletionCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<Completion>>;\n create(\n body: CompletionCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<Completion> | Completion>;\n create(\n body: CompletionCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<Completion> | APIPromise<Stream<Completion>> {\n return this._client.post('/v1/complete', {\n body,\n timeout: (this._client as any)._options.timeout ?? 600000,\n ...options,\n stream: body.stream ?? false,\n }) as APIPromise<Completion> | APIPromise<Stream<Completion>>;\n }\n}\n\nexport interface Completion {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * The resulting completion up to and excluding the stop sequences.\n */\n completion: string;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * The reason that we stopped.\n *\n * This may be one the following values:\n *\n * - `\"stop_sequence\"`: we reached a stop sequence \u2014 either provided by you via the\n * `stop_sequences` parameter, or a stop sequence built into the model\n * - `\"max_tokens\"`: we exceeded `max_tokens_to_sample` or the model's maximum\n */\n stop_reason: string | null;\n\n /**\n * Object type.\n *\n * For Text Completions, this is always `\"completion\"`.\n */\n type: 'completion';\n}\n\nexport type CompletionCreateParams = CompletionCreateParamsNonStreaming | CompletionCreateParamsStreaming;\n\nexport interface CompletionCreateParamsBase {\n /**\n * The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n */\n max_tokens_to_sample: number;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * The prompt that you want Claude to complete.\n *\n * For proper response generation you will need to format your prompt using\n * alternating `\\n\\nHuman:` and `\\n\\nAssistant:` conversational turns. For example:\n *\n * ```\n * \"\\n\\nHuman: {userQuestion}\\n\\nAssistant:\"\n * ```\n *\n * See [prompt validation](https://docs.anthropic.com/en/api/prompt-validation) and\n * our guide to\n * [prompt design](https://docs.anthropic.com/en/docs/intro-to-prompting) for more\n * details.\n */\n prompt: string;\n\n /**\n * An object describing metadata about the request.\n */\n metadata?: MessagesAPI.Metadata;\n\n /**\n * Sequences that will cause the model to stop generating.\n *\n * Our models stop on `\"\\n\\nHuman:\"`, and may include additional built-in stop\n * sequences in the future. By providing the stop_sequences parameter, you may\n * include additional strings that will cause the model to stop generating.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/streaming) for details.\n */\n stream?: boolean;\n\n /**\n * Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\n */\n temperature?: number;\n\n /**\n * Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_p?: number;\n}\n\nexport namespace CompletionCreateParams {\n /**\n * @deprecated use `Anthropic.Messages.Metadata` instead\n */\n export type Metadata = MessagesAPI.Metadata;\n\n export type CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming;\n export type CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming;\n}\n\nexport interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase {\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/streaming) for details.\n */\n stream?: false;\n}\n\nexport interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase {\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/streaming) for details.\n */\n stream: true;\n}\n\nexport declare namespace Completions {\n export {\n type Completion as Completion,\n type CompletionCreateParams as CompletionCreateParams,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../resource.js\";\nimport { isRequestOptions } from \"../../core.js\";\nimport * as Core from \"../../core.js\";\nimport * as Shared from \"../shared.js\";\nimport * as MessagesAPI from \"./messages.js\";\nimport { Page, type PageParams } from \"../../pagination.js\";\nimport { JSONLDecoder } from \"../../internal/decoders/jsonl.js\";\nimport { AnthropicError } from \"../../error.js\";\n\nexport class Batches extends APIResource {\n /**\n * Send a batch of Message creation requests.\n *\n * The Message Batches API can be used to process multiple Messages API requests at\n * once. Once a Message Batch is created, it begins processing immediately. Batches\n * can take up to 24 hours to complete.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {\n return this._client.post('/v1/messages/batches', { body, ...options });\n }\n\n /**\n * This endpoint is idempotent and can be used to poll for Message Batch\n * completion. To access the results of a Message Batch, make a request to the\n * `results_url` field in the response.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {\n return this._client.get(`/v1/messages/batches/${messageBatchId}`, options);\n }\n\n /**\n * List all Message Batches within a Workspace. Most recently created batches are\n * returned first.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n list(\n query?: BatchListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<MessageBatchesPage, MessageBatch>;\n list(options?: Core.RequestOptions): Core.PagePromise<MessageBatchesPage, MessageBatch>;\n list(\n query: BatchListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<MessageBatchesPage, MessageBatch> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/v1/messages/batches', MessageBatchesPage, { query, ...options });\n }\n\n /**\n * Delete a Message Batch.\n *\n * Message Batches can only be deleted once they've finished processing. If you'd\n * like to delete an in-progress batch, you must first cancel it.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n delete(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<DeletedMessageBatch> {\n return this._client.delete(`/v1/messages/batches/${messageBatchId}`, options);\n }\n\n /**\n * Batches may be canceled any time before processing ends. Once cancellation is\n * initiated, the batch enters a `canceling` state, at which time the system may\n * complete any in-progress, non-interruptible requests before finalizing\n * cancellation.\n *\n * The number of canceled requests is specified in `request_counts`. To determine\n * which requests were canceled, check the individual results within the batch.\n * Note that cancellation may not result in any canceled requests if they were\n * non-interruptible.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {\n return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel`, options);\n }\n\n /**\n * Streams the results of a Message Batch as a `.jsonl` file.\n *\n * Each line in the file is a JSON object containing the result of a single request\n * in the Message Batch. Results are not guaranteed to be in the same order as\n * requests. Use the `custom_id` field to match results to requests.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n */\n async results(\n messageBatchId: string,\n options?: Core.RequestOptions,\n ): Promise<JSONLDecoder<MessageBatchIndividualResponse>> {\n const batch = await this.retrieve(messageBatchId);\n if (!batch.results_url) {\n throw new AnthropicError(\n `No batch \\`results_url\\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`,\n );\n }\n\n return this._client\n .get(batch.results_url, {\n ...options,\n headers: {\n Accept: 'application/binary',\n ...options?.headers,\n },\n __binaryResponse: true,\n })\n ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));\n }\n}\n\nexport class MessageBatchesPage extends Page<MessageBatch> {}\n\nexport interface DeletedMessageBatch {\n /**\n * ID of the Message Batch.\n */\n id: string;\n\n /**\n * Deleted object type.\n *\n * For Message Batches, this is always `\"message_batch_deleted\"`.\n */\n type: 'message_batch_deleted';\n}\n\nexport interface MessageBatch {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * archived and its results became unavailable.\n */\n archived_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which cancellation was\n * initiated for the Message Batch. Specified only if cancellation was initiated.\n */\n cancel_initiated_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * created.\n */\n created_at: string;\n\n /**\n * RFC 3339 datetime string representing the time at which processing for the\n * Message Batch ended. Specified only once processing ends.\n *\n * Processing ends when every request in a Message Batch has either succeeded,\n * errored, canceled, or expired.\n */\n ended_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch will\n * expire and end processing, which is 24 hours after creation.\n */\n expires_at: string;\n\n /**\n * Processing status of the Message Batch.\n */\n processing_status: 'in_progress' | 'canceling' | 'ended';\n\n /**\n * Tallies requests within the Message Batch, categorized by their status.\n *\n * Requests start as `processing` and move to one of the other statuses only once\n * processing of the entire batch ends. The sum of all values always matches the\n * total number of requests in the batch.\n */\n request_counts: MessageBatchRequestCounts;\n\n /**\n * URL to a `.jsonl` file containing the results of the Message Batch requests.\n * Specified only once processing ends.\n *\n * Results in the file are not guaranteed to be in the same order as requests. Use\n * the `custom_id` field to match results to requests.\n */\n results_url: string | null;\n\n /**\n * Object type.\n *\n * For Message Batches, this is always `\"message_batch\"`.\n */\n type: 'message_batch';\n}\n\nexport interface MessageBatchCanceledResult {\n type: 'canceled';\n}\n\nexport interface MessageBatchErroredResult {\n error: Shared.ErrorResponse;\n\n type: 'errored';\n}\n\nexport interface MessageBatchExpiredResult {\n type: 'expired';\n}\n\n/**\n * This is a single line in the response `.jsonl` file and does not represent the\n * response as a whole.\n */\nexport interface MessageBatchIndividualResponse {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\n result: MessageBatchResult;\n}\n\nexport interface MessageBatchRequestCounts {\n /**\n * Number of requests in the Message Batch that have been canceled.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n canceled: number;\n\n /**\n * Number of requests in the Message Batch that encountered an error.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n errored: number;\n\n /**\n * Number of requests in the Message Batch that have expired.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n expired: number;\n\n /**\n * Number of requests in the Message Batch that are processing.\n */\n processing: number;\n\n /**\n * Number of requests in the Message Batch that have completed successfully.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n succeeded: number;\n}\n\n/**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\nexport type MessageBatchResult =\n | MessageBatchSucceededResult\n | MessageBatchErroredResult\n | MessageBatchCanceledResult\n | MessageBatchExpiredResult;\n\nexport interface MessageBatchSucceededResult {\n message: MessagesAPI.Message;\n\n type: 'succeeded';\n}\n\nexport interface BatchCreateParams {\n /**\n * List of requests for prompt completion. Each is an individual request to create\n * a Message.\n */\n requests: Array<BatchCreateParams.Request>;\n}\n\nexport namespace BatchCreateParams {\n export interface Request {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Messages API creation parameters for the individual request.\n *\n * See the [Messages API reference](/en/api/messages) for full documentation on\n * available parameters.\n */\n params: MessagesAPI.MessageCreateParamsNonStreaming;\n }\n}\n\nexport interface BatchListParams extends PageParams {}\n\nBatches.MessageBatchesPage = MessageBatchesPage;\n\nexport declare namespace Batches {\n export {\n type DeletedMessageBatch as DeletedMessageBatch,\n type MessageBatch as MessageBatch,\n type MessageBatchCanceledResult as MessageBatchCanceledResult,\n type MessageBatchErroredResult as MessageBatchErroredResult,\n type MessageBatchExpiredResult as MessageBatchExpiredResult,\n type MessageBatchIndividualResponse as MessageBatchIndividualResponse,\n type MessageBatchRequestCounts as MessageBatchRequestCounts,\n type MessageBatchResult as MessageBatchResult,\n type MessageBatchSucceededResult as MessageBatchSucceededResult,\n MessageBatchesPage as MessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchListParams as BatchListParams,\n };\n}\n", "import * as Core from \"../core.js\";\nimport { AnthropicError, APIUserAbortError } from \"../error.js\";\nimport {\n type ContentBlock,\n Messages,\n type Message,\n type MessageStreamEvent,\n type MessageParam,\n type MessageCreateParams,\n type MessageCreateParamsBase,\n type TextBlock,\n type TextCitation,\n} from \"../resources/messages.js\";\nimport { type ReadableStream, type Response } from \"../_shims/index.js\";\nimport { Stream } from \"../streaming.js\";\nimport { partialParse } from \"../_vendor/partial-json-parser/parser.js\";\n\nexport interface MessageStreamEvents {\n connect: () => void;\n streamEvent: (event: MessageStreamEvent, snapshot: Message) => void;\n text: (textDelta: string, textSnapshot: string) => void;\n citation: (citation: TextCitation, citationsSnapshot: TextCitation[]) => void;\n inputJson: (partialJson: string, jsonSnapshot: unknown) => void;\n thinking: (thinkingDelta: string, thinkingSnapshot: string) => void;\n signature: (signature: string) => void;\n message: (message: Message) => void;\n contentBlock: (content: ContentBlock) => void;\n finalMessage: (message: Message) => void;\n error: (error: AnthropicError) => void;\n abort: (error: APIUserAbortError) => void;\n end: () => void;\n}\n\ntype MessageStreamEventListeners<Event extends keyof MessageStreamEvents> = {\n listener: MessageStreamEvents[Event];\n once?: boolean;\n}[];\n\nconst JSON_BUF_PROPERTY = '__json_buf';\n\nexport class MessageStream implements AsyncIterable<MessageStreamEvent> {\n messages: MessageParam[] = [];\n receivedMessages: Message[] = [];\n #currentMessageSnapshot: Message | undefined;\n\n controller: AbortController = new AbortController();\n\n #connectedPromise: Promise<Response | null>;\n #resolveConnectedPromise: (response: Response | null) => void = () => {};\n #rejectConnectedPromise: (error: AnthropicError) => void = () => {};\n\n #endPromise: Promise<void>;\n #resolveEndPromise: () => void = () => {};\n #rejectEndPromise: (error: AnthropicError) => void = () => {};\n\n #listeners: { [Event in keyof MessageStreamEvents]?: MessageStreamEventListeners<Event> } = {};\n\n #ended = false;\n #errored = false;\n #aborted = false;\n #catchingPromiseCreated = false;\n #response: Response | null | undefined;\n #request_id: string | null | undefined;\n\n constructor() {\n this.#connectedPromise = new Promise<Response | null>((resolve, reject) => {\n this.#resolveConnectedPromise = resolve;\n this.#rejectConnectedPromise = reject;\n });\n\n this.#endPromise = new Promise<void>((resolve, reject) => {\n this.#resolveEndPromise = resolve;\n this.#rejectEndPromise = reject;\n });\n\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n this.#connectedPromise.catch(() => {});\n this.#endPromise.catch(() => {});\n }\n\n get response(): Response | null | undefined {\n return this.#response;\n }\n\n get request_id(): string | null | undefined {\n return this.#request_id;\n }\n\n /**\n * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * This is the same as the `APIPromise.withResponse()` method.\n *\n * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`\n * as no `Response` is available.\n */\n async withResponse(): Promise<{\n data: MessageStream;\n response: Response;\n request_id: string | null | undefined;\n }> {\n const response = await this.#connectedPromise;\n if (!response) {\n throw new Error('Could not resolve a `Response` object');\n }\n\n return {\n data: this,\n response,\n request_id: response.headers.get('request-id'),\n };\n }\n\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream: ReadableStream): MessageStream {\n const runner = new MessageStream();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n\n static createMessage(\n messages: Messages,\n params: MessageCreateParamsBase,\n options?: Core.RequestOptions,\n ): MessageStream {\n const runner = new MessageStream();\n for (const message of params.messages) {\n runner._addMessageParam(message);\n }\n runner._run(() =>\n runner._createMessage(\n messages,\n { ...params, stream: true },\n { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } },\n ),\n );\n return runner;\n }\n\n protected _run(executor: () => Promise<any>) {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, this.#handleError);\n }\n\n protected _addMessageParam(message: MessageParam) {\n this.messages.push(message);\n }\n\n protected _addMessage(message: Message, emit = true) {\n this.receivedMessages.push(message);\n if (emit) {\n this._emit('message', message);\n }\n }\n\n protected async _createMessage(\n messages: Messages,\n params: MessageCreateParams,\n options?: Core.RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n const { response, data: stream } = await messages\n .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })\n .withResponse();\n this._connected(response);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n }\n\n protected _connected(response: Response | null) {\n if (this.ended) return;\n this.#response = response;\n this.#request_id = response?.headers.get('request-id');\n this.#resolveConnectedPromise(response);\n this._emit('connect');\n }\n\n get ended(): boolean {\n return this.#ended;\n }\n\n get errored(): boolean {\n return this.#errored;\n }\n\n get aborted(): boolean {\n return this.#aborted;\n }\n\n abort() {\n this.controller.abort();\n }\n\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this MessageStream, so that calls can be chained\n */\n on<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener });\n return this;\n }\n\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this MessageStream, so that calls can be chained\n */\n off<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners = this.#listeners[event];\n if (!listeners) return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0) listeners.splice(index, 1);\n return this;\n }\n\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this MessageStream, so that calls can be chained\n */\n once<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted<Event extends keyof MessageStreamEvents>(\n event: Event,\n ): Promise<\n Parameters<MessageStreamEvents[Event]> extends [infer Param] ? Param\n : Parameters<MessageStreamEvents[Event]> extends [] ? void\n : Parameters<MessageStreamEvents[Event]>\n > {\n return new Promise((resolve, reject) => {\n this.#catchingPromiseCreated = true;\n if (event !== 'error') this.once('error', reject);\n this.once(event, resolve as any);\n });\n }\n\n async done(): Promise<void> {\n this.#catchingPromiseCreated = true;\n await this.#endPromise;\n }\n\n get currentMessage(): Message | undefined {\n return this.#currentMessageSnapshot;\n }\n\n #getFinalMessage(): Message {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n return this.receivedMessages.at(-1)!;\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message response,\n * or rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalMessage(): Promise<Message> {\n await this.done();\n return this.#getFinalMessage();\n }\n\n #getFinalText(): string {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n const textBlocks = this.receivedMessages\n .at(-1)!\n .content.filter((block): block is TextBlock => block.type === 'text')\n .map((block) => block.text);\n if (textBlocks.length === 0) {\n throw new AnthropicError('stream ended without producing a content block with type=text');\n }\n return textBlocks.join(' ');\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message's text response, concatenated\n * together if there are more than one text blocks.\n * Rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalText(): Promise<string> {\n await this.done();\n return this.#getFinalText();\n }\n\n #handleError = (error: unknown) => {\n this.#errored = true;\n if (error instanceof Error && error.name === 'AbortError') {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n this.#aborted = true;\n return this._emit('abort', error);\n }\n if (error instanceof AnthropicError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const anthropicError: AnthropicError = new AnthropicError(error.message);\n // @ts-ignore\n anthropicError.cause = error;\n return this._emit('error', anthropicError);\n }\n return this._emit('error', new AnthropicError(String(error)));\n };\n\n protected _emit<Event extends keyof MessageStreamEvents>(\n event: Event,\n ...args: Parameters<MessageStreamEvents[Event]>\n ) {\n // make sure we don't emit any MessageStreamEvents after end\n if (this.#ended) return;\n\n if (event === 'end') {\n this.#ended = true;\n this.#resolveEndPromise();\n }\n\n const listeners: MessageStreamEventListeners<Event> | undefined = this.#listeners[event];\n if (listeners) {\n this.#listeners[event] = listeners.filter((l) => !l.once) as any;\n listeners.forEach(({ listener }: any) => listener(...args));\n }\n\n if (event === 'abort') {\n const error = args[0] as APIUserAbortError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n return;\n }\n\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n\n const error = args[0] as AnthropicError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.final...()\n // - etc.\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n }\n }\n\n protected _emitFinal() {\n const finalMessage = this.receivedMessages.at(-1);\n if (finalMessage) {\n this._emit('finalMessage', this.#getFinalMessage());\n }\n }\n\n #beginRequest() {\n if (this.ended) return;\n this.#currentMessageSnapshot = undefined;\n }\n #addStreamEvent(event: MessageStreamEvent) {\n if (this.ended) return;\n const messageSnapshot = this.#accumulateMessage(event);\n this._emit('streamEvent', event, messageSnapshot);\n\n switch (event.type) {\n case 'content_block_delta': {\n const content = messageSnapshot.content.at(-1)!;\n switch (event.delta.type) {\n case 'text_delta': {\n if (content.type === 'text') {\n this._emit('text', event.delta.text, content.text || '');\n }\n break;\n }\n case 'citations_delta': {\n if (content.type === 'text') {\n this._emit('citation', event.delta.citation, content.citations ?? []);\n }\n break;\n }\n case 'input_json_delta': {\n if (content.type === 'tool_use' && content.input) {\n this._emit('inputJson', event.delta.partial_json, content.input);\n }\n break;\n }\n case 'thinking_delta': {\n if (content.type === 'thinking') {\n this._emit('thinking', event.delta.thinking, content.thinking);\n }\n break;\n }\n case 'signature_delta': {\n if (content.type === 'thinking') {\n this._emit('signature', content.signature);\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n break;\n }\n case 'message_stop': {\n this._addMessageParam(messageSnapshot);\n this._addMessage(messageSnapshot, true);\n break;\n }\n case 'content_block_stop': {\n this._emit('contentBlock', messageSnapshot.content.at(-1)!);\n break;\n }\n case 'message_start': {\n this.#currentMessageSnapshot = messageSnapshot;\n break;\n }\n case 'content_block_start':\n case 'message_delta':\n break;\n }\n }\n #endRequest(): Message {\n if (this.ended) {\n throw new AnthropicError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = this.#currentMessageSnapshot;\n if (!snapshot) {\n throw new AnthropicError(`request ended without sending any chunks`);\n }\n this.#currentMessageSnapshot = undefined;\n return snapshot;\n }\n\n protected async _fromReadableStream(\n readableStream: ReadableStream,\n options?: Core.RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n this._connected(null);\n const stream = Stream.fromReadableStream<MessageStreamEvent>(readableStream, this.controller);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n }\n\n /**\n * Mutates this.#currentMessage with the current event. Handling the accumulation of multiple messages\n * will be needed to be handled by the caller, this method will throw if you try to accumulate for multiple\n * messages.\n */\n #accumulateMessage(event: MessageStreamEvent): Message {\n let snapshot = this.#currentMessageSnapshot;\n\n if (event.type === 'message_start') {\n if (snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving \"message_stop\"`);\n }\n return event.message;\n }\n\n if (!snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before \"message_start\"`);\n }\n\n switch (event.type) {\n case 'message_stop':\n return snapshot;\n case 'message_delta':\n snapshot.stop_reason = event.delta.stop_reason;\n snapshot.stop_sequence = event.delta.stop_sequence;\n snapshot.usage.output_tokens = event.usage.output_tokens;\n return snapshot;\n case 'content_block_start':\n snapshot.content.push(event.content_block);\n return snapshot;\n case 'content_block_delta': {\n const snapshotContent = snapshot.content.at(event.index);\n\n switch (event.delta.type) {\n case 'text_delta': {\n if (snapshotContent?.type === 'text') {\n snapshotContent.text += event.delta.text;\n }\n break;\n }\n case 'citations_delta': {\n if (snapshotContent?.type === 'text') {\n snapshotContent.citations ??= [];\n snapshotContent.citations.push(event.delta.citation);\n }\n break;\n }\n case 'input_json_delta': {\n if (snapshotContent?.type === 'tool_use') {\n // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = (snapshotContent as any)[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n\n Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n\n if (jsonBuf) {\n snapshotContent.input = partialParse(jsonBuf);\n }\n }\n break;\n }\n case 'thinking_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshotContent.thinking += event.delta.thinking;\n }\n break;\n }\n case 'signature_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshotContent.signature = event.delta.signature;\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n\n return snapshot;\n }\n case 'content_block_stop':\n return snapshot;\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<MessageStreamEvent> {\n const pushQueue: MessageStreamEvent[] = [];\n const readQueue: {\n resolve: (chunk: MessageStreamEvent | undefined) => void;\n reject: (error: unknown) => void;\n }[] = [];\n let done = false;\n\n this.on('streamEvent', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n } else {\n pushQueue.push(event);\n }\n });\n\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n return {\n next: async (): Promise<IteratorResult<MessageStreamEvent>> => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise<MessageStreamEvent | undefined>((resolve, reject) =>\n readQueue.push({ resolve, reject }),\n ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift()!;\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n\n toReadableStream(): ReadableStream {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\n\n// used to ensure exhaustive case matching without throwing a runtime error\nfunction checkNever(x: never) {}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../../resource.js\";\nimport { APIPromise } from \"../../core.js\";\nimport * as Core from \"../../core.js\";\nimport * as MessagesAPI from \"./messages.js\";\nimport * as BatchesAPI from \"./batches.js\";\nimport {\n BatchCreateParams,\n BatchListParams,\n Batches,\n DeletedMessageBatch,\n MessageBatch,\n MessageBatchCanceledResult,\n MessageBatchErroredResult,\n MessageBatchExpiredResult,\n MessageBatchIndividualResponse,\n MessageBatchRequestCounts,\n MessageBatchResult,\n MessageBatchSucceededResult,\n MessageBatchesPage,\n} from \"./batches.js\";\nimport { Stream } from \"../../streaming.js\";\nimport { MessageStream } from \"../../lib/MessageStream.js\";\n\nexport { MessageStream } from \"../../lib/MessageStream.js\";\n\nexport class Messages extends APIResource {\n batches: BatchesAPI.Batches = new BatchesAPI.Batches(this._client);\n\n /**\n * Send a structured list of input messages with text and/or image content, and the\n * model will generate the next message in the conversation.\n *\n * The Messages API can be used for either single queries or stateless multi-turn\n * conversations.\n *\n * Learn more about the Messages API in our [user guide](/en/docs/initial-setup)\n */\n create(body: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Message>;\n create(\n body: MessageCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent>>;\n create(\n body: MessageCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent> | Message>;\n create(\n body: MessageCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>> {\n if (body.model in DEPRECATED_MODELS) {\n console.warn(\n `The model '${body.model}' is deprecated and will reach end-of-life on ${\n DEPRECATED_MODELS[body.model]\n }\\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`,\n );\n }\n return this._client.post('/v1/messages', {\n body,\n timeout:\n (this._client as any)._options.timeout ??\n (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)),\n ...options,\n stream: body.stream ?? false,\n }) as APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>>;\n }\n\n /**\n * Create a Message stream\n */\n stream(body: MessageStreamParams, options?: Core.RequestOptions): MessageStream {\n return MessageStream.createMessage(this, body, options);\n }\n\n /**\n * Count the number of tokens in a Message.\n *\n * The Token Count API can be used to count the number of tokens in a Message,\n * including tools, images, and documents, without creating it.\n *\n * Learn more about token counting in our\n * [user guide](/en/docs/build-with-claude/token-counting)\n */\n countTokens(\n body: MessageCountTokensParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<MessageTokensCount> {\n return this._client.post('/v1/messages/count_tokens', { body, ...options });\n }\n}\n\nexport interface Base64ImageSource {\n data: string;\n\n media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';\n\n type: 'base64';\n}\n\nexport interface Base64PDFSource {\n data: string;\n\n media_type: 'application/pdf';\n\n type: 'base64';\n}\n\nexport interface CacheControlEphemeral {\n type: 'ephemeral';\n}\n\nexport interface CitationCharLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface CitationCharLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface CitationContentBlockLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface CitationContentBlockLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface CitationPageLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface CitationPageLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface CitationsConfigParam {\n enabled?: boolean;\n}\n\nexport interface CitationsDelta {\n citation: CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;\n\n type: 'citations_delta';\n}\n\nexport type ContentBlock = TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;\n\nexport type ContentBlockDeltaEvent = RawContentBlockDeltaEvent;\n\nexport type ContentBlockParam =\n | TextBlockParam\n | ImageBlockParam\n | ToolUseBlockParam\n | ToolResultBlockParam\n | DocumentBlockParam\n | ThinkingBlockParam\n | RedactedThinkingBlockParam;\n\nexport interface ContentBlockSource {\n content: string | Array<ContentBlockSourceContent>;\n\n type: 'content';\n}\n\nexport type ContentBlockSourceContent = TextBlockParam | ImageBlockParam;\n\nexport type ContentBlockStartEvent = RawContentBlockStartEvent;\n\nexport type ContentBlockStopEvent = RawContentBlockStopEvent;\n\nexport interface DocumentBlockParam {\n source: Base64PDFSource | PlainTextSource | ContentBlockSource | URLPDFSource;\n\n type: 'document';\n\n cache_control?: CacheControlEphemeral | null;\n\n citations?: CitationsConfigParam;\n\n context?: string | null;\n\n title?: string | null;\n}\n\nexport interface ImageBlockParam {\n source: Base64ImageSource | URLImageSource;\n\n type: 'image';\n\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport type InputJsonDelta = InputJSONDelta;\n\nexport interface InputJSONDelta {\n partial_json: string;\n\n type: 'input_json_delta';\n}\n\nexport interface Message {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * Content generated by the model.\n *\n * This is an array of content blocks, each of which has a `type` that determines\n * its shape.\n *\n * Example:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"Hi, I'm Claude.\" }]\n * ```\n *\n * If the request input `messages` ended with an `assistant` turn, then the\n * response `content` will continue directly from that last turn. You can use this\n * to constrain the model's output.\n *\n * For example, if the input `messages` were:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Then the response `content` might be:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"B)\" }]\n * ```\n */\n content: Array<ContentBlock>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: Model;\n\n /**\n * Conversational role of the generated message.\n *\n * This will always be `\"assistant\"`.\n */\n role: 'assistant';\n\n /**\n * The reason that we stopped.\n *\n * This may be one the following values:\n *\n * - `\"end_turn\"`: the model reached a natural stopping point\n * - `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n * - `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n * - `\"tool_use\"`: the model invoked one or more tools\n *\n * In non-streaming mode this value is always non-null. In streaming mode, it is\n * null in the `message_start` event and non-null otherwise.\n */\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;\n\n /**\n * Which custom stop sequence was generated, if any.\n *\n * This value will be a non-null string if one of your custom stop sequences was\n * generated.\n */\n stop_sequence: string | null;\n\n /**\n * Object type.\n *\n * For Messages, this is always `\"message\"`.\n */\n type: 'message';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: Usage;\n}\n\nexport type MessageCountTokensTool = Tool | ToolBash20250124 | ToolTextEditor20250124;\n\nexport type MessageDeltaEvent = RawMessageDeltaEvent;\n\nexport interface MessageDeltaUsage {\n /**\n * The cumulative number of output tokens which were used.\n */\n output_tokens: number;\n}\n\nexport interface MessageParam {\n content: string | Array<ContentBlockParam>;\n\n role: 'user' | 'assistant';\n}\n\nexport type MessageStartEvent = RawMessageStartEvent;\n\nexport type MessageStopEvent = RawMessageStopEvent;\n\nexport type MessageStreamEvent = RawMessageStreamEvent;\n\nexport interface MessageTokensCount {\n /**\n * The total number of tokens across the provided list of messages, system prompt,\n * and tools.\n */\n input_tokens: number;\n}\n\nexport interface Metadata {\n /**\n * An external identifier for the user who is associated with the request.\n *\n * This should be a uuid, hash value, or other opaque identifier. Anthropic may use\n * this id to help detect abuse. Do not include any identifying information such as\n * name, email address, or phone number.\n */\n user_id?: string | null;\n}\n\n/**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\nexport type Model =\n | 'claude-3-7-sonnet-latest'\n | 'claude-3-7-sonnet-20250219'\n | 'claude-3-5-haiku-latest'\n | 'claude-3-5-haiku-20241022'\n | 'claude-3-5-sonnet-latest'\n | 'claude-3-5-sonnet-20241022'\n | 'claude-3-5-sonnet-20240620'\n | 'claude-3-opus-latest'\n | 'claude-3-opus-20240229'\n | 'claude-3-sonnet-20240229'\n | 'claude-3-haiku-20240307'\n | 'claude-2.1'\n | 'claude-2.0'\n | (string & {});\n\nconst DEPRECATED_MODELS: {\n [K in Model]?: string;\n} = {\n 'claude-1.3': 'November 6th, 2024',\n 'claude-1.3-100k': 'November 6th, 2024',\n 'claude-instant-1.1': 'November 6th, 2024',\n 'claude-instant-1.1-100k': 'November 6th, 2024',\n 'claude-instant-1.2': 'November 6th, 2024',\n 'claude-3-sonnet-20240229': 'July 21st, 2025',\n 'claude-2.1': 'July 21st, 2025',\n 'claude-2.0': 'July 21st, 2025',\n};\n\nexport interface PlainTextSource {\n data: string;\n\n media_type: 'text/plain';\n\n type: 'text';\n}\n\nexport interface RawContentBlockDeltaEvent {\n delta: TextDelta | InputJSONDelta | CitationsDelta | ThinkingDelta | SignatureDelta;\n\n index: number;\n\n type: 'content_block_delta';\n}\n\nexport interface RawContentBlockStartEvent {\n content_block: TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;\n\n index: number;\n\n type: 'content_block_start';\n}\n\nexport interface RawContentBlockStopEvent {\n index: number;\n\n type: 'content_block_stop';\n}\n\nexport interface RawMessageDeltaEvent {\n delta: RawMessageDeltaEvent.Delta;\n\n type: 'message_delta';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: MessageDeltaUsage;\n}\n\nexport namespace RawMessageDeltaEvent {\n export interface Delta {\n stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;\n\n stop_sequence: string | null;\n }\n}\n\nexport interface RawMessageStartEvent {\n message: Message;\n\n type: 'message_start';\n}\n\nexport interface RawMessageStopEvent {\n type: 'message_stop';\n}\n\nexport type RawMessageStreamEvent =\n | RawMessageStartEvent\n | RawMessageDeltaEvent\n | RawMessageStopEvent\n | RawContentBlockStartEvent\n | RawContentBlockDeltaEvent\n | RawContentBlockStopEvent;\n\nexport interface RedactedThinkingBlock {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface RedactedThinkingBlockParam {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface SignatureDelta {\n signature: string;\n\n type: 'signature_delta';\n}\n\nexport interface TextBlock {\n /**\n * Citations supporting the text block.\n *\n * The type of citation returned will depend on the type of document being cited.\n * Citing a PDF results in `page_location`, plain text results in `char_location`,\n * and content document results in `content_block_location`.\n */\n citations: Array<TextCitation> | null;\n\n text: string;\n\n type: 'text';\n}\n\nexport interface TextBlockParam {\n text: string;\n\n type: 'text';\n\n cache_control?: CacheControlEphemeral | null;\n\n citations?: Array<TextCitationParam> | null;\n}\n\nexport type TextCitation = CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;\n\nexport type TextCitationParam =\n | CitationCharLocationParam\n | CitationPageLocationParam\n | CitationContentBlockLocationParam;\n\nexport interface TextDelta {\n text: string;\n\n type: 'text_delta';\n}\n\nexport interface ThinkingBlock {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface ThinkingBlockParam {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface ThinkingConfigDisabled {\n type: 'disabled';\n}\n\nexport interface ThinkingConfigEnabled {\n /**\n * Determines how many tokens Claude can use for its internal reasoning process.\n * Larger budgets can enable more thorough analysis for complex problems, improving\n * response quality.\n *\n * Must be \u22651024 and less than `max_tokens`.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n budget_tokens: number;\n\n type: 'enabled';\n}\n\n/**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\nexport type ThinkingConfigParam = ThinkingConfigEnabled | ThinkingConfigDisabled;\n\nexport interface ThinkingDelta {\n thinking: string;\n\n type: 'thinking_delta';\n}\n\nexport interface Tool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n input_schema: Tool.InputSchema;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: string;\n\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Description of what this tool does.\n *\n * Tool descriptions should be as detailed as possible. The more information that\n * the model has about what the tool is and how to use it, the better it will\n * perform. You can use natural language descriptions to reinforce important\n * aspects of the tool input JSON schema.\n */\n description?: string;\n}\n\nexport namespace Tool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n export interface InputSchema {\n type: 'object';\n\n properties?: unknown | null;\n [k: string]: unknown;\n }\n}\n\nexport interface ToolBash20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'bash';\n\n type: 'bash_20250124';\n\n cache_control?: CacheControlEphemeral | null;\n}\n\n/**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\nexport type ToolChoice = ToolChoiceAuto | ToolChoiceAny | ToolChoiceTool | ToolChoiceNone;\n\n/**\n * The model will use any available tools.\n */\nexport interface ToolChoiceAny {\n type: 'any';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will automatically decide whether to use tools.\n */\nexport interface ToolChoiceAuto {\n type: 'auto';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output at most one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will not be allowed to use tools.\n */\nexport interface ToolChoiceNone {\n type: 'none';\n}\n\n/**\n * The model will use the specified tool with `tool_choice.name`.\n */\nexport interface ToolChoiceTool {\n /**\n * The name of the tool to use.\n */\n name: string;\n\n type: 'tool';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\nexport interface ToolResultBlockParam {\n tool_use_id: string;\n\n type: 'tool_result';\n\n cache_control?: CacheControlEphemeral | null;\n\n content?: string | Array<TextBlockParam | ImageBlockParam>;\n\n is_error?: boolean;\n}\n\nexport interface ToolTextEditor20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in tool_use blocks.\n */\n name: 'str_replace_editor';\n\n type: 'text_editor_20250124';\n\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport type ToolUnion = Tool | ToolBash20250124 | ToolTextEditor20250124;\n\nexport interface ToolUseBlock {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n}\n\nexport interface ToolUseBlockParam {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport interface URLImageSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface URLPDFSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface Usage {\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number | null;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number | null;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n}\n\nexport type MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming;\n\nexport interface MessageCreateParamsBase {\n /**\n * The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n *\n * Different models have different maximum values for this parameter. See\n * [models](https://docs.anthropic.com/en/docs/models-overview) for details.\n */\n max_tokens: number;\n\n /**\n * Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * Starting with Claude 3 models, you can also send image content blocks:\n *\n * ```json\n * {\n * \"role\": \"user\",\n * \"content\": [\n * {\n * \"type\": \"image\",\n * \"source\": {\n * \"type\": \"base64\",\n * \"media_type\": \"image/jpeg\",\n * \"data\": \"/9j/4AAQSkZJRg...\"\n * }\n * },\n * { \"type\": \"text\", \"text\": \"What is in this image?\" }\n * ]\n * }\n * ```\n *\n * We currently support the `base64` source type for images, and the `image/jpeg`,\n * `image/png`, `image/gif`, and `image/webp` media types.\n *\n * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for\n * more input examples.\n *\n * Note that if you want to include a\n * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use\n * the top-level `system` parameter \u2014 there is no `\"system\"` role for input\n * messages in the Messages API.\n */\n messages: Array<MessageParam>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: Model;\n\n /**\n * An object describing metadata about the request.\n */\n metadata?: Metadata;\n\n /**\n * Custom text sequences that will cause the model to stop generating.\n *\n * Our models will normally stop when they have naturally completed their turn,\n * which will result in a response `stop_reason` of `\"end_turn\"`.\n *\n * If you want the model to stop generating when it encounters custom strings of\n * text, you can use the `stop_sequences` parameter. If the model encounters one of\n * the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"`\n * and the response `stop_sequence` value will contain the matched stop sequence.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream?: boolean;\n\n /**\n * System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).\n */\n system?: string | Array<TextBlockParam>;\n\n /**\n * Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\n */\n temperature?: number;\n\n /**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: ThinkingConfigParam;\n\n /**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: ToolChoice;\n\n /**\n * Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.\n */\n tools?: Array<ToolUnion>;\n\n /**\n * Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_p?: number;\n}\n\nexport namespace MessageCreateParams {\n /**\n * @deprecated use `Anthropic.Messages.ToolChoiceAuto` instead\n */\n export type Metadata = MessagesAPI.Metadata;\n\n /**\n * @deprecated use `Anthropic.Messages.ToolChoiceAuto` instead\n */\n export type ToolChoiceAuto = MessagesAPI.ToolChoiceAuto;\n\n /**\n * @deprecated use `Anthropic.Messages.ToolChoiceAny` instead\n */\n export type ToolChoiceAny = MessagesAPI.ToolChoiceAny;\n\n /**\n * @deprecated use `Anthropic.Messages.ToolChoiceTool` instead\n */\n export type ToolChoiceTool = MessagesAPI.ToolChoiceTool;\n\n export type MessageCreateParamsNonStreaming = MessagesAPI.MessageCreateParamsNonStreaming;\n export type MessageCreateParamsStreaming = MessagesAPI.MessageCreateParamsStreaming;\n}\n\nexport interface MessageCreateParamsNonStreaming extends MessageCreateParamsBase {\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream?: false;\n}\n\nexport interface MessageCreateParamsStreaming extends MessageCreateParamsBase {\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for\n * details.\n */\n stream: true;\n}\n\nexport type MessageStreamParams = MessageCreateParamsBase;\n\nexport interface MessageCountTokensParams {\n /**\n * Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * Starting with Claude 3 models, you can also send image content blocks:\n *\n * ```json\n * {\n * \"role\": \"user\",\n * \"content\": [\n * {\n * \"type\": \"image\",\n * \"source\": {\n * \"type\": \"base64\",\n * \"media_type\": \"image/jpeg\",\n * \"data\": \"/9j/4AAQSkZJRg...\"\n * }\n * },\n * { \"type\": \"text\", \"text\": \"What is in this image?\" }\n * ]\n * }\n * ```\n *\n * We currently support the `base64` source type for images, and the `image/jpeg`,\n * `image/png`, `image/gif`, and `image/webp` media types.\n *\n * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for\n * more input examples.\n *\n * Note that if you want to include a\n * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use\n * the top-level `system` parameter \u2014 there is no `\"system\"` role for input\n * messages in the Messages API.\n */\n messages: Array<MessageParam>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: Model;\n\n /**\n * System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts).\n */\n system?: string | Array<TextBlockParam>;\n\n /**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: ThinkingConfigParam;\n\n /**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: ToolChoice;\n\n /**\n * Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details.\n */\n tools?: Array<MessageCountTokensTool>;\n}\n\nMessages.Batches = Batches;\nMessages.MessageBatchesPage = MessageBatchesPage;\n\nexport declare namespace Messages {\n export {\n type Base64ImageSource as Base64ImageSource,\n type Base64PDFSource as Base64PDFSource,\n type CacheControlEphemeral as CacheControlEphemeral,\n type CitationCharLocation as CitationCharLocation,\n type CitationCharLocationParam as CitationCharLocationParam,\n type CitationContentBlockLocation as CitationContentBlockLocation,\n type CitationContentBlockLocationParam as CitationContentBlockLocationParam,\n type CitationPageLocation as CitationPageLocation,\n type CitationPageLocationParam as CitationPageLocationParam,\n type CitationsConfigParam as CitationsConfigParam,\n type CitationsDelta as CitationsDelta,\n type ContentBlock as ContentBlock,\n type ContentBlockDeltaEvent as ContentBlockDeltaEvent,\n type ContentBlockParam as ContentBlockParam,\n type ContentBlockSource as ContentBlockSource,\n type ContentBlockSourceContent as ContentBlockSourceContent,\n type ContentBlockStartEvent as ContentBlockStartEvent,\n type ContentBlockStopEvent as ContentBlockStopEvent,\n type DocumentBlockParam as DocumentBlockParam,\n type ImageBlockParam as ImageBlockParam,\n type InputJsonDelta as InputJsonDelta,\n type InputJSONDelta as InputJSONDelta,\n type Message as Message,\n type MessageCountTokensTool as MessageCountTokensTool,\n type MessageDeltaEvent as MessageDeltaEvent,\n type MessageDeltaUsage as MessageDeltaUsage,\n type MessageParam as MessageParam,\n type MessageStartEvent as MessageStartEvent,\n type MessageStopEvent as MessageStopEvent,\n type MessageStreamEvent as MessageStreamEvent,\n type MessageTokensCount as MessageTokensCount,\n type Metadata as Metadata,\n type Model as Model,\n type PlainTextSource as PlainTextSource,\n type RawContentBlockDeltaEvent as RawContentBlockDeltaEvent,\n type RawContentBlockStartEvent as RawContentBlockStartEvent,\n type RawContentBlockStopEvent as RawContentBlockStopEvent,\n type RawMessageDeltaEvent as RawMessageDeltaEvent,\n type RawMessageStartEvent as RawMessageStartEvent,\n type RawMessageStopEvent as RawMessageStopEvent,\n type RawMessageStreamEvent as RawMessageStreamEvent,\n type RedactedThinkingBlock as RedactedThinkingBlock,\n type RedactedThinkingBlockParam as RedactedThinkingBlockParam,\n type SignatureDelta as SignatureDelta,\n type TextBlock as TextBlock,\n type TextBlockParam as TextBlockParam,\n type TextCitation as TextCitation,\n type TextCitationParam as TextCitationParam,\n type TextDelta as TextDelta,\n type ThinkingBlock as ThinkingBlock,\n type ThinkingBlockParam as ThinkingBlockParam,\n type ThinkingConfigDisabled as ThinkingConfigDisabled,\n type ThinkingConfigEnabled as ThinkingConfigEnabled,\n type ThinkingConfigParam as ThinkingConfigParam,\n type ThinkingDelta as ThinkingDelta,\n type Tool as Tool,\n type ToolBash20250124 as ToolBash20250124,\n type ToolChoice as ToolChoice,\n type ToolChoiceAny as ToolChoiceAny,\n type ToolChoiceAuto as ToolChoiceAuto,\n type ToolChoiceNone as ToolChoiceNone,\n type ToolChoiceTool as ToolChoiceTool,\n type ToolResultBlockParam as ToolResultBlockParam,\n type ToolTextEditor20250124 as ToolTextEditor20250124,\n type ToolUnion as ToolUnion,\n type ToolUseBlock as ToolUseBlock,\n type ToolUseBlockParam as ToolUseBlockParam,\n type URLImageSource as URLImageSource,\n type URLPDFSource as URLPDFSource,\n type Usage as Usage,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageStreamParams as MessageStreamParams,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export {\n Batches as Batches,\n type DeletedMessageBatch as DeletedMessageBatch,\n type MessageBatch as MessageBatch,\n type MessageBatchCanceledResult as MessageBatchCanceledResult,\n type MessageBatchErroredResult as MessageBatchErroredResult,\n type MessageBatchExpiredResult as MessageBatchExpiredResult,\n type MessageBatchIndividualResponse as MessageBatchIndividualResponse,\n type MessageBatchRequestCounts as MessageBatchRequestCounts,\n type MessageBatchResult as MessageBatchResult,\n type MessageBatchSucceededResult as MessageBatchSucceededResult,\n MessageBatchesPage as MessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchListParams as BatchListParams,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from \"../resource.js\";\nimport { isRequestOptions } from \"../core.js\";\nimport * as Core from \"../core.js\";\nimport { Page, type PageParams } from \"../pagination.js\";\n\nexport class Models extends APIResource {\n /**\n * Get a specific model.\n *\n * The Models API response can be used to determine information about a specific\n * model or resolve a model alias to a model ID.\n */\n retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo> {\n return this._client.get(`/v1/models/${modelId}`, options);\n }\n\n /**\n * List available models.\n *\n * The Models API response can be used to determine which models are available for\n * use in the API. More recently released models are listed first.\n */\n list(query?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;\n list(options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;\n list(\n query: ModelListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<ModelInfosPage, ModelInfo> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/v1/models', ModelInfosPage, { query, ...options });\n }\n}\n\nexport class ModelInfosPage extends Page<ModelInfo> {}\n\nexport interface ModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the model was released.\n * May be set to an epoch value if the release date is unknown.\n */\n created_at: string;\n\n /**\n * A human-readable name for the model.\n */\n display_name: string;\n\n /**\n * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\n}\n\nexport interface ModelListParams extends PageParams {}\n\nModels.ModelInfosPage = ModelInfosPage;\n\nexport declare namespace Models {\n export {\n type ModelInfo as ModelInfo,\n ModelInfosPage as ModelInfosPage,\n type ModelListParams as ModelListParams,\n };\n}\n", "// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { type Agent } from \"./_shims/index.js\";\nimport * as Core from \"./core.js\";\nimport * as Errors from \"./error.js\";\nimport * as Pagination from \"./pagination.js\";\nimport { type PageParams, PageResponse } from \"./pagination.js\";\nimport * as Uploads from \"./uploads.js\";\nimport * as API from \"./resources/index.js\";\nimport {\n Completion,\n CompletionCreateParams,\n CompletionCreateParamsNonStreaming,\n CompletionCreateParamsStreaming,\n Completions,\n} from \"./resources/completions.js\";\nimport { ModelInfo, ModelInfosPage, ModelListParams, Models } from \"./resources/models.js\";\nimport {\n AnthropicBeta,\n Beta,\n BetaAPIError,\n BetaAuthenticationError,\n BetaBillingError,\n BetaError,\n BetaErrorResponse,\n BetaGatewayTimeoutError,\n BetaInvalidRequestError,\n BetaNotFoundError,\n BetaOverloadedError,\n BetaPermissionError,\n BetaRateLimitError,\n} from \"./resources/beta/beta.js\";\nimport {\n Base64ImageSource,\n Base64PDFSource,\n CacheControlEphemeral,\n CitationCharLocation,\n CitationCharLocationParam,\n CitationContentBlockLocation,\n CitationContentBlockLocationParam,\n CitationPageLocation,\n CitationPageLocationParam,\n CitationsConfigParam,\n CitationsDelta,\n ContentBlock,\n ContentBlockDeltaEvent,\n ContentBlockParam,\n ContentBlockSource,\n ContentBlockSourceContent,\n ContentBlockStartEvent,\n ContentBlockStopEvent,\n DocumentBlockParam,\n ImageBlockParam,\n InputJSONDelta,\n Message,\n MessageCountTokensParams,\n MessageCountTokensTool,\n MessageCreateParams,\n MessageCreateParamsNonStreaming,\n MessageCreateParamsStreaming,\n MessageDeltaEvent,\n MessageDeltaUsage,\n MessageParam,\n MessageStartEvent,\n MessageStopEvent,\n MessageStreamEvent,\n MessageStreamParams,\n MessageTokensCount,\n Messages,\n Metadata,\n Model,\n PlainTextSource,\n RawContentBlockDeltaEvent,\n RawContentBlockStartEvent,\n RawContentBlockStopEvent,\n RawMessageDeltaEvent,\n RawMessageStartEvent,\n RawMessageStopEvent,\n RawMessageStreamEvent,\n RedactedThinkingBlock,\n RedactedThinkingBlockParam,\n SignatureDelta,\n TextBlock,\n TextBlockParam,\n TextCitation,\n TextCitationParam,\n TextDelta,\n ThinkingBlock,\n ThinkingBlockParam,\n ThinkingConfigDisabled,\n ThinkingConfigEnabled,\n ThinkingConfigParam,\n ThinkingDelta,\n Tool,\n ToolBash20250124,\n ToolChoice,\n ToolChoiceAny,\n ToolChoiceAuto,\n ToolChoiceNone,\n ToolChoiceTool,\n ToolResultBlockParam,\n ToolTextEditor20250124,\n ToolUnion,\n ToolUseBlock,\n ToolUseBlockParam,\n URLImageSource,\n URLPDFSource,\n Usage,\n} from \"./resources/messages/messages.js\";\n\nexport interface ClientOptions {\n /**\n * Defaults to process.env['ANTHROPIC_API_KEY'].\n */\n apiKey?: string | null | undefined;\n\n /**\n * Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].\n */\n authToken?: string | null | undefined;\n\n /**\n * Override the default base URL for the API, e.g., \"https://api.example.com/v2/\"\n *\n * Defaults to process.env['ANTHROPIC_BASE_URL'].\n */\n baseURL?: string | null | undefined;\n\n /**\n * The maximum amount of time (in milliseconds) that the client should wait for a response\n * from the server before timing out a single request.\n *\n * Note that request timeouts are retried by default, so in a worst-case scenario you may wait\n * much longer than this timeout before the promise succeeds or fails.\n */\n timeout?: number | undefined;\n\n /**\n * An HTTP agent used to manage HTTP(S) connections.\n *\n * If not provided, an agent will be constructed by default in the Node.js environment,\n * otherwise no agent is used.\n */\n httpAgent?: Agent | undefined;\n\n /**\n * Specify a custom `fetch` function implementation.\n *\n * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is\n * defined globally.\n */\n fetch?: Core.Fetch | undefined;\n\n /**\n * The maximum number of times that the client will retry a request in case of a\n * temporary failure, like a network error or a 5XX error from the server.\n *\n * @default 2\n */\n maxRetries?: number | undefined;\n\n /**\n * Default headers to include with every request to the API.\n *\n * These can be removed in individual requests by explicitly setting the\n * header to `undefined` or `null` in request options.\n */\n defaultHeaders?: Core.Headers | undefined;\n\n /**\n * Default query parameters to include with every request to the API.\n *\n * These can be removed in individual requests by explicitly setting the\n * param to `undefined` in request options.\n */\n defaultQuery?: Core.DefaultQuery | undefined;\n\n /**\n * By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n * Only set this option to `true` if you understand the risks and have appropriate mitigations in place.\n */\n dangerouslyAllowBrowser?: boolean | undefined;\n}\n\n/**\n * API Client for interfacing with the Anthropic API.\n */\nexport class Anthropic extends Core.APIClient {\n apiKey: string | null;\n authToken: string | null;\n\n private _options: ClientOptions;\n\n /**\n * API Client for interfacing with the Anthropic API.\n *\n * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]\n * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]\n * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.\n * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @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.\n */\n constructor({\n baseURL = Core.readEnv('ANTHROPIC_BASE_URL'),\n apiKey = Core.readEnv('ANTHROPIC_API_KEY') ?? null,\n authToken = Core.readEnv('ANTHROPIC_AUTH_TOKEN') ?? null,\n ...opts\n }: ClientOptions = {}) {\n const options: ClientOptions = {\n apiKey,\n authToken,\n ...opts,\n baseURL: baseURL || `https://api.anthropic.com`,\n };\n\n if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {\n throw new Errors.AnthropicError(\n \"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\",\n );\n }\n\n super({\n baseURL: options.baseURL!,\n timeout: options.timeout ?? 600000 /* 10 minutes */,\n httpAgent: options.httpAgent,\n maxRetries: options.maxRetries,\n fetch: options.fetch,\n });\n\n this._options = options;\n\n this.apiKey = apiKey;\n this.authToken = authToken;\n }\n\n completions: API.Completions = new API.Completions(this);\n messages: API.Messages = new API.Messages(this);\n models: API.Models = new API.Models(this);\n beta: API.Beta = new API.Beta(this);\n\n protected override defaultQuery(): Core.DefaultQuery | undefined {\n return this._options.defaultQuery;\n }\n\n protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {\n return {\n ...super.defaultHeaders(opts),\n ...(this._options.dangerouslyAllowBrowser ?\n { 'anthropic-dangerous-direct-browser-access': 'true' }\n : undefined),\n 'anthropic-version': '2023-06-01',\n ...this._options.defaultHeaders,\n };\n }\n\n protected override validateHeaders(headers: Core.Headers, customHeaders: Core.Headers) {\n if (this.apiKey && headers['x-api-key']) {\n return;\n }\n if (customHeaders['x-api-key'] === null) {\n return;\n }\n\n if (this.authToken && headers['authorization']) {\n return;\n }\n if (customHeaders['authorization'] === null) {\n return;\n }\n\n throw new Error(\n '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',\n );\n }\n\n protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {\n const apiKeyAuth = this.apiKeyAuth(opts);\n const bearerAuth = this.bearerAuth(opts);\n\n if (apiKeyAuth != null && !Core.isEmptyObj(apiKeyAuth)) {\n return apiKeyAuth;\n }\n\n if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {\n return bearerAuth;\n }\n return {};\n }\n\n protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {\n if (this.apiKey == null) {\n return {};\n }\n return { 'X-Api-Key': this.apiKey };\n }\n\n protected bearerAuth(opts: Core.FinalRequestOptions): Core.Headers {\n if (this.authToken == null) {\n return {};\n }\n return { Authorization: `Bearer ${this.authToken}` };\n }\n\n static Anthropic = this;\n static HUMAN_PROMPT = '\\n\\nHuman:';\n static AI_PROMPT = '\\n\\nAssistant:';\n static DEFAULT_TIMEOUT = 600000; // 10 minutes\n\n static AnthropicError = Errors.AnthropicError;\n static APIError = Errors.APIError;\n static APIConnectionError = Errors.APIConnectionError;\n static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;\n static APIUserAbortError = Errors.APIUserAbortError;\n static NotFoundError = Errors.NotFoundError;\n static ConflictError = Errors.ConflictError;\n static RateLimitError = Errors.RateLimitError;\n static BadRequestError = Errors.BadRequestError;\n static AuthenticationError = Errors.AuthenticationError;\n static InternalServerError = Errors.InternalServerError;\n static PermissionDeniedError = Errors.PermissionDeniedError;\n static UnprocessableEntityError = Errors.UnprocessableEntityError;\n\n static toFile = Uploads.toFile;\n static fileFromPath = Uploads.fileFromPath;\n}\n\nAnthropic.Completions = Completions;\nAnthropic.Messages = Messages;\nAnthropic.Models = Models;\nAnthropic.ModelInfosPage = ModelInfosPage;\nAnthropic.Beta = Beta;\nexport declare namespace Anthropic {\n export type RequestOptions = Core.RequestOptions;\n\n export import Page = Pagination.Page;\n export { type PageParams as PageParams, type PageResponse as PageResponse };\n\n export {\n Completions as Completions,\n type Completion as Completion,\n type CompletionCreateParams as CompletionCreateParams,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n };\n\n export {\n Messages as Messages,\n type Base64ImageSource as Base64ImageSource,\n type Base64PDFSource as Base64PDFSource,\n type CacheControlEphemeral as CacheControlEphemeral,\n type CitationCharLocation as CitationCharLocation,\n type CitationCharLocationParam as CitationCharLocationParam,\n type CitationContentBlockLocation as CitationContentBlockLocation,\n type CitationContentBlockLocationParam as CitationContentBlockLocationParam,\n type CitationPageLocation as CitationPageLocation,\n type CitationPageLocationParam as CitationPageLocationParam,\n type CitationsConfigParam as CitationsConfigParam,\n type CitationsDelta as CitationsDelta,\n type ContentBlock as ContentBlock,\n type ContentBlockDeltaEvent as ContentBlockDeltaEvent,\n type ContentBlockParam as ContentBlockParam,\n type ContentBlockSource as ContentBlockSource,\n type ContentBlockSourceContent as ContentBlockSourceContent,\n type ContentBlockStartEvent as ContentBlockStartEvent,\n type ContentBlockStopEvent as ContentBlockStopEvent,\n type DocumentBlockParam as DocumentBlockParam,\n type ImageBlockParam as ImageBlockParam,\n type InputJSONDelta as InputJSONDelta,\n type Message as Message,\n type MessageCountTokensTool as MessageCountTokensTool,\n type MessageDeltaEvent as MessageDeltaEvent,\n type MessageDeltaUsage as MessageDeltaUsage,\n type MessageParam as MessageParam,\n type MessageStartEvent as MessageStartEvent,\n type MessageStopEvent as MessageStopEvent,\n type MessageStreamEvent as MessageStreamEvent,\n type MessageTokensCount as MessageTokensCount,\n type Metadata as Metadata,\n type Model as Model,\n type PlainTextSource as PlainTextSource,\n type RawContentBlockDeltaEvent as RawContentBlockDeltaEvent,\n type RawContentBlockStartEvent as RawContentBlockStartEvent,\n type RawContentBlockStopEvent as RawContentBlockStopEvent,\n type RawMessageDeltaEvent as RawMessageDeltaEvent,\n type RawMessageStartEvent as RawMessageStartEvent,\n type RawMessageStopEvent as RawMessageStopEvent,\n type RawMessageStreamEvent as RawMessageStreamEvent,\n type RedactedThinkingBlock as RedactedThinkingBlock,\n type RedactedThinkingBlockParam as RedactedThinkingBlockParam,\n type SignatureDelta as SignatureDelta,\n type TextBlock as TextBlock,\n type TextBlockParam as TextBlockParam,\n type TextCitation as TextCitation,\n type TextCitationParam as TextCitationParam,\n type TextDelta as TextDelta,\n type ThinkingBlock as ThinkingBlock,\n type ThinkingBlockParam as ThinkingBlockParam,\n type ThinkingConfigDisabled as ThinkingConfigDisabled,\n type ThinkingConfigEnabled as ThinkingConfigEnabled,\n type ThinkingConfigParam as ThinkingConfigParam,\n type ThinkingDelta as ThinkingDelta,\n type Tool as Tool,\n type ToolBash20250124 as ToolBash20250124,\n type ToolChoice as ToolChoice,\n type ToolChoiceAny as ToolChoiceAny,\n type ToolChoiceAuto as ToolChoiceAuto,\n type ToolChoiceNone as ToolChoiceNone,\n type ToolChoiceTool as ToolChoiceTool,\n type ToolResultBlockParam as ToolResultBlockParam,\n type ToolTextEditor20250124 as ToolTextEditor20250124,\n type ToolUnion as ToolUnion,\n type ToolUseBlock as ToolUseBlock,\n type ToolUseBlockParam as ToolUseBlockParam,\n type URLImageSource as URLImageSource,\n type URLPDFSource as URLPDFSource,\n type Usage as Usage,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageStreamParams as MessageStreamParams,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export {\n Models as Models,\n type ModelInfo as ModelInfo,\n ModelInfosPage as ModelInfosPage,\n type ModelListParams as ModelListParams,\n };\n\n export {\n Beta as Beta,\n type AnthropicBeta as AnthropicBeta,\n type BetaAPIError as BetaAPIError,\n type BetaAuthenticationError as BetaAuthenticationError,\n type BetaBillingError as BetaBillingError,\n type BetaError as BetaError,\n type BetaErrorResponse as BetaErrorResponse,\n type BetaGatewayTimeoutError as BetaGatewayTimeoutError,\n type BetaInvalidRequestError as BetaInvalidRequestError,\n type BetaNotFoundError as BetaNotFoundError,\n type BetaOverloadedError as BetaOverloadedError,\n type BetaPermissionError as BetaPermissionError,\n type BetaRateLimitError as BetaRateLimitError,\n };\n\n export type APIErrorObject = API.APIErrorObject;\n export type AuthenticationError = API.AuthenticationError;\n export type BillingError = API.BillingError;\n export type ErrorObject = API.ErrorObject;\n export type ErrorResponse = API.ErrorResponse;\n export type GatewayTimeoutError = API.GatewayTimeoutError;\n export type InvalidRequestError = API.InvalidRequestError;\n export type NotFoundError = API.NotFoundError;\n export type OverloadedError = API.OverloadedError;\n export type PermissionError = API.PermissionError;\n export type RateLimitError = API.RateLimitError;\n}\nexport const { HUMAN_PROMPT, AI_PROMPT } = Anthropic;\n\nexport { toFile, fileFromPath } from \"./uploads.js\";\nexport {\n AnthropicError,\n APIError,\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n NotFoundError,\n ConflictError,\n RateLimitError,\n BadRequestError,\n AuthenticationError,\n InternalServerError,\n PermissionDeniedError,\n UnprocessableEntityError,\n} from \"./error.js\";\n\nexport default Anthropic;\n", "import type Anthropic from '@anthropic-ai/sdk';\n\nexport const DEFAULT_ANTHROPIC_PARAMS = {\n // model: 'claude-3-5-sonnet-20241022',\n model: 'claude-3-7-sonnet-20250219',\n max_tokens: 8192,\n temperature: 0.1\n};\n\nexport const DEFAULT_ANTHROPIC_OPTIONS = {\n headers: {\n 'x-api-key': null, // Ensuring headers are omitted\n authorization: null\n }\n};\n\nasync function sendPrompt(\n anthropic: Anthropic,\n config: {\n proxyUrl: string;\n headers?: Record<string, string | null | undefined>;\n\n model?: string;\n maxTokens?: number;\n temperature?: number;\n },\n prompt: string,\n signal: AbortSignal\n): Promise<AsyncGenerator<string, void, unknown>> {\n const customOptions: Partial<typeof DEFAULT_ANTHROPIC_PARAMS> = {};\n if (config.model) customOptions.model = config.model;\n if (config.maxTokens) customOptions.max_tokens = config.maxTokens;\n if (config.temperature) customOptions.temperature = config.temperature;\n\n const msg = await anthropic.messages.create(\n {\n ...DEFAULT_ANTHROPIC_PARAMS,\n ...customOptions,\n stream: true,\n messages: [\n {\n role: 'user',\n content: [\n {\n type: 'text',\n text: prompt\n }\n ]\n }\n ]\n },\n {\n signal,\n ...DEFAULT_ANTHROPIC_OPTIONS,\n headers: {\n ...(DEFAULT_ANTHROPIC_OPTIONS.headers ?? {}),\n ...config.headers\n }\n }\n );\n\n // Return an async generator that yields only the text chunks\n async function* textStreamGenerator() {\n try {\n for await (const chunk of msg) {\n if (\n chunk.type === 'content_block_delta' &&\n chunk.delta.type === 'text_delta'\n ) {\n yield chunk.delta.text;\n }\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Stream error:', error);\n throw error; // Re-throw to allow consumer to handle\n }\n }\n\n return textStreamGenerator();\n}\n\nexport default sendPrompt;\n", "function improve(text: string): string {\n return `\nYou are an AI writing assistant tasked with improving a given text based on a specific type of improvement requested. Your goal is to enhance the text while maintaining its original meaning and intent.\n\nHere is the original text you will be working with:\n\n<original_text>\n${text}\n</original_text>\n\nPlease follow these steps to improve the text:\n\n1. Carefully read and analyze the original text.\n2. Consider the specific improvement type requested and how it applies to the given text.\n3. Make the necessary changes to improve the text according to the requested improvement type. This may include:\n - Rephrasing sentences\n - Adjusting vocabulary\n - Restructuring paragraphs\n - Adding or removing content as appropriate\n4. Ensure that the improved version maintains the original meaning and intent of the text.\n5. Return the improved text without any additional commentary or explanation.\n6. If there is nothing to improve, simply return the original text without any changes.\n7. If you cannot make any meaningful improvements, return the original text as is.\n\nOnce you have made the improvements, only return the improved text and nothing else.\n`;\n}\n\nexport default improve;\n", "function shorter(text: string): string {\n return `\nYou will be given a text to shorten. Your task is to reduce the length of the text by 30% to 50% while maintaining its original voice, perspective, and key information. This is not a summary - you should preserve the style and tone of the original text.\n\nHere is the original text:\n\n<original_text>\n${text}\n</original_text>\n\nTo complete this task, follow these steps:\n\n1. Carefully read and analyze the text, paying attention to its style, tone, and main points.\n\n2. Identify areas where the text can be condensed without losing essential information or altering the author's voice.\n\n3. Begin shortening the text by:\n - Removing redundant or repetitive information\n - Simplifying complex sentences\n - Eliminating unnecessary examples or elaborations\n - Combining related ideas into more concise statements\n\n4. As you shorten, continuously check that you are:\n - Maintaining the original voice and perspective\n - Keeping all crucial information\n - Preserving the flow and coherence of the text\n\n5. Aim to reduce the length by 30% to 50% of the original. If you find yourself shortening less than 30%, look for additional opportunities to condense. If you're reducing more than 50%, ensure you haven't cut too much important content.\n\n6. Once you've finished shortening, review the text to ensure it still reads smoothly and retains the essence of the original.\n\nProvide only the shortened version of the text in your response, without any additional comments, tags or explanations.\n`;\n}\n\nexport default shorter;\n", "function longer(text: string): string {\n return `\nYou are tasked with expanding a given text to make it longer. Here's how to proceed:\n\nFirst, you will be provided with the original text:\n\n<original_text>\n${text}\n</original_text>\n\nTo expand the text:\n\n1. Analyze the original text to understand its main ideas, tone, and style.\n2. Identify areas where you can add more detail, examples, or explanations.\n3. Expand on these areas by:\n - Providing more context or background information\n - Adding relevant examples or anecdotes\n - Elaborating on key points\n - Introducing related concepts or ideas\n - Explaining implications or consequences of the main ideas\n4. Ensure that the expanded text length is not exceeding the original text by more than 50%.\n5. Always expand the text, even if it is a single word. Explain the word with a few short sentences in that case. If the text is empty, make up a short sentence.\n\nGuidelines:\n\n- Maintain the original tone and style of the text.\n- Ensure all additions are relevant to the main topic.\n- Keep the flow of the text natural and coherent.\n- Do not contradict any information in the original text.\n\nOnly return the longer text and nothing else.\n\nMake sure to only return the expanded text and nothing else. Do not include any additional information or comments in your response about what you have done.\n\nDo not add the original text or the original_text tags to the response.\n`;\n}\n\nexport default longer;\n", "function fix(text: string): string {\n return `\nYou are tasked with fixing spelling and grammar errors in a given text. Your goal is to improve the text while maintaining its original meaning and style. Here is the text you need to correct:\n\n<original_text>\n${text}\n</original_text>\n\nPlease follow these steps to complete the task:\n\n1. Carefully read through the text and identify any spelling or grammatical errors.\n\n2. Correct all spelling mistakes, including typos and incorrectly spelled words.\n\n3. Fix grammatical errors, including:\n - Incorrect verb tenses\n - Subject-verb agreement issues\n - Improper use of articles (a, an, the)\n - Incorrect word usage\n - Run-on sentences or sentence fragments\n - Punctuation errors\n\n4. Ensure proper capitalization, especially at the beginning of sentences and for proper nouns.\n\n5. Maintain the original meaning and tone of the text. Do not add or remove information, or change the author's intended message.\n\n6. Make sure the corrected text flows naturally and is easy to read.\n\nAfter making the necessary corrections, please provide only the improved output and nothing else.\n\nRemember to preserve the original structure and formatting of the text as much as possible while making your corrections.\n`;\n}\n\nexport default fix;\n", "function generateTextForSpeech(text: string): string {\n return `\n Your task is to create a new text based on a given prompt. The text should be short enough that it can be read aloud in no more than 5 seconds.\n\nFollow these guidelines when generating the text:\n1. Keep the text concise and to the point.\n2. Use simple words and sentence structures.\n3. Aim for approximately 20-25 words.\n4. Ensure the text is coherent and meaningful.\n5. Stay relevant to the given prompt.\n\nHere is the prompt to base your text on:\n<prompt>\n${text}\n</prompt>\n\nGenerate a short text based on this prompt. Output only the generated text, without any additional explanation or commentary. Do not include any XML tags in your response.\n`;\n}\n\nexport default generateTextForSpeech;\n", "export const LANGUAGES = {\n en_US: 'English (US)',\n en_UK: 'English (UK)',\n es: 'Spanish',\n fr: 'French',\n de: 'German',\n pt: 'Portuguese',\n it: 'Italian',\n ru: 'Russian',\n zh: 'Mandarin Chinese',\n ja: 'Japanese'\n} as const;\n\nexport const LOCALES = Object.keys(LANGUAGES) as Locale[];\n\nexport type Locale = keyof typeof LANGUAGES;\n\nfunction translate(text: string, locale: Locale): string {\n const language = LANGUAGES[locale] || locale;\n\n return `\nYou are a translation AI. Your task is to translate the given text into the specified target language. Follow these steps:\n\n1. Here is the source text to be translated:\n<source_text>\n${text}\n</source_text>\n\n2. The target language for translation is:\n<target_language>\n${language}\n</target_language>\n\n3. Translate the source text into the target language. Ensure that you maintain the original meaning, tone, and style as closely as possible while adapting to the linguistic and cultural norms of the target language.\n\n4. Return only the translated text, without any additional comments, explanations, or metadata. Do not include the original text or any other information in your response.\n`;\n}\n\nexport default translate;\n", "function changeTone(text: string, type: string): string {\n const prompt = `\nYou will be given a piece of text and a desired tone. Your task is to rewrite the text to match the desired tone while preserving the original meaning and key information. Here's how to proceed:\n\nFirst, you will be provided with the original text:\n<original_text>\n${text}\n</original_text>\n\nThe desired tone for the rewritten text is:\n<desired_tone>\n${type}\n</desired_tone>\n\nTo change the tone of the text:\n1. Analyze the current tone and style of the original text.\n2. Identify the key information and main ideas in the original text.\n3. Consider the characteristics of the desired tone (e.g., formal, casual, humorous, professional, etc.).\n4. Rewrite the text, adapting the language, vocabulary, and sentence structure to match the desired tone while maintaining the original meaning and key information.\n5. Ensure that the rewritten text flows naturally and coherently.\n6. Only return the rewritten text without any additional commentary, tags or explanation.\n\nNow, rewrite the text to match the desired tone. Your response should contain only the rewritten text, without any additional explanations or comments. Do not use any tags in your response.\n`;\n\n return prompt;\n}\n\nexport default changeTone;\n", "function changeTextTo(text: string, customPrompt: string): string {\n return `\nYou will be given an original text and a custom prompt addition that specifies how to change the text. Your task is to modify the original text according to the prompt and return only the new, modified text.\n\nHere is the original text:\n<original_text>\n${text}\n</original_text>\n\nThe custom prompt addition is:\n<change_text_to>\n${customPrompt}\n</change_text_to>\n\nPlease modify the original text according to the \"Change Text to...\" prompt. Only return the new, modified text without any additional commentary or explanation. Your entire response should be the modified text itself, with no other content.\n`;\n}\n\nexport default changeTextTo;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport {\n Provider,\n QuickAction,\n type CommonProviderConfiguration\n} from '@imgly/plugin-ai-generation-web';\nimport Anthropic from '@anthropic-ai/sdk';\nimport sendPrompt from './sendPrompt';\nimport improve from './prompts/improve';\nimport shorter from './prompts/shorter';\nimport longer from './prompts/longer';\nimport fix from './prompts/fix';\nimport generateTextForSpeech from './prompts/generateTextForSpeech';\nimport translate, { LANGUAGES, LOCALES } from './prompts/translate';\nimport changeTone from './prompts/changeTone';\nimport changeTextTo from './prompts/changeTextTo';\n\ntype AnthropicInput = {\n prompt: string;\n temperature?: number;\n maxTokens?: number;\n\n blockId?: number;\n initialText?: string;\n};\n\ntype AnthropicOutput = {\n kind: 'text';\n text: string;\n};\n\nexport function AnthropicProvider(\n config: CommonProviderConfiguration<AnthropicInput, AnthropicOutput>\n): (context: {\n cesdk: CreativeEditorSDK;\n}) => Promise<Provider<'text', AnthropicInput, AnthropicOutput>> {\n return (context: { cesdk: CreativeEditorSDK }) => {\n context.cesdk.i18n.setTranslations({\n en: {\n ...Object.entries(LANGUAGES).reduce(\n (acc: Record<string, string>, [locale, langauge]) => {\n acc[`ly.img.ai.inference.translate.type.${locale}`] = langauge;\n return acc;\n },\n {}\n )\n }\n });\n\n let anthropic: Anthropic | null = null;\n const provider: Provider<'text', AnthropicInput, AnthropicOutput> = {\n kind: 'text',\n id: 'anthropic',\n initialize: async () => {\n anthropic = new Anthropic({\n dangerouslyAllowBrowser: true,\n baseURL: config.proxyUrl,\n // Will be injected by the proxy\n apiKey: null,\n authToken: null\n });\n },\n input: {\n quickActions: {\n actions: [\n ImproveQuickAction(),\n FixQuickAction(),\n ShorterQuickAction(),\n LongerQuickAction(),\n SpeechQuickAction(),\n ChangeToneQuickAction(),\n TranslateQuickAction(),\n ChangeTextToQuickAction()\n ]\n }\n },\n output: {\n middleware: config.middleware,\n generate: async (\n { prompt, blockId },\n { engine, abortSignal }\n ): Promise<AsyncGenerator<AnthropicOutput, AnthropicOutput>> => {\n if (anthropic == null)\n throw new Error('Anthropic SDK is not initialized');\n\n if (\n blockId != null &&\n engine.block.getType(blockId) !== '//ly.img.ubq/text'\n ) {\n throw new Error(\n 'If a block is provided to this generation, it most be a text block'\n );\n }\n\n if (config.debug)\n // eslint-disable-next-line no-console\n console.log(\n 'Sending prompt to Anthropic:',\n JSON.stringify(prompt, undefined, 2)\n );\n\n const stream = await sendPrompt(\n anthropic,\n {\n proxyUrl: config.proxyUrl,\n headers: config.headers\n },\n prompt,\n abortSignal\n );\n\n // Create a new AsyncGenerator that yields AnthropicOutput objects\n async function* outputGenerator(): AsyncGenerator<\n AnthropicOutput,\n AnthropicOutput\n > {\n let inferredText: string = '';\n for await (const chunk of stream) {\n if (abortSignal.aborted) {\n break;\n }\n inferredText += chunk;\n yield {\n kind: 'text',\n text: inferredText\n };\n }\n // Return the final result\n return {\n kind: 'text',\n text: inferredText\n };\n }\n\n return outputGenerator();\n }\n }\n };\n\n return Promise.resolve(provider);\n };\n}\n\ntype Parameter = {\n id: string;\n label: string;\n icon?: string;\n};\n\n// Define a type that can handle different prompt function signatures\ntype PromptFunction =\n | ((text: string) => string)\n | ((text: string, param: string) => string)\n | ((text: string, param: any) => string);\n\ntype QuickActionOptions = {\n id: string;\n label: string;\n icon: string;\n promptFn: PromptFunction;\n parameters?: Parameter[];\n // Optional custom renderExpanded function for complex quick actions\n renderExpanded?: QuickAction<\n AnthropicInput,\n AnthropicOutput\n >['renderExpanded'];\n};\n\n/**\n * Creates a Quick Action for text operations\n * Supports both simple actions and ones with parameter selection via popover menus\n */\nfunction createTextQuickAction(\n options: QuickActionOptions\n): QuickAction<AnthropicInput, AnthropicOutput> {\n const { id, label, icon, promptFn, parameters, renderExpanded } = options;\n\n // Common enable function for all quick actions\n const enableFn = ({ engine }: { engine: any }) => {\n const blockIds = engine.block.findAllSelected();\n if (blockIds == null || blockIds.length !== 1) return false;\n\n const [blockId] = blockIds;\n return engine.block.getType(blockId) === '//ly.img.ubq/text';\n };\n\n // Base configuration shared by all types of quick actions\n type BaseQuickAction = Pick<\n QuickAction<AnthropicInput, AnthropicOutput>,\n 'id' | 'version' | 'confirmation' | 'enable'\n >;\n\n const baseConfig: BaseQuickAction = {\n id,\n version: '1',\n confirmation: true,\n enable: enableFn\n };\n\n // If a custom renderExpanded function is provided, create an expandable quick action\n if (renderExpanded) {\n return {\n ...baseConfig,\n render: ({ builder }, { toggleExpand }) => {\n builder.Button(`${id}.button`, {\n label,\n icon,\n labelAlignment: 'left',\n variant: 'plain',\n onClick: toggleExpand\n });\n },\n renderExpanded\n };\n }\n\n // For simple actions without parameters\n if (!parameters || parameters.length === 0) {\n return {\n ...baseConfig,\n render: ({ builder, engine }, { generate, closeMenu }) => {\n builder.Button(id, {\n label,\n icon,\n labelAlignment: 'left',\n variant: 'plain',\n onClick: () => {\n closeMenu();\n const [blockId] = engine.block.findAllSelected();\n const initialText = engine.block.getString(blockId, 'text/text');\n\n // Type assertion to handle the simpler function signature\n const simpleFn = promptFn as (text: string) => string;\n generate({\n prompt: simpleFn(initialText),\n blockId,\n initialText\n });\n }\n });\n }\n };\n }\n\n // For actions with parameters displayed in a popover menu\n return {\n ...baseConfig,\n render: ({ builder, engine, experimental }, { generate, closeMenu }) => {\n experimental.builder.Popover(`${id}.popover`, {\n label,\n icon,\n labelAlignment: 'left',\n variant: 'plain',\n trailingIcon: '@imgly/ChevronRight',\n placement: 'right',\n children: () => {\n builder.Section(`${id}.popover.section`, {\n children: () => {\n experimental.builder.Menu(`${id}.popover.menu`, {\n children: () => {\n parameters.forEach((param) => {\n builder.Button(`${id}.popover.menu.${param.id}`, {\n label: param.label,\n icon: param.icon,\n labelAlignment: 'left',\n variant: 'plain',\n onClick: () => {\n closeMenu();\n const [blockId] = engine.block.findAllSelected();\n const initialText = engine.block.getString(\n blockId,\n 'text/text'\n );\n\n // Type assertion to handle the parameterized function signature\n const paramFn = promptFn as (\n text: string,\n param: any\n ) => string;\n generate({\n prompt: paramFn(initialText, param.id),\n blockId,\n initialText\n });\n }\n });\n });\n }\n });\n }\n });\n }\n });\n }\n };\n}\n\nfunction ImproveQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'improve',\n label: 'Improve',\n icon: '@imgly/MagicWand',\n promptFn: improve\n });\n}\n\nfunction ShorterQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'shorter',\n label: 'Make Shorter',\n icon: '@imgly/TextShorter',\n promptFn: shorter\n });\n}\n\nfunction LongerQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'longer',\n label: 'Make Longer',\n icon: '@imgly/TextLonger',\n promptFn: longer\n });\n}\n\nfunction FixQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'fix',\n label: 'Fix Spelling & Grammar',\n icon: '@imgly/CheckmarkAll',\n promptFn: fix\n });\n}\n\nfunction SpeechQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'speech',\n label: 'Generate Speech Text',\n icon: '@imgly/Microphone',\n promptFn: generateTextForSpeech\n });\n}\n\nconst TONE_TYPES = [\n 'professional',\n 'casual',\n 'friendly',\n 'serious',\n 'humorous',\n 'optimistic'\n];\n\nfunction ChangeToneQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'changeTone',\n label: 'Change Tone',\n icon: '@imgly/Microphone',\n promptFn: changeTone,\n parameters: TONE_TYPES.map((tone) => ({\n id: tone,\n label: tone.charAt(0).toUpperCase() + tone.slice(1)\n }))\n });\n}\n\nfunction TranslateQuickAction(): QuickAction<AnthropicInput, AnthropicOutput> {\n return createTextQuickAction({\n id: 'translate',\n label: 'Translate',\n icon: '@imgly/Language',\n promptFn: translate,\n parameters: LOCALES.map((locale) => ({\n id: locale,\n label: LANGUAGES[locale]\n }))\n });\n}\n\nfunction ChangeTextToQuickAction(): QuickAction<\n AnthropicInput,\n AnthropicOutput\n> {\n return createTextQuickAction({\n id: 'changeTextTo',\n label: 'Change Text to...',\n icon: '@imgly/Rename',\n promptFn: changeTextTo,\n renderExpanded: (\n { builder, engine, experimental, state },\n { generate, toggleExpand }\n ) => {\n const customPromptState = state('changeTextTo.prompt', '');\n\n builder.TextArea('changeTextTo.textarea', {\n inputLabel: 'Change text to...',\n ...customPromptState\n });\n\n builder.Separator('changeTextTo.separator');\n\n experimental.builder.ButtonRow('changeTextTo.footer', {\n justifyContent: 'space-between',\n children: () => {\n builder.Button('changeTextTo.footer.cancel', {\n label: 'Back',\n icon: '@imgly/ChevronLeft',\n onClick: toggleExpand\n });\n\n builder.Button('changeTextTo.footer.apply', {\n label: 'Rewrite',\n icon: '@imgly/MagicWand',\n color: 'accent',\n onClick: () => {\n const customPrompt = customPromptState.value;\n if (!customPrompt) return;\n\n const [blockId] = engine.block.findAllSelected();\n const initialText = engine.block.getString(blockId, 'text/text');\n\n generate({\n prompt: changeTextTo(initialText, customPrompt),\n blockId,\n initialText\n });\n\n toggleExpand();\n }\n });\n }\n });\n }\n });\n}\n", "import { AnthropicProvider } from './AnthropicProvider';\n\nconst Anthropic = {\n AnthropicProvider\n};\n\nexport default Anthropic;\n"],
|
|
5
|
+
"mappings": "AAAO,IAAMA,EAAU,SC0BhB,IAAIC,GAAO,GACPC,EACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GAEL,SAAUC,GAASC,EAAcC,EAA6B,CAAE,KAAM,EAAK,EAAE,CACjF,GAAIhB,GACF,MAAM,IAAI,MACR,8CAA8Ce,EAAM,IAAI,2DAA2D,EAGvH,GAAId,EACF,MAAM,IAAI,MACR,2CAA2Cc,EAAM,IAAI,+CAA+Cd,CAAI,KAAK,EAGjHD,GAAOgB,EAAQ,KACff,EAAOc,EAAM,KACbb,GAAQa,EAAM,MACdZ,GAAUY,EAAM,QAChBX,GAAWW,EAAM,SACjBV,GAAUU,EAAM,QAChBT,GAAWS,EAAM,SACjBR,GAAOQ,EAAM,KACbP,GAAOO,EAAM,KACbN,GAAiBM,EAAM,eACvBL,GAA6BK,EAAM,2BACnCJ,GAAkBI,EAAM,gBACxBH,GAAeG,EAAM,aACrBF,GAAiBE,EAAM,cACzB,CC/DM,IAAOE,GAAP,KAAoB,CACxB,YAAmBC,EAAS,CAAT,KAAA,KAAAA,CAAY,CAC/B,IAAK,OAAO,WAAW,GAAC,CACtB,MAAO,eACT,GCAI,SAAUC,GAAW,CAAE,iBAAAC,CAAgB,EAAqC,CAAA,EAAE,CAClF,IAAMC,EACJD,EACE,gCACA,sNAKAE,EAAQC,EAAUC,EAAWC,EACjC,GAAI,CAEFH,EAAS,MAETC,EAAW,QAEXC,EAAY,SAEZC,EAAW,cACJC,EAAO,CACd,MAAM,IAAI,MACR,iEACGA,EAAc,OACjB,KAAKL,CAAc,EAAE,EAIzB,MAAO,CACL,KAAM,MACN,MAAOC,EACP,QAASC,E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ReadableStream", "getMultipartRequestOptions", "getDefaultAgent", "fileFromPath", "isFsReadStream", "setShims", "shims", "options", "MultipartBody", "body", "getRuntime", "manuallyImported", "recommendation", "_fetch", "_Request", "_Response", "_Headers", "error", "form", "opts", "MultipartBody", "url", "value", "kind", "setShims", "getRuntime", "AnthropicError", "APIError", "_APIError", "status", "error", "message", "headers", "msg", "errorResponse", "APIConnectionError", "castToError", "BadRequestError", "AuthenticationError", "PermissionDeniedError", "NotFoundError", "ConflictError", "UnprocessableEntityError", "RateLimitError", "InternalServerError", "APIUserAbortError", "cause", "APIConnectionTimeoutError", "LineDecoder", "_LineDecoder_carriageReturnIndex", "__classPrivateFieldSet", "chunk", "binaryChunk", "newData", "lines", "patternIndex", "findNewlineIndex", "__classPrivateFieldGet", "endIndex", "line", "bytes", "AnthropicError", "buffer", "startIndex", "i", "findDoubleNewlineIndex", "ReadableStreamToAsyncIterable", "stream", "reader", "result", "e", "cancelPromise", "Stream", "_Stream", "iterator", "controller", "response", "consumed", "done", "sse", "_iterSSEMessages", "e", "APIError", "createResponseHeaders", "readableStream", "iterLines", "lineDecoder", "LineDecoder", "iter", "ReadableStreamToAsyncIterable", "chunk", "line", "left", "right", "teeIterator", "queue", "result", "self", "encoder", "ReadableStream", "ctrl", "value", "bytes", "err", "AnthropicError", "sseDecoder", "SSEDecoder", "sseChunk", "iterSSEChunks", "data", "binaryChunk", "newData", "patternIndex", "findDoubleNewlineIndex", "fieldname", "_", "partition", "str", "delimiter", "index", "isResponseLike", "value", "isFileLike", "isBlobLike", "toFile", "value", "name", "options", "isFileLike", "isResponseLike", "blob", "data", "isBlobLike", "File", "bits", "getBytes", "getName", "type", "parts", "isAsyncIterableIterator", "chunk", "propsForError", "p", "getStringFromMaybeBuffer", "x", "isMultipartBody", "body", "defaultParseResponse", "props", "response", "debug", "Stream", "contentType", "json", "_addRequestID", "text", "value", "APIPromise", "_APIPromise", "responsePromise", "parseResponse", "resolve", "transform", "p", "data", "onfulfilled", "onrejected", "onfinally", "APIClient", "baseURL", "maxRetries", "timeout", "httpAgent", "overriddenFetch", "validatePositiveInteger", "fetch", "opts", "getPlatformHeaders", "headers", "customHeaders", "uuid4", "path", "method", "body", "isBlobLike", "Page", "options", "retryCount", "query", "isMultipartBody", "contentLength", "url", "getDefaultAgent", "minAgentTimeout", "reqHeaders", "defaultHeaders", "applyHeadersMut", "kind", "getHeader", "maxTokens", "AnthropicError", "request", "header", "status", "error", "message", "APIError", "remainingRetries", "optionsInput", "retriesRemaining", "req", "APIUserAbortError", "controller", "castToError", "APIConnectionTimeoutError", "APIConnectionError", "responseHeaders", "createResponseHeaders", "retryMessage", "errText", "e", "errJSON", "safeJSON", "errMessage", "PagePromise", "isAbsoluteURL", "defaultQuery", "isEmptyObj", "_", "key", "init", "ms", "signal", "fetchOptions", "socketKeepAliveInterval", "keepAliveTimeout", "socket", "shouldRetryHeader", "timeoutMillis", "retryAfterMillisHeader", "timeoutMs", "retryAfterHeader", "timeoutSeconds", "sleep", "numRetries", "sleepSeconds", "jitter", "VERSION", "AbstractPage", "client", "_AbstractPage_client", "__classPrivateFieldSet", "nextInfo", "nextOptions", "params", "__classPrivateFieldGet", "page", "item", "target", "name", "requestOptionsKeys", "isRequestOptions", "obj", "k", "hasOwn", "getPlatformProperties", "normalizePlatform", "normalizeArch", "browserInfo", "getBrowserInfo", "browserPatterns", "pattern", "match", "major", "minor", "patch", "arch", "platform", "_platformHeaders", "startsWithSchemeRegexp", "n", "err", "readEnv", "env", "isEmptyObj", "obj", "_k", "hasOwn", "key", "applyHeadersMut", "targetHeaders", "newHeaders", "k", "lowerKey", "val", "debug", "action", "args", "uuid4", "c", "r", "isRunningInBrowser", "isHeadersProtocol", "headers", "getHeader", "headers", "header", "lowerCasedHeader", "isHeadersProtocol", "intercapsHeader", "_m", "g1", "g2", "key", "value", "Page", "AbstractPage", "client", "response", "body", "options", "info", "params", "firstId", "cursor", "APIResource", "client", "Models", "APIResource", "modelId", "options", "query", "isRequestOptions", "BetaModelInfosPage", "Page", "JSONLDecoder", "_JSONLDecoder", "iterator", "controller", "lineDecoder", "LineDecoder", "chunk", "line", "response", "AnthropicError", "ReadableStreamToAsyncIterable", "Batches", "APIResource", "params", "options", "betas", "body", "messageBatchId", "isRequestOptions", "query", "BetaMessageBatchesPage", "batch", "AnthropicError", "_", "props", "JSONLDecoder", "Page", "tokenize", "input", "current", "tokens", "char", "value", "danglingQuote", "NUMBERS", "LETTERS", "strip", "lastToken", "lastCharacterOfLastToken", "tokenBeforeTheLastToken", "unstrip", "tail", "token", "item", "generate", "output", "partialParse", "JSON_BUF_PROPERTY", "BetaMessageStream", "_BetaMessageStream", "_BetaMessageStream_currentMessageSnapshot", "_BetaMessageStream_connectedPromise", "_BetaMessageStream_resolveConnectedPromise", "_BetaMessageStream_rejectConnectedPromise", "_BetaMessageStream_endPromise", "_BetaMessageStream_resolveEndPromise", "_BetaMessageStream_rejectEndPromise", "_BetaMessageStream_listeners", "_BetaMessageStream_ended", "_BetaMessageStream_errored", "_BetaMessageStream_aborted", "_BetaMessageStream_catchingPromiseCreated", "_BetaMessageStream_response", "_BetaMessageStream_request_id", "_BetaMessageStream_handleError", "error", "__classPrivateFieldSet", "APIUserAbortError", "AnthropicError", "anthropicError", "resolve", "reject", "__classPrivateFieldGet", "response", "stream", "runner", "messages", "params", "options", "message", "executor", "emit", "signal", "_BetaMessageStream_instances", "_BetaMessageStream_beginRequest", "event", "_BetaMessageStream_addStreamEvent", "_BetaMessageStream_endRequest", "listener", "listeners", "index", "l", "_BetaMessageStream_getFinalMessage", "_BetaMessageStream_getFinalText", "args", "readableStream", "Stream", "textBlocks", "block", "messageSnapshot", "_BetaMessageStream_accumulateMessage", "content", "snapshot", "snapshotContent", "jsonBuf", "partialParse", "pushQueue", "readQueue", "done", "reader", "err", "chunk", "DEPRECATED_MODELS", "Messages", "APIResource", "Batches", "params", "options", "betas", "body", "BetaMessageStream", "BetaMessageBatchesPage", "Beta", "APIResource", "Models", "Messages", "BetaModelInfosPage", "Completions", "APIResource", "body", "options", "Batches", "APIResource", "body", "options", "messageBatchId", "query", "isRequestOptions", "MessageBatchesPage", "batch", "AnthropicError", "_", "props", "JSONLDecoder", "Page", "JSON_BUF_PROPERTY", "MessageStream", "_MessageStream", "_MessageStream_currentMessageSnapshot", "_MessageStream_connectedPromise", "_MessageStream_resolveConnectedPromise", "_MessageStream_rejectConnectedPromise", "_MessageStream_endPromise", "_MessageStream_resolveEndPromise", "_MessageStream_rejectEndPromise", "_MessageStream_listeners", "_MessageStream_ended", "_MessageStream_errored", "_MessageStream_aborted", "_MessageStream_catchingPromiseCreated", "_MessageStream_response", "_MessageStream_request_id", "_MessageStream_handleError", "error", "__classPrivateFieldSet", "APIUserAbortError", "AnthropicError", "anthropicError", "resolve", "reject", "__classPrivateFieldGet", "response", "stream", "runner", "messages", "params", "options", "message", "executor", "emit", "signal", "_MessageStream_instances", "_MessageStream_beginRequest", "event", "_MessageStream_addStreamEvent", "_MessageStream_endRequest", "listener", "listeners", "index", "l", "_MessageStream_getFinalMessage", "_MessageStream_getFinalText", "args", "readableStream", "Stream", "textBlocks", "block", "messageSnapshot", "_MessageStream_accumulateMessage", "content", "snapshot", "snapshotContent", "jsonBuf", "partialParse", "pushQueue", "readQueue", "done", "reader", "err", "chunk", "Messages", "APIResource", "Batches", "body", "options", "DEPRECATED_MODELS", "MessageStream", "MessageBatchesPage", "Models", "APIResource", "modelId", "options", "query", "isRequestOptions", "ModelInfosPage", "Page", "Anthropic", "APIClient", "baseURL", "readEnv", "apiKey", "authToken", "opts", "options", "isRunningInBrowser", "AnthropicError", "Completions", "Messages", "Models", "Beta", "headers", "customHeaders", "apiKeyAuth", "bearerAuth", "isEmptyObj", "_a", "APIError", "APIConnectionError", "APIConnectionTimeoutError", "APIUserAbortError", "NotFoundError", "ConflictError", "RateLimitError", "BadRequestError", "AuthenticationError", "InternalServerError", "PermissionDeniedError", "UnprocessableEntityError", "toFile", "fileFromPath", "ModelInfosPage", "HUMAN_PROMPT", "AI_PROMPT", "sdk_default", "DEFAULT_ANTHROPIC_PARAMS", "DEFAULT_ANTHROPIC_OPTIONS", "sendPrompt", "anthropic", "config", "prompt", "signal", "customOptions", "msg", "textStreamGenerator", "chunk", "error", "sendPrompt_default", "improve", "text", "improve_default", "shorter", "text", "shorter_default", "longer", "text", "longer_default", "fix", "text", "fix_default", "generateTextForSpeech", "text", "generateTextForSpeech_default", "LANGUAGES", "LOCALES", "translate", "text", "locale", "language", "translate_default", "changeTone", "text", "type", "changeTone_default", "changeTextTo", "text", "customPrompt", "changeTextTo_default", "AnthropicProvider", "config", "context", "LANGUAGES", "acc", "locale", "langauge", "anthropic", "provider", "sdk_default", "ImproveQuickAction", "FixQuickAction", "ShorterQuickAction", "LongerQuickAction", "SpeechQuickAction", "ChangeToneQuickAction", "TranslateQuickAction", "ChangeTextToQuickAction", "prompt", "blockId", "engine", "abortSignal", "stream", "sendPrompt_default", "outputGenerator", "inferredText", "chunk", "createTextQuickAction", "options", "id", "label", "icon", "promptFn", "parameters", "renderExpanded", "baseConfig", "blockIds", "builder", "toggleExpand", "generate", "closeMenu", "initialText", "experimental", "param", "improve_default", "shorter_default", "longer_default", "fix_default", "generateTextForSpeech_default", "TONE_TYPES", "changeTone_default", "tone", "translate_default", "LOCALES", "changeTextTo_default", "state", "customPromptState", "customPrompt", "Anthropic", "AnthropicProvider", "anthropic_default"]
|
|
7
7
|
}
|