feat: Complete zCode CLI X with Telegram bot integration

- Add full Telegram bot functionality with Z.AI API integration
- Implement 4 tools: Bash, FileEdit, WebSearch, Git
- Add 3 agents: Code Reviewer, Architect, DevOps Engineer
- Add 6 skills for common coding tasks
- Add systemd service file for 24/7 operation
- Add nginx configuration for HTTPS webhook
- Add comprehensive documentation
- Implement WebSocket server for real-time updates
- Add logging system with Winston
- Add environment validation

🤖 zCode CLI X - Agentic coder with Z.AI + Telegram integration
This commit is contained in:
admin
2026-05-05 09:01:26 +00:00
Unverified
parent 4a7035dd92
commit 875c7f9b91
24688 changed files with 3224957 additions and 221 deletions

View File

@@ -0,0 +1,646 @@
import { APIResource } from "../../../core/resource.mjs";
import * as BetaAPI from "../beta.mjs";
import { APIPromise } from "../../../core/api-promise.mjs";
import * as BetaMessagesAPI from "./messages.mjs";
import { Page, type PageParams, PagePromise } from "../../../core/pagination.mjs";
import { RequestOptions } from "../../../internal/request-options.mjs";
import { JSONLDecoder } from "../../../internal/decoders/jsonl.mjs";
import * as MessagesApi from "../../messages/messages.mjs";
export declare class Batches extends APIResource {
/**
* Send a batch of Message creation requests.
*
* The Message Batches API can be used to process multiple Messages API requests at
* once. Once a Message Batch is created, it begins processing immediately. Batches
* can take up to 24 hours to complete.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.create({
* requests: [
* {
* custom_id: 'my-custom-id-1',
* params: {
* max_tokens: 1024,
* messages: [
* { content: 'Hello, world', role: 'user' },
* ],
* model: 'claude-opus-4-6',
* },
* },
* ],
* });
* ```
*/
create(params: BatchCreateParams, options?: RequestOptions): APIPromise<BetaMessageBatch>;
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.retrieve(
* 'message_batch_id',
* );
* ```
*/
retrieve(messageBatchID: string, params?: BatchRetrieveParams | null | undefined, options?: RequestOptions): APIPromise<BetaMessageBatch>;
/**
* List all Message Batches within a Workspace. Most recently created batches are
* returned first.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const betaMessageBatch of client.beta.messages.batches.list()) {
* // ...
* }
* ```
*/
list(params?: BatchListParams | null | undefined, options?: RequestOptions): PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;
/**
* Delete a Message Batch.
*
* Message Batches can only be deleted once they've finished processing. If you'd
* like to delete an in-progress batch, you must first cancel it.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaDeletedMessageBatch =
* await client.beta.messages.batches.delete(
* 'message_batch_id',
* );
* ```
*/
delete(messageBatchID: string, params?: BatchDeleteParams | null | undefined, options?: RequestOptions): APIPromise<BetaDeletedMessageBatch>;
/**
* Batches may be canceled any time before processing ends. Once cancellation is
* initiated, the batch enters a `canceling` state, at which time the system may
* complete any in-progress, non-interruptible requests before finalizing
* cancellation.
*
* The number of canceled requests is specified in `request_counts`. To determine
* which requests were canceled, check the individual results within the batch.
* Note that cancellation may not result in any canceled requests if they were
* non-interruptible.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.cancel(
* 'message_batch_id',
* );
* ```
*/
cancel(messageBatchID: string, params?: BatchCancelParams | null | undefined, options?: RequestOptions): APIPromise<BetaMessageBatch>;
/**
* Streams the results of a Message Batch as a `.jsonl` file.
*
* Each line in the file is a JSON object containing the result of a single request
* in the Message Batch. Results are not guaranteed to be in the same order as
* requests. Use the `custom_id` field to match results to requests.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatchIndividualResponse =
* await client.beta.messages.batches.results(
* 'message_batch_id',
* );
* ```
*/
results(messageBatchID: string, params?: BatchResultsParams | undefined, options?: RequestOptions): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;
}
export type BetaMessageBatchesPage = Page<BetaMessageBatch>;
export interface BetaDeletedMessageBatch {
/**
* ID of the Message Batch.
*/
id: string;
/**
* Deleted object type.
*
* For Message Batches, this is always `"message_batch_deleted"`.
*/
type: 'message_batch_deleted';
}
export interface BetaMessageBatch {
/**
* Unique object identifier.
*
* The format and length of IDs may change over time.
*/
id: string;
/**
* RFC 3339 datetime string representing the time at which the Message Batch was
* archived and its results became unavailable.
*/
archived_at: string | null;
/**
* RFC 3339 datetime string representing the time at which cancellation was
* initiated for the Message Batch. Specified only if cancellation was initiated.
*/
cancel_initiated_at: string | null;
/**
* RFC 3339 datetime string representing the time at which the Message Batch was
* created.
*/
created_at: string;
/**
* RFC 3339 datetime string representing the time at which processing for the
* Message Batch ended. Specified only once processing ends.
*
* Processing ends when every request in a Message Batch has either succeeded,
* errored, canceled, or expired.
*/
ended_at: string | null;
/**
* RFC 3339 datetime string representing the time at which the Message Batch will
* expire and end processing, which is 24 hours after creation.
*/
expires_at: string;
/**
* Processing status of the Message Batch.
*/
processing_status: 'in_progress' | 'canceling' | 'ended';
/**
* Tallies requests within the Message Batch, categorized by their status.
*
* Requests start as `processing` and move to one of the other statuses only once
* processing of the entire batch ends. The sum of all values always matches the
* total number of requests in the batch.
*/
request_counts: BetaMessageBatchRequestCounts;
/**
* URL to a `.jsonl` file containing the results of the Message Batch requests.
* Specified only once processing ends.
*
* Results in the file are not guaranteed to be in the same order as requests. Use
* the `custom_id` field to match results to requests.
*/
results_url: string | null;
/**
* Object type.
*
* For Message Batches, this is always `"message_batch"`.
*/
type: 'message_batch';
}
export interface BetaMessageBatchCanceledResult {
type: 'canceled';
}
export interface BetaMessageBatchErroredResult {
error: BetaAPI.BetaErrorResponse;
type: 'errored';
}
export interface BetaMessageBatchExpiredResult {
type: 'expired';
}
/**
* This is a single line in the response `.jsonl` file and does not represent the
* response as a whole.
*/
export interface BetaMessageBatchIndividualResponse {
/**
* Developer-provided ID created for each request in a Message Batch. Useful for
* matching results to requests, as results may be given out of request order.
*
* Must be unique for each request within the Message Batch.
*/
custom_id: string;
/**
* Processing result for this request.
*
* Contains a Message output if processing was successful, an error response if
* processing failed, or the reason why processing was not attempted, such as
* cancellation or expiration.
*/
result: BetaMessageBatchResult;
}
export interface BetaMessageBatchRequestCounts {
/**
* Number of requests in the Message Batch that have been canceled.
*
* This is zero until processing of the entire Message Batch has ended.
*/
canceled: number;
/**
* Number of requests in the Message Batch that encountered an error.
*
* This is zero until processing of the entire Message Batch has ended.
*/
errored: number;
/**
* Number of requests in the Message Batch that have expired.
*
* This is zero until processing of the entire Message Batch has ended.
*/
expired: number;
/**
* Number of requests in the Message Batch that are processing.
*/
processing: number;
/**
* Number of requests in the Message Batch that have completed successfully.
*
* This is zero until processing of the entire Message Batch has ended.
*/
succeeded: number;
}
/**
* Processing result for this request.
*
* Contains a Message output if processing was successful, an error response if
* processing failed, or the reason why processing was not attempted, such as
* cancellation or expiration.
*/
export type BetaMessageBatchResult = BetaMessageBatchSucceededResult | BetaMessageBatchErroredResult | BetaMessageBatchCanceledResult | BetaMessageBatchExpiredResult;
export interface BetaMessageBatchSucceededResult {
message: BetaMessagesAPI.BetaMessage;
type: 'succeeded';
}
export interface BatchCreateParams {
/**
* Body param: List of requests for prompt completion. Each is an individual
* request to create a Message.
*/
requests: Array<BatchCreateParams.Request>;
/**
* Header param: Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export declare namespace BatchCreateParams {
interface Request {
/**
* Developer-provided ID created for each request in a Message Batch. Useful for
* matching results to requests, as results may be given out of request order.
*
* Must be unique for each request within the Message Batch.
*/
custom_id: string;
/**
* Messages API creation parameters for the individual request.
*
* See the [Messages API reference](https://docs.claude.com/en/api/messages) for
* full documentation on available parameters.
*/
params: Request.Params;
}
namespace Request {
/**
* Messages API creation parameters for the individual request.
*
* See the [Messages API reference](https://docs.claude.com/en/api/messages) for
* full documentation on available parameters.
*/
interface Params {
/**
* The maximum number of tokens to generate before stopping.
*
* Note that our models may stop _before_ reaching this maximum. This parameter
* only specifies the absolute maximum number of tokens to generate.
*
* Different models have different maximum values for this parameter. See
* [models](https://docs.claude.com/en/docs/models-overview) for details.
*/
max_tokens: number;
/**
* Input messages.
*
* Our models are trained to operate on alternating `user` and `assistant`
* conversational turns. When creating a new `Message`, you specify the prior
* conversational turns with the `messages` parameter, and the model then generates
* the next `Message` in the conversation. Consecutive `user` or `assistant` turns
* in your request will be combined into a single turn.
*
* Each input message must be an object with a `role` and `content`. You can
* specify a single `user`-role message, or you can include multiple `user` and
* `assistant` messages.
*
* If the final message uses the `assistant` role, the response content will
* continue immediately from the content in that message. This can be used to
* constrain part of the model's response.
*
* Example with a single `user` message:
*
* ```json
* [{ "role": "user", "content": "Hello, Claude" }]
* ```
*
* Example with multiple conversational turns:
*
* ```json
* [
* { "role": "user", "content": "Hello there." },
* { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
* { "role": "user", "content": "Can you explain LLMs in plain English?" }
* ]
* ```
*
* Example with a partially-filled response from Claude:
*
* ```json
* [
* {
* "role": "user",
* "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
* },
* { "role": "assistant", "content": "The best answer is (" }
* ]
* ```
*
* Each input message `content` may be either a single `string` or an array of
* content blocks, where each block has a specific `type`. Using a `string` for
* `content` is shorthand for an array of one content block of type `"text"`. The
* following input messages are equivalent:
*
* ```json
* { "role": "user", "content": "Hello, Claude" }
* ```
*
* ```json
* { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
* ```
*
* See [input examples](https://docs.claude.com/en/api/messages-examples).
*
* Note that if you want to include a
* [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the
* top-level `system` parameter — there is no `"system"` role for input messages in
* the Messages API.
*
* There is a limit of 100,000 messages in a single request.
*/
messages: Array<BetaMessagesAPI.BetaMessageParam>;
/**
* The model that will complete your prompt.\n\nSee
* [models](https://docs.anthropic.com/en/docs/models-overview) for additional
* details and options.
*/
model: MessagesApi.Model;
/**
* Top-level cache control automatically applies a cache_control marker to the last
* cacheable block in the request.
*/
cache_control?: BetaMessagesAPI.BetaCacheControlEphemeral | null;
/**
* Container identifier for reuse across requests.
*/
container?: BetaMessagesAPI.BetaContainerParams | string | null;
/**
* Context management configuration.
*
* This allows you to control how Claude manages context across multiple requests,
* such as whether to clear function results or not.
*/
context_management?: BetaMessagesAPI.BetaContextManagementConfig | null;
/**
* Specifies the geographic region for inference processing. If not specified, the
* workspace's `default_inference_geo` is used.
*/
inference_geo?: string | null;
/**
* MCP servers to be utilized in this request
*/
mcp_servers?: Array<BetaMessagesAPI.BetaRequestMCPServerURLDefinition>;
/**
* An object describing metadata about the request.
*/
metadata?: BetaMessagesAPI.BetaMetadata;
/**
* Configuration options for the model's output, such as the output format.
*/
output_config?: BetaMessagesAPI.BetaOutputConfig;
/**
* @deprecated Deprecated: Use `output_config.format` instead. See
* [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
*
* A schema to specify Claude's output format in responses. This parameter will be
* removed in a future release.
*/
output_format?: BetaMessagesAPI.BetaJSONOutputFormat | null;
/**
* Determines whether to use priority capacity (if available) or standard capacity
* for this request.
*
* Anthropic offers different levels of service for your API requests. See
* [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.
*/
service_tier?: 'auto' | 'standard_only';
/**
* The inference speed mode for this request. `"fast"` enables high
* output-tokens-per-second inference.
*/
speed?: 'standard' | 'fast' | null;
/**
* Custom text sequences that will cause the model to stop generating.
*
* Our models will normally stop when they have naturally completed their turn,
* which will result in a response `stop_reason` of `"end_turn"`.
*
* If you want the model to stop generating when it encounters custom strings of
* text, you can use the `stop_sequences` parameter. If the model encounters one of
* the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
* and the response `stop_sequence` value will contain the matched stop sequence.
*/
stop_sequences?: Array<string>;
/**
* Whether to incrementally stream the response using server-sent events.
*
* See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.
*/
stream?: boolean;
/**
* System prompt.
*
* A system prompt is a way of providing context and instructions to Claude, such
* as specifying a particular goal or role. See our
* [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).
*/
system?: string | Array<BetaMessagesAPI.BetaTextBlockParam>;
/**
* Amount of randomness injected into the response.
*
* Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
* for analytical / multiple choice, and closer to `1.0` for creative and
* generative tasks.
*
* Note that even with `temperature` of `0.0`, the results will not be fully
* deterministic.
*/
temperature?: number;
/**
* Configuration for enabling Claude's extended thinking.
*
* When enabled, responses include `thinking` content blocks showing Claude's
* thinking process before the final answer. Requires a minimum budget of 1,024
* tokens and counts towards your `max_tokens` limit.
*
* See
* [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)
* for details.
*/
thinking?: BetaMessagesAPI.BetaThinkingConfigParam;
/**
* How the model should use the provided tools. The model can use a specific tool,
* any available tool, decide by itself, or not use tools at all.
*/
tool_choice?: BetaMessagesAPI.BetaToolChoice;
/**
* Definitions of tools that the model may use.
*
* If you include `tools` in your API request, the model may return `tool_use`
* content blocks that represent the model's use of those tools. You can then run
* those tools using the tool input generated by the model and then optionally
* return results back to the model using `tool_result` content blocks.
*
* There are two types of tools: **client tools** and **server tools**. The
* behavior described below applies to client tools. For
* [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools),
* see their individual documentation as each has its own behavior (e.g., the
* [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).
*
* Each tool definition includes:
*
* - `name`: Name of the tool.
* - `description`: Optional, but strongly-recommended description of the tool.
* - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
* tool `input` shape that the model will produce in `tool_use` output content
* blocks.
*
* For example, if you defined `tools` as:
*
* ```json
* [
* {
* "name": "get_stock_price",
* "description": "Get the current stock price for a given ticker symbol.",
* "input_schema": {
* "type": "object",
* "properties": {
* "ticker": {
* "type": "string",
* "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
* }
* },
* "required": ["ticker"]
* }
* }
* ]
* ```
*
* And then asked the model "What's the S&P 500 at today?", the model might produce
* `tool_use` content blocks in the response like this:
*
* ```json
* [
* {
* "type": "tool_use",
* "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
* "name": "get_stock_price",
* "input": { "ticker": "^GSPC" }
* }
* ]
* ```
*
* You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
* input, and return the following back to the model in a subsequent `user`
* message:
*
* ```json
* [
* {
* "type": "tool_result",
* "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
* "content": "259.75 USD"
* }
* ]
* ```
*
* Tools can be used for workflows that include running client-side tools and
* functions, or more generally whenever you want the model to produce a particular
* JSON structure of output.
*
* See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.
*/
tools?: Array<BetaMessagesAPI.BetaToolUnion>;
/**
* Only sample from the top K options for each subsequent token.
*
* Used to remove "long tail" low probability responses.
* [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
*
* Recommended for advanced use cases only. You usually only need to use
* `temperature`.
*/
top_k?: number;
/**
* Use nucleus sampling.
*
* In nucleus sampling, we compute the cumulative distribution over all the options
* for each subsequent token in decreasing probability order and cut it off once it
* reaches a particular probability specified by `top_p`. You should either alter
* `temperature` or `top_p`, but not both.
*
* Recommended for advanced use cases only. You usually only need to use
* `temperature`.
*/
top_p?: number;
}
}
}
export interface BatchRetrieveParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchListParams extends PageParams {
/**
* Header param: Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchDeleteParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchCancelParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchResultsParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export declare namespace Batches {
export { type BetaDeletedMessageBatch as BetaDeletedMessageBatch, type BetaMessageBatch as BetaMessageBatch, type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult, type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult, type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult, type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse, type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts, type BetaMessageBatchResult as BetaMessageBatchResult, type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult, type BetaMessageBatchesPage as BetaMessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchRetrieveParams as BatchRetrieveParams, type BatchListParams as BatchListParams, type BatchDeleteParams as BatchDeleteParams, type BatchCancelParams as BatchCancelParams, type BatchResultsParams as BatchResultsParams, };
}
//# sourceMappingURL=batches.d.mts.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,646 @@
import { APIResource } from "../../../core/resource.js";
import * as BetaAPI from "../beta.js";
import { APIPromise } from "../../../core/api-promise.js";
import * as BetaMessagesAPI from "./messages.js";
import { Page, type PageParams, PagePromise } from "../../../core/pagination.js";
import { RequestOptions } from "../../../internal/request-options.js";
import { JSONLDecoder } from "../../../internal/decoders/jsonl.js";
import * as MessagesApi from "../../messages/messages.js";
export declare class Batches extends APIResource {
/**
* Send a batch of Message creation requests.
*
* The Message Batches API can be used to process multiple Messages API requests at
* once. Once a Message Batch is created, it begins processing immediately. Batches
* can take up to 24 hours to complete.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.create({
* requests: [
* {
* custom_id: 'my-custom-id-1',
* params: {
* max_tokens: 1024,
* messages: [
* { content: 'Hello, world', role: 'user' },
* ],
* model: 'claude-opus-4-6',
* },
* },
* ],
* });
* ```
*/
create(params: BatchCreateParams, options?: RequestOptions): APIPromise<BetaMessageBatch>;
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.retrieve(
* 'message_batch_id',
* );
* ```
*/
retrieve(messageBatchID: string, params?: BatchRetrieveParams | null | undefined, options?: RequestOptions): APIPromise<BetaMessageBatch>;
/**
* List all Message Batches within a Workspace. Most recently created batches are
* returned first.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const betaMessageBatch of client.beta.messages.batches.list()) {
* // ...
* }
* ```
*/
list(params?: BatchListParams | null | undefined, options?: RequestOptions): PagePromise<BetaMessageBatchesPage, BetaMessageBatch>;
/**
* Delete a Message Batch.
*
* Message Batches can only be deleted once they've finished processing. If you'd
* like to delete an in-progress batch, you must first cancel it.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaDeletedMessageBatch =
* await client.beta.messages.batches.delete(
* 'message_batch_id',
* );
* ```
*/
delete(messageBatchID: string, params?: BatchDeleteParams | null | undefined, options?: RequestOptions): APIPromise<BetaDeletedMessageBatch>;
/**
* Batches may be canceled any time before processing ends. Once cancellation is
* initiated, the batch enters a `canceling` state, at which time the system may
* complete any in-progress, non-interruptible requests before finalizing
* cancellation.
*
* The number of canceled requests is specified in `request_counts`. To determine
* which requests were canceled, check the individual results within the batch.
* Note that cancellation may not result in any canceled requests if they were
* non-interruptible.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.cancel(
* 'message_batch_id',
* );
* ```
*/
cancel(messageBatchID: string, params?: BatchCancelParams | null | undefined, options?: RequestOptions): APIPromise<BetaMessageBatch>;
/**
* Streams the results of a Message Batch as a `.jsonl` file.
*
* Each line in the file is a JSON object containing the result of a single request
* in the Message Batch. Results are not guaranteed to be in the same order as
* requests. Use the `custom_id` field to match results to requests.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatchIndividualResponse =
* await client.beta.messages.batches.results(
* 'message_batch_id',
* );
* ```
*/
results(messageBatchID: string, params?: BatchResultsParams | undefined, options?: RequestOptions): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>>;
}
export type BetaMessageBatchesPage = Page<BetaMessageBatch>;
export interface BetaDeletedMessageBatch {
/**
* ID of the Message Batch.
*/
id: string;
/**
* Deleted object type.
*
* For Message Batches, this is always `"message_batch_deleted"`.
*/
type: 'message_batch_deleted';
}
export interface BetaMessageBatch {
/**
* Unique object identifier.
*
* The format and length of IDs may change over time.
*/
id: string;
/**
* RFC 3339 datetime string representing the time at which the Message Batch was
* archived and its results became unavailable.
*/
archived_at: string | null;
/**
* RFC 3339 datetime string representing the time at which cancellation was
* initiated for the Message Batch. Specified only if cancellation was initiated.
*/
cancel_initiated_at: string | null;
/**
* RFC 3339 datetime string representing the time at which the Message Batch was
* created.
*/
created_at: string;
/**
* RFC 3339 datetime string representing the time at which processing for the
* Message Batch ended. Specified only once processing ends.
*
* Processing ends when every request in a Message Batch has either succeeded,
* errored, canceled, or expired.
*/
ended_at: string | null;
/**
* RFC 3339 datetime string representing the time at which the Message Batch will
* expire and end processing, which is 24 hours after creation.
*/
expires_at: string;
/**
* Processing status of the Message Batch.
*/
processing_status: 'in_progress' | 'canceling' | 'ended';
/**
* Tallies requests within the Message Batch, categorized by their status.
*
* Requests start as `processing` and move to one of the other statuses only once
* processing of the entire batch ends. The sum of all values always matches the
* total number of requests in the batch.
*/
request_counts: BetaMessageBatchRequestCounts;
/**
* URL to a `.jsonl` file containing the results of the Message Batch requests.
* Specified only once processing ends.
*
* Results in the file are not guaranteed to be in the same order as requests. Use
* the `custom_id` field to match results to requests.
*/
results_url: string | null;
/**
* Object type.
*
* For Message Batches, this is always `"message_batch"`.
*/
type: 'message_batch';
}
export interface BetaMessageBatchCanceledResult {
type: 'canceled';
}
export interface BetaMessageBatchErroredResult {
error: BetaAPI.BetaErrorResponse;
type: 'errored';
}
export interface BetaMessageBatchExpiredResult {
type: 'expired';
}
/**
* This is a single line in the response `.jsonl` file and does not represent the
* response as a whole.
*/
export interface BetaMessageBatchIndividualResponse {
/**
* Developer-provided ID created for each request in a Message Batch. Useful for
* matching results to requests, as results may be given out of request order.
*
* Must be unique for each request within the Message Batch.
*/
custom_id: string;
/**
* Processing result for this request.
*
* Contains a Message output if processing was successful, an error response if
* processing failed, or the reason why processing was not attempted, such as
* cancellation or expiration.
*/
result: BetaMessageBatchResult;
}
export interface BetaMessageBatchRequestCounts {
/**
* Number of requests in the Message Batch that have been canceled.
*
* This is zero until processing of the entire Message Batch has ended.
*/
canceled: number;
/**
* Number of requests in the Message Batch that encountered an error.
*
* This is zero until processing of the entire Message Batch has ended.
*/
errored: number;
/**
* Number of requests in the Message Batch that have expired.
*
* This is zero until processing of the entire Message Batch has ended.
*/
expired: number;
/**
* Number of requests in the Message Batch that are processing.
*/
processing: number;
/**
* Number of requests in the Message Batch that have completed successfully.
*
* This is zero until processing of the entire Message Batch has ended.
*/
succeeded: number;
}
/**
* Processing result for this request.
*
* Contains a Message output if processing was successful, an error response if
* processing failed, or the reason why processing was not attempted, such as
* cancellation or expiration.
*/
export type BetaMessageBatchResult = BetaMessageBatchSucceededResult | BetaMessageBatchErroredResult | BetaMessageBatchCanceledResult | BetaMessageBatchExpiredResult;
export interface BetaMessageBatchSucceededResult {
message: BetaMessagesAPI.BetaMessage;
type: 'succeeded';
}
export interface BatchCreateParams {
/**
* Body param: List of requests for prompt completion. Each is an individual
* request to create a Message.
*/
requests: Array<BatchCreateParams.Request>;
/**
* Header param: Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export declare namespace BatchCreateParams {
interface Request {
/**
* Developer-provided ID created for each request in a Message Batch. Useful for
* matching results to requests, as results may be given out of request order.
*
* Must be unique for each request within the Message Batch.
*/
custom_id: string;
/**
* Messages API creation parameters for the individual request.
*
* See the [Messages API reference](https://docs.claude.com/en/api/messages) for
* full documentation on available parameters.
*/
params: Request.Params;
}
namespace Request {
/**
* Messages API creation parameters for the individual request.
*
* See the [Messages API reference](https://docs.claude.com/en/api/messages) for
* full documentation on available parameters.
*/
interface Params {
/**
* The maximum number of tokens to generate before stopping.
*
* Note that our models may stop _before_ reaching this maximum. This parameter
* only specifies the absolute maximum number of tokens to generate.
*
* Different models have different maximum values for this parameter. See
* [models](https://docs.claude.com/en/docs/models-overview) for details.
*/
max_tokens: number;
/**
* Input messages.
*
* Our models are trained to operate on alternating `user` and `assistant`
* conversational turns. When creating a new `Message`, you specify the prior
* conversational turns with the `messages` parameter, and the model then generates
* the next `Message` in the conversation. Consecutive `user` or `assistant` turns
* in your request will be combined into a single turn.
*
* Each input message must be an object with a `role` and `content`. You can
* specify a single `user`-role message, or you can include multiple `user` and
* `assistant` messages.
*
* If the final message uses the `assistant` role, the response content will
* continue immediately from the content in that message. This can be used to
* constrain part of the model's response.
*
* Example with a single `user` message:
*
* ```json
* [{ "role": "user", "content": "Hello, Claude" }]
* ```
*
* Example with multiple conversational turns:
*
* ```json
* [
* { "role": "user", "content": "Hello there." },
* { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
* { "role": "user", "content": "Can you explain LLMs in plain English?" }
* ]
* ```
*
* Example with a partially-filled response from Claude:
*
* ```json
* [
* {
* "role": "user",
* "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
* },
* { "role": "assistant", "content": "The best answer is (" }
* ]
* ```
*
* Each input message `content` may be either a single `string` or an array of
* content blocks, where each block has a specific `type`. Using a `string` for
* `content` is shorthand for an array of one content block of type `"text"`. The
* following input messages are equivalent:
*
* ```json
* { "role": "user", "content": "Hello, Claude" }
* ```
*
* ```json
* { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
* ```
*
* See [input examples](https://docs.claude.com/en/api/messages-examples).
*
* Note that if you want to include a
* [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the
* top-level `system` parameter — there is no `"system"` role for input messages in
* the Messages API.
*
* There is a limit of 100,000 messages in a single request.
*/
messages: Array<BetaMessagesAPI.BetaMessageParam>;
/**
* The model that will complete your prompt.\n\nSee
* [models](https://docs.anthropic.com/en/docs/models-overview) for additional
* details and options.
*/
model: MessagesApi.Model;
/**
* Top-level cache control automatically applies a cache_control marker to the last
* cacheable block in the request.
*/
cache_control?: BetaMessagesAPI.BetaCacheControlEphemeral | null;
/**
* Container identifier for reuse across requests.
*/
container?: BetaMessagesAPI.BetaContainerParams | string | null;
/**
* Context management configuration.
*
* This allows you to control how Claude manages context across multiple requests,
* such as whether to clear function results or not.
*/
context_management?: BetaMessagesAPI.BetaContextManagementConfig | null;
/**
* Specifies the geographic region for inference processing. If not specified, the
* workspace's `default_inference_geo` is used.
*/
inference_geo?: string | null;
/**
* MCP servers to be utilized in this request
*/
mcp_servers?: Array<BetaMessagesAPI.BetaRequestMCPServerURLDefinition>;
/**
* An object describing metadata about the request.
*/
metadata?: BetaMessagesAPI.BetaMetadata;
/**
* Configuration options for the model's output, such as the output format.
*/
output_config?: BetaMessagesAPI.BetaOutputConfig;
/**
* @deprecated Deprecated: Use `output_config.format` instead. See
* [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
*
* A schema to specify Claude's output format in responses. This parameter will be
* removed in a future release.
*/
output_format?: BetaMessagesAPI.BetaJSONOutputFormat | null;
/**
* Determines whether to use priority capacity (if available) or standard capacity
* for this request.
*
* Anthropic offers different levels of service for your API requests. See
* [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.
*/
service_tier?: 'auto' | 'standard_only';
/**
* The inference speed mode for this request. `"fast"` enables high
* output-tokens-per-second inference.
*/
speed?: 'standard' | 'fast' | null;
/**
* Custom text sequences that will cause the model to stop generating.
*
* Our models will normally stop when they have naturally completed their turn,
* which will result in a response `stop_reason` of `"end_turn"`.
*
* If you want the model to stop generating when it encounters custom strings of
* text, you can use the `stop_sequences` parameter. If the model encounters one of
* the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
* and the response `stop_sequence` value will contain the matched stop sequence.
*/
stop_sequences?: Array<string>;
/**
* Whether to incrementally stream the response using server-sent events.
*
* See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.
*/
stream?: boolean;
/**
* System prompt.
*
* A system prompt is a way of providing context and instructions to Claude, such
* as specifying a particular goal or role. See our
* [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).
*/
system?: string | Array<BetaMessagesAPI.BetaTextBlockParam>;
/**
* Amount of randomness injected into the response.
*
* Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
* for analytical / multiple choice, and closer to `1.0` for creative and
* generative tasks.
*
* Note that even with `temperature` of `0.0`, the results will not be fully
* deterministic.
*/
temperature?: number;
/**
* Configuration for enabling Claude's extended thinking.
*
* When enabled, responses include `thinking` content blocks showing Claude's
* thinking process before the final answer. Requires a minimum budget of 1,024
* tokens and counts towards your `max_tokens` limit.
*
* See
* [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)
* for details.
*/
thinking?: BetaMessagesAPI.BetaThinkingConfigParam;
/**
* How the model should use the provided tools. The model can use a specific tool,
* any available tool, decide by itself, or not use tools at all.
*/
tool_choice?: BetaMessagesAPI.BetaToolChoice;
/**
* Definitions of tools that the model may use.
*
* If you include `tools` in your API request, the model may return `tool_use`
* content blocks that represent the model's use of those tools. You can then run
* those tools using the tool input generated by the model and then optionally
* return results back to the model using `tool_result` content blocks.
*
* There are two types of tools: **client tools** and **server tools**. The
* behavior described below applies to client tools. For
* [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools),
* see their individual documentation as each has its own behavior (e.g., the
* [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).
*
* Each tool definition includes:
*
* - `name`: Name of the tool.
* - `description`: Optional, but strongly-recommended description of the tool.
* - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
* tool `input` shape that the model will produce in `tool_use` output content
* blocks.
*
* For example, if you defined `tools` as:
*
* ```json
* [
* {
* "name": "get_stock_price",
* "description": "Get the current stock price for a given ticker symbol.",
* "input_schema": {
* "type": "object",
* "properties": {
* "ticker": {
* "type": "string",
* "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
* }
* },
* "required": ["ticker"]
* }
* }
* ]
* ```
*
* And then asked the model "What's the S&P 500 at today?", the model might produce
* `tool_use` content blocks in the response like this:
*
* ```json
* [
* {
* "type": "tool_use",
* "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
* "name": "get_stock_price",
* "input": { "ticker": "^GSPC" }
* }
* ]
* ```
*
* You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
* input, and return the following back to the model in a subsequent `user`
* message:
*
* ```json
* [
* {
* "type": "tool_result",
* "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
* "content": "259.75 USD"
* }
* ]
* ```
*
* Tools can be used for workflows that include running client-side tools and
* functions, or more generally whenever you want the model to produce a particular
* JSON structure of output.
*
* See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.
*/
tools?: Array<BetaMessagesAPI.BetaToolUnion>;
/**
* Only sample from the top K options for each subsequent token.
*
* Used to remove "long tail" low probability responses.
* [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
*
* Recommended for advanced use cases only. You usually only need to use
* `temperature`.
*/
top_k?: number;
/**
* Use nucleus sampling.
*
* In nucleus sampling, we compute the cumulative distribution over all the options
* for each subsequent token in decreasing probability order and cut it off once it
* reaches a particular probability specified by `top_p`. You should either alter
* `temperature` or `top_p`, but not both.
*
* Recommended for advanced use cases only. You usually only need to use
* `temperature`.
*/
top_p?: number;
}
}
}
export interface BatchRetrieveParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchListParams extends PageParams {
/**
* Header param: Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchDeleteParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchCancelParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export interface BatchResultsParams {
/**
* Optional header to specify the beta version(s) you want to use.
*/
betas?: Array<BetaAPI.AnthropicBeta>;
}
export declare namespace Batches {
export { type BetaDeletedMessageBatch as BetaDeletedMessageBatch, type BetaMessageBatch as BetaMessageBatch, type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult, type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult, type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult, type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse, type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts, type BetaMessageBatchResult as BetaMessageBatchResult, type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult, type BetaMessageBatchesPage as BetaMessageBatchesPage, type BatchCreateParams as BatchCreateParams, type BatchRetrieveParams as BatchRetrieveParams, type BatchListParams as BatchListParams, type BatchDeleteParams as BatchDeleteParams, type BatchCancelParams as BatchCancelParams, type BatchResultsParams as BatchResultsParams, };
}
//# sourceMappingURL=batches.d.ts.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,204 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Batches = void 0;
const resource_1 = require("../../../core/resource.js");
const pagination_1 = require("../../../core/pagination.js");
const headers_1 = require("../../../internal/headers.js");
const jsonl_1 = require("../../../internal/decoders/jsonl.js");
const error_1 = require("../../../error.js");
const path_1 = require("../../../internal/utils/path.js");
class Batches extends resource_1.APIResource {
/**
* Send a batch of Message creation requests.
*
* The Message Batches API can be used to process multiple Messages API requests at
* once. Once a Message Batch is created, it begins processing immediately. Batches
* can take up to 24 hours to complete.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.create({
* requests: [
* {
* custom_id: 'my-custom-id-1',
* params: {
* max_tokens: 1024,
* messages: [
* { content: 'Hello, world', role: 'user' },
* ],
* model: 'claude-opus-4-6',
* },
* },
* ],
* });
* ```
*/
create(params, options) {
const { betas, ...body } = params;
return this._client.post('/v1/messages/batches?beta=true', {
body,
...options,
headers: (0, headers_1.buildHeaders)([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.retrieve(
* 'message_batch_id',
* );
* ```
*/
retrieve(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.get((0, path_1.path) `/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,
headers: (0, headers_1.buildHeaders)([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* List all Message Batches within a Workspace. Most recently created batches are
* returned first.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const betaMessageBatch of client.beta.messages.batches.list()) {
* // ...
* }
* ```
*/
list(params = {}, options) {
const { betas, ...query } = params ?? {};
return this._client.getAPIList('/v1/messages/batches?beta=true', (pagination_1.Page), {
query,
...options,
headers: (0, headers_1.buildHeaders)([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* Delete a Message Batch.
*
* Message Batches can only be deleted once they've finished processing. If you'd
* like to delete an in-progress batch, you must first cancel it.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaDeletedMessageBatch =
* await client.beta.messages.batches.delete(
* 'message_batch_id',
* );
* ```
*/
delete(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.delete((0, path_1.path) `/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,
headers: (0, headers_1.buildHeaders)([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* Batches may be canceled any time before processing ends. Once cancellation is
* initiated, the batch enters a `canceling` state, at which time the system may
* complete any in-progress, non-interruptible requests before finalizing
* cancellation.
*
* The number of canceled requests is specified in `request_counts`. To determine
* which requests were canceled, check the individual results within the batch.
* Note that cancellation may not result in any canceled requests if they were
* non-interruptible.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.cancel(
* 'message_batch_id',
* );
* ```
*/
cancel(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.post((0, path_1.path) `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
...options,
headers: (0, headers_1.buildHeaders)([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* Streams the results of a Message Batch as a `.jsonl` file.
*
* Each line in the file is a JSON object containing the result of a single request
* in the Message Batch. Results are not guaranteed to be in the same order as
* requests. Use the `custom_id` field to match results to requests.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatchIndividualResponse =
* await client.beta.messages.batches.results(
* 'message_batch_id',
* );
* ```
*/
async results(messageBatchID, params = {}, options) {
const batch = await this.retrieve(messageBatchID);
if (!batch.results_url) {
throw new error_1.AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
}
const { betas } = params ?? {};
return this._client
.get(batch.results_url, {
...options,
headers: (0, headers_1.buildHeaders)([
{
'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),
Accept: 'application/binary',
},
options?.headers,
]),
stream: true,
__binaryResponse: true,
})
._thenUnwrap((_, props) => jsonl_1.JSONLDecoder.fromResponse(props.response, props.controller));
}
}
exports.Batches = Batches;
//# sourceMappingURL=batches.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"batches.js","sourceRoot":"","sources":["../../../src/resources/beta/messages/batches.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,wDAAqD;AAIrD,4DAA8E;AAC9E,0DAAyD;AAEzD,+DAAgE;AAChE,6CAAgD;AAChD,0DAAoD;AAGpD,MAAa,OAAQ,SAAQ,sBAAW;IACtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,MAAM,CAAC,MAAyB,EAAE,OAAwB;QACxD,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;QAClC,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,gCAAgC,EAAE;YACzD,IAAI;YACJ,GAAG,OAAO;YACV,OAAO,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AM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC,OAAO;aAChB,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE;YACtB,GAAG,OAAO;YACV,OAAO,EAAE,IAAA,sBAAY,EAAC;gBACpB;oBACE,gBAAgB,EAAE,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,4BAA4B,CAAC,CAAC,QAAQ,EAAE;oBAC7E,MAAM,EAAE,oBAAoB;iBAC7B;gBACD,OAAO,EAAE,OAAO;aACjB,CAAC;YACF,MAAM,EAAE,IAAI;YACZ,gBAAgB,EAAE,IAAI;SACvB,CAAC;aACD,WAAW,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,oBAAY,CAAC,YAAY,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,UAAU,CAAC,CAEvF,CAAC;IACJ,CAAC;CACF;AA5ND,0BA4NC"}

View File

@@ -0,0 +1,200 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../../core/resource.mjs";
import { Page } from "../../../core/pagination.mjs";
import { buildHeaders } from "../../../internal/headers.mjs";
import { JSONLDecoder } from "../../../internal/decoders/jsonl.mjs";
import { AnthropicError } from "../../../error.mjs";
import { path } from "../../../internal/utils/path.mjs";
export class Batches extends APIResource {
/**
* Send a batch of Message creation requests.
*
* The Message Batches API can be used to process multiple Messages API requests at
* once. Once a Message Batch is created, it begins processing immediately. Batches
* can take up to 24 hours to complete.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.create({
* requests: [
* {
* custom_id: 'my-custom-id-1',
* params: {
* max_tokens: 1024,
* messages: [
* { content: 'Hello, world', role: 'user' },
* ],
* model: 'claude-opus-4-6',
* },
* },
* ],
* });
* ```
*/
create(params, options) {
const { betas, ...body } = params;
return this._client.post('/v1/messages/batches?beta=true', {
body,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.retrieve(
* 'message_batch_id',
* );
* ```
*/
retrieve(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.get(path `/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* List all Message Batches within a Workspace. Most recently created batches are
* returned first.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const betaMessageBatch of client.beta.messages.batches.list()) {
* // ...
* }
* ```
*/
list(params = {}, options) {
const { betas, ...query } = params ?? {};
return this._client.getAPIList('/v1/messages/batches?beta=true', (Page), {
query,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* Delete a Message Batch.
*
* Message Batches can only be deleted once they've finished processing. If you'd
* like to delete an in-progress batch, you must first cancel it.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaDeletedMessageBatch =
* await client.beta.messages.batches.delete(
* 'message_batch_id',
* );
* ```
*/
delete(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.delete(path `/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* Batches may be canceled any time before processing ends. Once cancellation is
* initiated, the batch enters a `canceling` state, at which time the system may
* complete any in-progress, non-interruptible requests before finalizing
* cancellation.
*
* The number of canceled requests is specified in `request_counts`. To determine
* which requests were canceled, check the individual results within the batch.
* Note that cancellation may not result in any canceled requests if they were
* non-interruptible.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.cancel(
* 'message_batch_id',
* );
* ```
*/
cancel(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* Streams the results of a Message Batch as a `.jsonl` file.
*
* Each line in the file is a JSON object containing the result of a single request
* in the Message Batch. Results are not guaranteed to be in the same order as
* requests. Use the `custom_id` field to match results to requests.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatchIndividualResponse =
* await client.beta.messages.batches.results(
* 'message_batch_id',
* );
* ```
*/
async results(messageBatchID, params = {}, options) {
const batch = await this.retrieve(messageBatchID);
if (!batch.results_url) {
throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
}
const { betas } = params ?? {};
return this._client
.get(batch.results_url, {
...options,
headers: buildHeaders([
{
'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),
Accept: 'application/binary',
},
options?.headers,
]),
stream: true,
__binaryResponse: true,
})
._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
}
}
//# sourceMappingURL=batches.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"batches.mjs","sourceRoot":"","sources":["../../../src/resources/beta/messages/batches.ts"],"names":[],"m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F,OAAO,EAAE,OAAO;aACjB,CAAC;SACH,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACH,KAAK,CAAC,OAAO,CACX,cAAsB,EACtB,SAAyC,EAAE,EAC3C,OAAwB;QAExB,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;YACvB,MAAM,IAAI,cAAc,CACtB,yDAAyD,KAAK,CAAC,iBAAiB,MAAM,KAAK,CAAC,EAAE,EAAE,CACjG,CAAC;QACJ,CAAC;QAED,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC,OAAO;aAChB,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE;YACtB,GAAG,OAAO;YACV,OAAO,EAAE,YAAY,CAAC;gBACpB;oBACE,gBAAgB,EAAE,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,4BAA4B,CAAC,CAAC,QAAQ,EAAE;oBAC7E,MAAM,EAAE,oBAAoB;iBAC7B;gBACD,OAAO,EAAE,OAAO;aACjB,CAAC;YACF,MAAM,EAAE,IAAI;YACZ,gBAAgB,EAAE,IAAI;SACvB,CAAC;aACD,WAAW,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,YAAY,CAAC,YAAY,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,UAAU,CAAC,CAEvF,CAAC;IACJ,CAAC;CACF"}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../../src/resources/beta/messages/index.ts"],"names":[],"mappings":"OAEO,EACL,OAAO,EACP,KAAK,uBAAuB,EAC5B,KAAK,gBAAgB,EACrB,KAAK,8BAA8B,EACnC,KAAK,6BAA6B,EAClC,KAAK,6BAA6B,EAClC,KAAK,kCA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AK,wBAAwB,EAC7B,KAAK,wBAAwB,EAC7B,KAAK,wBAAwB,EAC7B,KAAK,2BAA2B,EAChC,KAAK,gCAAgC,EACrC,KAAK,gCAAgC,EACrC,KAAK,qCAAqC,EAC1C,KAAK,+BAA+B,EACpC,KAAK,wBAAwB,EAC7B,KAAK,6BAA6B,EAClC,KAAK,yBAAyB,EAC9B,KAAK,yBAAyB,EAC9B,KAAK,6BAA6B,EAClC,KAAK,4BAA4B,EACjC,KAAK,mCAAmC,EACxC,KAAK,iCAAiC,EACtC,KAAK,wCAAwC,EAC7C,KAAK,4BAA4B,EACjC,KAAK,gCAAgC,EACrC,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,KAAK,+BAA+B,EACpC,KAAK,4BAA4B,EACjC,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,+BAA+B,EACpC,KAAK,+BAA+B,EACpC,KAAK,6BAA6B,EAClC,KAAK,kCAAkC,EACvC,KAAK,6BAA6B,EAClC,KAAK,kCAAkC,EACvC,KAAK,mCAAmC,EACxC,KAAK,wCAAwC,EAC7C,KAAK,iBAAiB,EACtB,KAAK,wBAAwB,EAC7B,KAAK,+BAA+B,GACrC;OACM,EAAE,cAAc,EAAE,KAAK,oBAAoB,EAAE,SAAS,EAAE"}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/resources/beta/messages/index.ts"],"names":[],"mappings":"OAEO,EACL,OAAO,EACP,KAAK,uBAAuB,EAC5B,KAAK,gBAAgB,EACrB,KAAK,8BAA8B,EACnC,KAAK,6BAA6B,EAClC,KAAK,6BAA6B,EAClC,KAAK,kCAAkC,EACvC,KAAK,6BAA6B,EAClC,KAAK,sBAAsB,EAC3B,KAAK,+BAA+B,EACpC,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,KAAK,iBAAiB,EACtB,KAA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wB,EAC7B,KAAK,6BAA6B,EAClC,KAAK,yBAAyB,EAC9B,KAAK,yBAAyB,EAC9B,KAAK,6BAA6B,EAClC,KAAK,4BAA4B,EACjC,KAAK,mCAAmC,EACxC,KAAK,iCAAiC,EACtC,KAAK,wCAAwC,EAC7C,KAAK,4BAA4B,EACjC,KAAK,gCAAgC,EACrC,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,KAAK,+BAA+B,EACpC,KAAK,4BAA4B,EACjC,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,+BAA+B,EACpC,KAAK,+BAA+B,EACpC,KAAK,6BAA6B,EAClC,KAAK,kCAAkC,EACvC,KAAK,6BAA6B,EAClC,KAAK,kCAAkC,EACvC,KAAK,mCAAmC,EACxC,KAAK,wCAAwC,EAC7C,KAAK,iBAAiB,EACtB,KAAK,wBAAwB,EAC7B,KAAK,+BAA+B,GACrC;OACM,EAAE,cAAc,EAAE,KAAK,oBAAoB,EAAE,SAAS,EAAE"}

View File

@@ -0,0 +1,12 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ToolError = exports.BetaToolRunner = exports.Messages = exports.Batches = void 0;
var batches_1 = require("./batches.js");
Object.defineProperty(exports, "Batches", { enumerable: true, get: function () { return batches_1.Batches; } });
var messages_1 = require("./messages.js");
Object.defineProperty(exports, "Messages", { enumerable: true, get: function () { return messages_1.Messages; } });
var messages_2 = require("./messages.js");
Object.defineProperty(exports, "BetaToolRunner", { enumerable: true, get: function () { return messages_2.BetaToolRunner; } });
Object.defineProperty(exports, "ToolError", { enumerable: true, get: function () { return messages_2.ToolError; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/resources/beta/messages/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,wCAkBmB;AAjBjB,kGAAA,OAAO,OAAA;AAkBT,0CA6MoB;AA5MlB,oGAAA,QAAQ,OAAA;AA6MV,0CAAkF;AAAzE,0GAAA,cAAc,OAAA;AAA6B,qGAAA,SAAS,OAAA"}

View File

@@ -0,0 +1,5 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export { Batches, } from "./batches.mjs";
export { Messages, } from "./messages.mjs";
export { BetaToolRunner, ToolError } from "./messages.mjs";
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/resources/beta/messages/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EACL,OAAO,GAiBR;OACM,EACL,QAAQ,GA4MT;OACM,EAAE,cAAc,EAA6B,SAAS,EAAE"}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,163 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ToolError = exports.BetaToolRunner = exports.Messages = void 0;
const tslib_1 = require("../../../internal/tslib.js");
const error_1 = require("../../../error.js");
const resource_1 = require("../../../core/resource.js");
const constants_1 = require("../../../internal/constants.js");
const headers_1 = require("../../../internal/headers.js");
const stainless_helper_header_1 = require("../../../lib/stainless-helper-header.js");
const beta_parser_1 = require("../../../lib/beta-parser.js");
const BetaMessageStream_1 = require("../../../lib/BetaMessageStream.js");
const BetaToolRunner_1 = require("../../../lib/tools/BetaToolRunner.js");
const ToolError_1 = require("../../../lib/tools/ToolError.js");
const BatchesAPI = tslib_1.__importStar(require("./batches.js"));
const batches_1 = require("./batches.js");
const DEPRECATED_MODELS = {
'claude-1.3': 'November 6th, 2024',
'claude-1.3-100k': 'November 6th, 2024',
'claude-instant-1.1': 'November 6th, 2024',
'claude-instant-1.1-100k': 'November 6th, 2024',
'claude-instant-1.2': 'November 6th, 2024',
'claude-3-sonnet-20240229': 'July 21st, 2025',
'claude-3-opus-20240229': 'January 5th, 2026',
'claude-2.1': 'July 21st, 2025',
'claude-2.0': 'July 21st, 2025',
'claude-3-7-sonnet-latest': 'February 19th, 2026',
'claude-3-7-sonnet-20250219': 'February 19th, 2026',
};
const MODELS_TO_WARN_WITH_THINKING_ENABLED = ['claude-opus-4-6'];
class Messages extends resource_1.APIResource {
constructor() {
super(...arguments);
this.batches = new BatchesAPI.Batches(this._client);
}
create(params, options) {
// Transform deprecated output_format to output_config.format
const modifiedParams = transformOutputFormat(params);
const { betas, ...body } = modifiedParams;
if (body.model in DEPRECATED_MODELS) {
console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
}
if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED &&
body.thinking &&
body.thinking.type === 'enabled') {
console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
}
let timeout = this._client._options.timeout;
if (!body.stream && timeout == null) {
const maxNonstreamingTokens = constants_1.MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;
timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
}
// Collect helper info from tools and messages
const helperHeader = (0, stainless_helper_header_1.stainlessHelperHeader)(body.tools, body.messages);
return this._client.post('/v1/messages?beta=true', {
body,
timeout: timeout ?? 600000,
...options,
headers: (0, headers_1.buildHeaders)([
{ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
helperHeader,
options?.headers,
]),
stream: modifiedParams.stream ?? false,
});
}
/**
* Send a structured list of input messages with text and/or image content, along with an expected `output_format` and
* the response will be automatically parsed and available in the `parsed_output` property of the message.
*
* @example
* ```ts
* const message = await client.beta.messages.parse({
* model: 'claude-3-5-sonnet-20241022',
* max_tokens: 1024,
* messages: [{ role: 'user', content: 'What is 2+2?' }],
* output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'),
* });
*
* console.log(message.parsed_output?.answer); // 4
* ```
*/
parse(params, options) {
options = {
...options,
headers: (0, headers_1.buildHeaders)([
{ 'anthropic-beta': [...(params.betas ?? []), 'structured-outputs-2025-12-15'].toString() },
options?.headers,
]),
};
return this.create(params, options).then((message) => (0, beta_parser_1.parseBetaMessage)(message, params, { logger: this._client.logger ?? console }));
}
/**
* Create a Message stream
*/
stream(body, options) {
return BetaMessageStream_1.BetaMessageStream.createMessage(this, body, options);
}
/**
* Count the number of tokens in a Message.
*
* The Token Count API can be used to count the number of tokens in a Message,
* including tools, images, and documents, without creating it.
*
* Learn more about token counting in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
*
* @example
* ```ts
* const betaMessageTokensCount =
* await client.beta.messages.countTokens({
* messages: [{ content: 'string', role: 'user' }],
* model: 'claude-opus-4-6',
* });
* ```
*/
countTokens(params, options) {
// Transform deprecated output_format to output_config.format
const modifiedParams = transformOutputFormat(params);
const { betas, ...body } = modifiedParams;
return this._client.post('/v1/messages/count_tokens?beta=true', {
body,
...options,
headers: (0, headers_1.buildHeaders)([
{ 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() },
options?.headers,
]),
});
}
toolRunner(body, options) {
return new BetaToolRunner_1.BetaToolRunner(this._client, body, options);
}
}
exports.Messages = Messages;
/**
* Transform deprecated output_format to output_config.format
* Returns a modified copy of the params without mutating the original
*/
function transformOutputFormat(params) {
if (!params.output_format) {
return params;
}
if (params.output_config?.format) {
throw new error_1.AnthropicError('Both output_format and output_config.format were provided. ' +
'Please use only output_config.format (output_format is deprecated).');
}
const { output_format, ...rest } = params;
return {
...rest,
output_config: {
...params.output_config,
format: output_format,
},
};
}
var BetaToolRunner_2 = require("../../../lib/tools/BetaToolRunner.js");
Object.defineProperty(exports, "BetaToolRunner", { enumerable: true, get: function () { return BetaToolRunner_2.BetaToolRunner; } });
var ToolError_2 = require("../../../lib/tools/ToolError.js");
Object.defineProperty(exports, "ToolError", { enumerable: true, get: function () { return ToolError_2.ToolError; } });
Messages.Batches = batches_1.Batches;
Messages.BetaToolRunner = BetaToolRunner_1.BetaToolRunner;
Messages.ToolError = ToolError_1.ToolError;
//# sourceMappingURL=messages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../../src/resources/beta/messages/messages.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;AAEtF,6CAAgD;AAGhD,wDAAqD;AAErD,8DAAwE;AACxE,0DAAyD;AAEzD,qFAA6E;AAC7E,6DAIkC;AAClC,yEAAmE;AACnE,yEAI2C;AAC3C,+DAAyD;AAKzD,iEAAwC;AACxC,0CAkBmB;AAEnB,MAAM,iBAAiB,GAEnB;IACF,YAAY,EAAE,oBAAoB;IAClC,iBAAiB,EAAE,oBAAoB;IACvC,oBAAoB,EAAE,oBAAoB;IAC1C,yBAAyB,EAAE,oBAAoB;IAC/C,oBAAoB,EAAE,oBAAoB;IAC1C,0BAA0B,EAAE,iBAAiB;IAC7C,wBAAwB,EAAE,mBAAmB;IAC7C,YAAY,EAAE,iBAAiB;IAC/B,YAAY,EAAE,iBAAiB;IAC/B,0BAA0B,EAAE,qBAAqB;IACjD,4BAA4B,EAAE,qBAAqB;CACpD,CAAC;AAEF,MAAM,oCAAoC,GAAY,CAAC,iBAAiB,CAAC,CAAC;AAE1E,MAAa,QAAS,SAAQ,sBAAW;IAAzC;;QACE,YAAO,GAAuB,IAAI,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IA0KrE,CAAC;IA5IC,MAAM,CACJ,MAA2B,EAC3B,OAAwB;QAExB,6DAA6D;QAC7D,MAAM,cAAc,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;QAErD,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,cAAc,CAAC;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,EAAE,EAAE;gBAChF,OAAO,EAAE,OAAO;aACjB,CAAC;SACH,CAAC,CAAC;IACL,CAAC;IAWD,UAAU,CAAC,IAA0B,EAAE,OAAsC;QAC3E,OAAO,IAAI,+BAAc,CAAC,IAAI,CAAC,OAAoB,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IACtE,CAAC;CACF;AA3KD,4BA2KC;AAED;;;GAGG;AACH,SAAS,qBAAqB,CAA2D,MAAS;IAChG,IAAI,CAAC,MAAM,CAAC,aAAa,EAAE,CAAC;QAC1B,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,IAAI,MAAM,CAAC,aAAa,EAAE,MAAM,EAAE,CAAC;QACjC,MAAM,IAAI,sBAAc,CACtB,6DAA6D;YAC3D,qEAAqE,CACxE,CAAC;IACJ,CAAC;IAED,MAAM,EAAE,aAAa,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IAE1C,OAAO;QACL,GAAG,IAAI;QACP,aAAa,EAAE;YACb,GAAG,MAAM,CAAC,aAAa;YACvB,MAAM,EAAE,aAAa;SACtB;KACG,CAAC;AACT,CAAC;AA6vHD,uEAA8F;AAArF,gHAAA,cAAc,OAAA;AACvB,6DAAyD;AAAhD,sGAAA,SAAS,OAAA;AAElB,QAAQ,CAAC,OAAO,GAAG,iBAAO,CAAC;AAE3B,QAAQ,CAAC,cAAc,GAAG,+BAAc,CAAC;AACzC,QAAQ,CAAC,SAAS,GAAG,qBAAS,CAAC"}

View File

@@ -0,0 +1,156 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { AnthropicError } from "../../../error.mjs";
import { APIResource } from "../../../core/resource.mjs";
import { MODEL_NONSTREAMING_TOKENS } from "../../../internal/constants.mjs";
import { buildHeaders } from "../../../internal/headers.mjs";
import { stainlessHelperHeader } from "../../../lib/stainless-helper-header.mjs";
import { parseBetaMessage, } from "../../../lib/beta-parser.mjs";
import { BetaMessageStream } from "../../../lib/BetaMessageStream.mjs";
import { BetaToolRunner, } from "../../../lib/tools/BetaToolRunner.mjs";
import { ToolError } from "../../../lib/tools/ToolError.mjs";
import * as BatchesAPI from "./batches.mjs";
import { Batches, } from "./batches.mjs";
const DEPRECATED_MODELS = {
'claude-1.3': 'November 6th, 2024',
'claude-1.3-100k': 'November 6th, 2024',
'claude-instant-1.1': 'November 6th, 2024',
'claude-instant-1.1-100k': 'November 6th, 2024',
'claude-instant-1.2': 'November 6th, 2024',
'claude-3-sonnet-20240229': 'July 21st, 2025',
'claude-3-opus-20240229': 'January 5th, 2026',
'claude-2.1': 'July 21st, 2025',
'claude-2.0': 'July 21st, 2025',
'claude-3-7-sonnet-latest': 'February 19th, 2026',
'claude-3-7-sonnet-20250219': 'February 19th, 2026',
};
const MODELS_TO_WARN_WITH_THINKING_ENABLED = ['claude-opus-4-6'];
export class Messages extends APIResource {
constructor() {
super(...arguments);
this.batches = new BatchesAPI.Batches(this._client);
}
create(params, options) {
// Transform deprecated output_format to output_config.format
const modifiedParams = transformOutputFormat(params);
const { betas, ...body } = modifiedParams;
if (body.model in DEPRECATED_MODELS) {
console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
}
if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED &&
body.thinking &&
body.thinking.type === 'enabled') {
console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
}
let timeout = this._client._options.timeout;
if (!body.stream && timeout == null) {
const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;
timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
}
// Collect helper info from tools and messages
const helperHeader = stainlessHelperHeader(body.tools, body.messages);
return this._client.post('/v1/messages?beta=true', {
body,
timeout: timeout ?? 600000,
...options,
headers: buildHeaders([
{ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
helperHeader,
options?.headers,
]),
stream: modifiedParams.stream ?? false,
});
}
/**
* Send a structured list of input messages with text and/or image content, along with an expected `output_format` and
* the response will be automatically parsed and available in the `parsed_output` property of the message.
*
* @example
* ```ts
* const message = await client.beta.messages.parse({
* model: 'claude-3-5-sonnet-20241022',
* max_tokens: 1024,
* messages: [{ role: 'user', content: 'What is 2+2?' }],
* output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'),
* });
*
* console.log(message.parsed_output?.answer); // 4
* ```
*/
parse(params, options) {
options = {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(params.betas ?? []), 'structured-outputs-2025-12-15'].toString() },
options?.headers,
]),
};
return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console }));
}
/**
* Create a Message stream
*/
stream(body, options) {
return BetaMessageStream.createMessage(this, body, options);
}
/**
* Count the number of tokens in a Message.
*
* The Token Count API can be used to count the number of tokens in a Message,
* including tools, images, and documents, without creating it.
*
* Learn more about token counting in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
*
* @example
* ```ts
* const betaMessageTokensCount =
* await client.beta.messages.countTokens({
* messages: [{ content: 'string', role: 'user' }],
* model: 'claude-opus-4-6',
* });
* ```
*/
countTokens(params, options) {
// Transform deprecated output_format to output_config.format
const modifiedParams = transformOutputFormat(params);
const { betas, ...body } = modifiedParams;
return this._client.post('/v1/messages/count_tokens?beta=true', {
body,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() },
options?.headers,
]),
});
}
toolRunner(body, options) {
return new BetaToolRunner(this._client, body, options);
}
}
/**
* Transform deprecated output_format to output_config.format
* Returns a modified copy of the params without mutating the original
*/
function transformOutputFormat(params) {
if (!params.output_format) {
return params;
}
if (params.output_config?.format) {
throw new AnthropicError('Both output_format and output_config.format were provided. ' +
'Please use only output_config.format (output_format is deprecated).');
}
const { output_format, ...rest } = params;
return {
...rest,
output_config: {
...params.output_config,
format: output_format,
},
};
}
export { BetaToolRunner } from "../../../lib/tools/BetaToolRunner.mjs";
export { ToolError } from "../../../lib/tools/ToolError.mjs";
Messages.Batches = Batches;
Messages.BetaToolRunner = BetaToolRunner;
Messages.ToolError = ToolError;
//# sourceMappingURL=messages.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"messages.mjs","sourceRoot":"","sources":["../../../src/resources/beta/messages/messages.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,cAAc,EAAE;OAGlB,EAAE,WAAW,EAAE;OAEf,EAAE,yBAAyB,EAAE;OAC7B,EAAE,YAAY,EAAE;OAEhB,EAAE,qBAAqB,EAAE;OACzB,EACL,gBAAgB,GAGjB;OACM,EAAE,iBAAiB,EAAE;OACrB,EACL,cAAc,GAGf;OACM,EAAE,SAAS,EAAE;OAKb,KAAK,UAAU;OACf,EAOL,OAAO,GAWR;AAED,MAAM,iBAAiB,GAEnB;IACF,YAAY,EAAE,oBAAoB;IAClC,iBAAiB,EAAE,oBAAoB;IACvC,oBAAoB,EAAE,oBAAoB;IAC1C,yBAAyB,EAAE,oBAAoB;IAC/C,oBAAoB,EAAE,oBAAoB;IAC1C,0BAA0B,EAAE,iBAAiB;IAC7C,wBAAwB,EAAE,mBAAmB;IAC7C,YAAY,EAAE,iBAAiB;IAC/B,YAAY,EAAE,iBAAiB;IAC/B,0BAA0B,EAAE,qBAAqB;IACjD,4BAA4B,EAAE,qBAAqB;CACpD,CAAC;AAEF,MAAM,oCAAoC,GAAY,CAAC,iBAAiB,CAAC,CAAC;AAE1E,MAAM,OAAO,QAAS,SAAQ,WAAW;IAAzC;;QACE,YAAO,GAAuB,IAAI,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IA0KrE,CAAC;IA5IC,MAAM,CACJ,MAA2B,EAC3B,OAAwB;QAExB,6DAA6D;QAC7D,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