Debian Codegraph @

src/anthropic/resources/beta/messages/messages.py

raw
1 from __future__ import annotations
2
3 import warnings
4 from typing import TYPE_CHECKING, List, Type, Union, Mapping, Iterable, Optional, cast
5 from functools import partial
6 from itertools import chain
7 from typing_extensions import Literal, overload
8
9 import httpx2
10 import pydantic
11
12 from .batches import (
13 Batches,
14 AsyncBatches,
15 BatchesWithRawResponse,
16 AsyncBatchesWithRawResponse,
17 BatchesWithStreamingResponse,
18 AsyncBatchesWithStreamingResponse,
19 )
20 from ...._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
21 from ...._utils import is_given, required_args, strip_not_given
22 from ...._compat import cached_property
23 from ...._models import TypeAdapter
24 from ...._resource import SyncAPIResource, AsyncAPIResource
25 from ...._response import (
26 to_raw_response_wrapper,
27 to_streamed_response_wrapper,
28 async_to_raw_response_wrapper,
29 async_to_streamed_response_wrapper,
30 )
31 from ....lib.tools import (
32 BetaToolRunner,
33 BetaAsyncToolRunner,
34 BetaStreamingToolRunner,
35 BetaAsyncStreamingToolRunner,
36 )
37 from ...._constants import DEFAULT_TIMEOUT, MODEL_NONSTREAMING_TOKENS
38 from ...._streaming import Stream, AsyncStream
39 from ....types.beta import (
40 BetaFallbacksParam,
41 BetaDiagnosticsParam,
42 BetaThinkingConfigParam,
43 message_create_params,
44 )
45 from ...._exceptions import AnthropicError
46 from ...._base_client import (
47 merge_headers,
48 make_request_options,
49 )
50 from ....lib.streaming import BetaMessageStreamManager, BetaAsyncMessageStreamManager
51 from ...messages.messages import DEPRECATED_MODELS, MODELS_TO_WARN_WITH_THINKING_ENABLED
52 from ....types.model_param import ModelParam
53 from ....lib._parse._response import ResponseFormatT, parse_beta_response
54 from ....lib._parse._transform import transform_schema
55 from ....lib._stainless_helpers import (
56 HELPER_METHOD_STREAM as _HELPER_METHOD_STREAM,
57 STAINLESS_HELPER_METHOD_HEADER as _STAINLESS_HELPER_METHOD_HEADER,
58 STAINLESS_STREAM_HELPER_HEADER as _STAINLESS_STREAM_HELPER_HEADER,
59 helper_header as _helper_header,
60 stainless_helper_header as _stainless_helper_header,
61 )
62 from ....lib.tools._tool_params import BetaToolLike, to_tool_params as _to_tool_params
63 from ....types.beta.beta_message import BetaMessage
64 from ....lib.tools._beta_functions import (
65 BetaFunctionTool,
66 BetaRunnableTool,
67 BetaAsyncFunctionTool,
68 BetaAsyncRunnableTool,
69 BetaBuiltinFunctionTool,
70 BetaAsyncBuiltinFunctionTool,
71 )
72 from ....types.anthropic_beta_param import AnthropicBetaParam
73 from ....types.beta.beta_message_param import BetaMessageParam
74 from ....types.beta.beta_metadata_param import BetaMetadataParam
75 from ....types.beta.parsed_beta_message import ParsedBetaMessage
76 from ....types.beta.beta_fallbacks_param import BetaFallbacksParam
77 from ....types.beta.beta_text_block_param import BetaTextBlockParam
78 from ....types.beta.beta_tool_union_param import BetaToolUnionParam
79 from ....types.beta.beta_diagnostics_param import BetaDiagnosticsParam
80 from ....types.beta.beta_tool_choice_param import BetaToolChoiceParam
81 from ....types.beta.beta_output_config_param import BetaOutputConfigParam
82 from ....types.beta.beta_message_tokens_count import BetaMessageTokensCount
83 from ....types.beta.beta_thinking_config_param import BetaThinkingConfigParam
84 from ....types.beta.beta_compaction_config_param import BetaCompactionConfigParam
85 from ....types.beta.beta_json_output_format_param import BetaJSONOutputFormatParam
86 from ....types.beta.beta_raw_message_stream_event import BetaRawMessageStreamEvent
87 from ....types.beta.beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam
88 from ....types.beta.beta_context_management_config_param import BetaContextManagementConfigParam
89 from ....types.beta.beta_request_mcp_server_url_definition_param import BetaRequestMCPServerURLDefinitionParam
90
91 if TYPE_CHECKING:
92 from ...._client import Anthropic, AsyncAnthropic
93
94 __all__ = ["Messages", "AsyncMessages"]
95
96
97 class Messages(SyncAPIResource):
98 @cached_property
99 def batches(self) -> Batches:
100 return Batches(self._client)
101
102 @cached_property
103 def with_raw_response(self) -> MessagesWithRawResponse:
104 """
105 This property can be used as a prefix for any HTTP method call to return
106 the raw response object instead of the parsed content.
107
108 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
109 """
110 return MessagesWithRawResponse(self)
111
112 @cached_property
113 def with_streaming_response(self) -> MessagesWithStreamingResponse:
114 """
115 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
116
117 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
118 """
119 return MessagesWithStreamingResponse(self)
120
121 @overload
122 def create(
123 self,
124 *,
125 max_tokens: int,
126 messages: Iterable[BetaMessageParam],
127 model: ModelParam,
128 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
129 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
130 container: Optional[message_create_params.Container] | Omit = omit,
131 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
132 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
133 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
134 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
135 inference_geo: Optional[str] | Omit = omit,
136 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
137 metadata: BetaMetadataParam | Omit = omit,
138 output_config: BetaOutputConfigParam | Omit = omit,
139 service_tier: Literal["auto", "standard_only"] | Omit = omit,
140 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
141 stop_sequences: SequenceNotStr[str] | Omit = omit,
142 stream: Literal[False] | Omit = omit,
143 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
144 thinking: BetaThinkingConfigParam | Omit = omit,
145 tool_choice: BetaToolChoiceParam | Omit = omit,
146 tools: Iterable[BetaToolLike] | Omit = omit,
147 betas: List[AnthropicBetaParam] | Omit = omit,
148 user_profile_id: str | Omit = omit,
149 workspace_id: str | Omit = omit,
150 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
151 # The extra values given here take precedence over values defined on the client or passed to this method.
152 extra_headers: Headers | None = None,
153 extra_query: Query | None = None,
154 extra_body: Body | None = None,
155 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
156 ) -> BetaMessage:
157 """
158 Send a structured list of input messages with text and/or image content, and the
159 model will generate the next message in the conversation.
160
161 The Messages API can be used for either single queries or stateless multi-turn
162 conversations.
163
164 Learn more about the Messages API in our
165 [user guide](https://platform.claude.com/docs/en/get-started)
166
167 Args:
168 max_tokens: The maximum number of tokens to generate before stopping.
169
170 Note that our models may stop _before_ reaching this maximum. This parameter
171 only specifies the absolute maximum number of tokens to generate.
172
173 Set to `0` to populate the
174 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
175 without generating a response.
176
177 Different models have different maximum values for this parameter. See
178 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
179 details.
180
181 messages: Input messages.
182
183 Our models are trained to operate on alternating `user` and `assistant`
184 conversational turns. When creating a new `Message`, you specify the prior
185 conversational turns with the `messages` parameter, and the model then generates
186 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
187 in your request will be combined into a single turn.
188
189 Each input message must be an object with a `role` and `content`. You can
190 specify a single `user`-role message, or you can include multiple `user` and
191 `assistant` messages.
192
193 If the final message uses the `assistant` role, the response content will
194 continue immediately from the content in that message. This can be used to
195 constrain part of the model's response.
196
197 Example with a single `user` message:
198
199 ```json
200 [{ "role": "user", "content": "Hello, Claude" }]
201 ```
202
203 Example with multiple conversational turns:
204
205 ```json
206 [
207 { "role": "user", "content": "Hello there." },
208 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
209 { "role": "user", "content": "Can you explain LLMs in plain English?" }
210 ]
211 ```
212
213 Example with a partially-filled response from Claude:
214
215 ```json
216 [
217 {
218 "role": "user",
219 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
220 },
221 { "role": "assistant", "content": "The best answer is (" }
222 ]
223 ```
224
225 Each input message `content` may be either a single `string` or an array of
226 content blocks, where each block has a specific `type`. Using a `string` for
227 `content` is shorthand for an array of one content block of type `"text"`. The
228 following input messages are equivalent:
229
230 ```json
231 { "role": "user", "content": "Hello, Claude" }
232 ```
233
234 ```json
235 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
236 ```
237
238 See
239 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
240
241 Note that if you want to include a
242 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
243 you can use the top-level `system` parameter — there is no `"system"` role for
244 input messages in the Messages API.
245
246 There is a limit of 100,000 messages in a single request.
247
248 model: The model that will complete your prompt.
249
250 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
251 details and options.
252
253 cache_control: Top-level cache control automatically applies a cache_control marker to the last
254 cacheable block in the request.
255
256 compaction: Compact the whole conversation and return a signed `compaction` block, alone,
257 that a later request sends back first in `messages`, in place of the messages it
258 summarizes. There is no trigger and no pause flag: sending the parameter
259 compacts, and nothing is sampled after the block.
260
261 The summarization prompt is the server's own unless `instructions` are given,
262 which then replace it for this request; a value that is empty or only whitespace
263 counts as absent.
264
265 container: Container identifier for reuse across requests.
266
267 context_management: Context management configuration.
268
269 This allows you to control how Claude manages context across multiple requests,
270 such as whether to clear function results or not.
271
272 diagnostics: Request-level diagnostics. Currently carries the previous response id for
273 prompt-cache divergence reporting.
274
275 fallback_credit_token: The `fallback_credit_token` from a prior refusal's `stop_details`.
276
277 When a preceding request was refused and returned a `fallback_credit_token`,
278 pass that code here on the retry to have the retry's cache-creation tokens for
279 the prefix that was warm on the refused model billed at the cache-read rate.
280 Must be redeemed by the same organization and workspace, with the same request
281 body (optionally extended by one appended `assistant` message whose content is
282 the partial text — with any trailing whitespace stripped from the final text
283 block — and paired server-tool blocks streamed before the refusal; the
284 appended-assistant form is not available for requests with `output_format` set
285 or forced `tool_choice`), on an eligible fallback model, on the same platform,
286 and within 5 minutes of the refusal; a mismatch is a 400. A token minted
287 mid-server-tool-loop whose partial content was continuable may only be redeemed
288 with the appended-assistant form — if an exact-body retry is rejected with a 400
289 saying the token must be redeemed by continuing the partial response, retry with
290 the appended-assistant form instead.
291
292 When the appended-assistant form is used on a model that otherwise disallows
293 assistant-turn prefill, this token also authorizes that one prefill.
294
295 fallbacks: Opt-in server-side retry on one or more substitute models when the requested
296 model declines for policy reasons. Tried in order: if the first entry also
297 declines, the second is tried, and so on. The string "default" requests the
298 requested model's server-defined default fallback configuration.
299
300 inference_geo: Specifies the geographic region for inference processing. If not specified, the
301 workspace's `default_inference_geo` is used.
302
303 mcp_servers: MCP servers to be utilized in this request
304
305 metadata: An object describing metadata about the request.
306
307 output_config: Configuration options for the model's output, such as the output format.
308
309 service_tier: Determines whether to use priority capacity (if available) or standard capacity
310 for this request.
311
312 Anthropic offers different levels of service for your API requests. See
313 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
314 details.
315
316 speed: Inference speed mode. `fast` provides significantly faster output token
317 generation at premium pricing. Not all models support `fast`; invalid
318 combinations are rejected at create time.
319
320 stop_sequences: Custom text sequences that will cause the model to stop generating.
321
322 Our models will normally stop when they have naturally completed their turn,
323 which will result in a response `stop_reason` of `"end_turn"`.
324
325 If you want the model to stop generating when it encounters custom strings of
326 text, you can use the `stop_sequences` parameter. If the model encounters one of
327 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
328 and the response `stop_sequence` value will contain the matched stop sequence.
329
330 stream: Whether to incrementally stream the response using server-sent events.
331
332 See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming)
333 for details.
334
335 system: System prompt.
336
337 A system prompt is a way of providing context and instructions to Claude, such
338 as specifying a particular goal or role. See our
339 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
340
341 thinking: Configuration for enabling Claude's extended thinking.
342
343 When enabled, responses include `thinking` content blocks showing Claude's
344 thinking process before the final answer. Requires a minimum budget of 1,024
345 tokens and counts towards your `max_tokens` limit.
346
347 See
348 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
349 for details.
350
351 tool_choice: How the model should use the provided tools. The model can use a specific tool,
352 any available tool, decide by itself, or not use tools at all.
353
354 tools: Definitions of tools that the model may use.
355
356 If you include `tools` in your API request, the model may return `tool_use`
357 content blocks that represent the model's use of those tools. You can then run
358 those tools using the tool input generated by the model and then optionally
359 return results back to the model using `tool_result` content blocks.
360
361 There are two types of tools: **client tools** and **server tools**. The
362 behavior described below applies to client tools. For
363 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
364 see their individual documentation as each has its own behavior (e.g., the
365 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
366
367 Each tool definition includes:
368
369 - `name`: Name of the tool.
370 - `description`: Optional, but strongly-recommended description of the tool.
371 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
372 tool `input` shape that the model will produce in `tool_use` output content
373 blocks.
374
375 For example, if you defined `tools` as:
376
377 ```json
378 [
379 {
380 "name": "get_stock_price",
381 "description": "Get the current stock price for a given ticker symbol.",
382 "input_schema": {
383 "type": "object",
384 "properties": {
385 "ticker": {
386 "type": "string",
387 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
388 }
389 },
390 "required": ["ticker"]
391 }
392 }
393 ]
394 ```
395
396 And then asked the model "What's the S&P 500 at today?", the model might produce
397 `tool_use` content blocks in the response like this:
398
399 ```json
400 [
401 {
402 "type": "tool_use",
403 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
404 "name": "get_stock_price",
405 "input": { "ticker": "^GSPC" }
406 }
407 ]
408 ```
409
410 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
411 input, and return the following back to the model in a subsequent `user`
412 message:
413
414 ```json
415 [
416 {
417 "type": "tool_result",
418 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
419 "content": "259.75 USD"
420 }
421 ]
422 ```
423
424 Tools can be used for workflows that include running client-side tools and
425 functions, or more generally whenever you want the model to produce a particular
426 JSON structure of output.
427
428 See our
429 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
430 for more details.
431
432 betas: Optional header to specify the beta version(s) you want to use.
433
434 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
435 party other than your organization. Requires the `user-profiles` beta header.
436
437 workspace_id: Optional header to select the Workspace for this request. The value is a
438 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
439
440 Only needed for credentials that can act on more than one Workspace. A
441 credential that belongs to a specific Workspace may omit it; if sent, it must
442 match that Workspace.
443
444 extra_headers: Send extra headers
445
446 extra_query: Add additional query parameters to the request
447
448 extra_body: Add additional JSON properties to the request
449
450 timeout: Override the client-level default timeout for this request, in seconds
451 """
452 ...
453
454 @overload
455 def create(
456 self,
457 *,
458 max_tokens: int,
459 messages: Iterable[BetaMessageParam],
460 model: ModelParam,
461 stream: Literal[True],
462 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
463 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
464 container: Optional[message_create_params.Container] | Omit = omit,
465 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
466 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
467 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
468 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
469 inference_geo: Optional[str] | Omit = omit,
470 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
471 metadata: BetaMetadataParam | Omit = omit,
472 output_config: BetaOutputConfigParam | Omit = omit,
473 service_tier: Literal["auto", "standard_only"] | Omit = omit,
474 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
475 stop_sequences: SequenceNotStr[str] | Omit = omit,
476 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
477 thinking: BetaThinkingConfigParam | Omit = omit,
478 tool_choice: BetaToolChoiceParam | Omit = omit,
479 tools: Iterable[BetaToolLike] | Omit = omit,
480 betas: List[AnthropicBetaParam] | Omit = omit,
481 user_profile_id: str | Omit = omit,
482 workspace_id: str | Omit = omit,
483 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
484 # The extra values given here take precedence over values defined on the client or passed to this method.
485 extra_headers: Headers | None = None,
486 extra_query: Query | None = None,
487 extra_body: Body | None = None,
488 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
489 ) -> Stream[BetaRawMessageStreamEvent]:
490 """
491 Send a structured list of input messages with text and/or image content, and the
492 model will generate the next message in the conversation.
493
494 The Messages API can be used for either single queries or stateless multi-turn
495 conversations.
496
497 Learn more about the Messages API in our
498 [user guide](https://platform.claude.com/docs/en/get-started)
499
500 Args:
501 max_tokens: The maximum number of tokens to generate before stopping.
502
503 Note that our models may stop _before_ reaching this maximum. This parameter
504 only specifies the absolute maximum number of tokens to generate.
505
506 Set to `0` to populate the
507 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
508 without generating a response.
509
510 Different models have different maximum values for this parameter. See
511 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
512 details.
513
514 messages: Input messages.
515
516 Our models are trained to operate on alternating `user` and `assistant`
517 conversational turns. When creating a new `Message`, you specify the prior
518 conversational turns with the `messages` parameter, and the model then generates
519 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
520 in your request will be combined into a single turn.
521
522 Each input message must be an object with a `role` and `content`. You can
523 specify a single `user`-role message, or you can include multiple `user` and
524 `assistant` messages.
525
526 If the final message uses the `assistant` role, the response content will
527 continue immediately from the content in that message. This can be used to
528 constrain part of the model's response.
529
530 Example with a single `user` message:
531
532 ```json
533 [{ "role": "user", "content": "Hello, Claude" }]
534 ```
535
536 Example with multiple conversational turns:
537
538 ```json
539 [
540 { "role": "user", "content": "Hello there." },
541 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
542 { "role": "user", "content": "Can you explain LLMs in plain English?" }
543 ]
544 ```
545
546 Example with a partially-filled response from Claude:
547
548 ```json
549 [
550 {
551 "role": "user",
552 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
553 },
554 { "role": "assistant", "content": "The best answer is (" }
555 ]
556 ```
557
558 Each input message `content` may be either a single `string` or an array of
559 content blocks, where each block has a specific `type`. Using a `string` for
560 `content` is shorthand for an array of one content block of type `"text"`. The
561 following input messages are equivalent:
562
563 ```json
564 { "role": "user", "content": "Hello, Claude" }
565 ```
566
567 ```json
568 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
569 ```
570
571 See
572 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
573
574 Note that if you want to include a
575 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
576 you can use the top-level `system` parameter — there is no `"system"` role for
577 input messages in the Messages API.
578
579 There is a limit of 100,000 messages in a single request.
580
581 model: The model that will complete your prompt.
582
583 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
584 details and options.
585
586 stream: Whether to incrementally stream the response using server-sent events.
587
588 See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming)
589 for details.
590
591 cache_control: Top-level cache control automatically applies a cache_control marker to the last
592 cacheable block in the request.
593
594 compaction: Compact the whole conversation and return a signed `compaction` block, alone,
595 that a later request sends back first in `messages`, in place of the messages it
596 summarizes. There is no trigger and no pause flag: sending the parameter
597 compacts, and nothing is sampled after the block.
598
599 The summarization prompt is the server's own unless `instructions` are given,
600 which then replace it for this request; a value that is empty or only whitespace
601 counts as absent.
602
603 container: Container identifier for reuse across requests.
604
605 context_management: Context management configuration.
606
607 This allows you to control how Claude manages context across multiple requests,
608 such as whether to clear function results or not.
609
610 diagnostics: Request-level diagnostics. Currently carries the previous response id for
611 prompt-cache divergence reporting.
612
613 fallback_credit_token: The `fallback_credit_token` from a prior refusal's `stop_details`.
614
615 When a preceding request was refused and returned a `fallback_credit_token`,
616 pass that code here on the retry to have the retry's cache-creation tokens for
617 the prefix that was warm on the refused model billed at the cache-read rate.
618 Must be redeemed by the same organization and workspace, with the same request
619 body (optionally extended by one appended `assistant` message whose content is
620 the partial text — with any trailing whitespace stripped from the final text
621 block — and paired server-tool blocks streamed before the refusal; the
622 appended-assistant form is not available for requests with `output_format` set
623 or forced `tool_choice`), on an eligible fallback model, on the same platform,
624 and within 5 minutes of the refusal; a mismatch is a 400. A token minted
625 mid-server-tool-loop whose partial content was continuable may only be redeemed
626 with the appended-assistant form — if an exact-body retry is rejected with a 400
627 saying the token must be redeemed by continuing the partial response, retry with
628 the appended-assistant form instead.
629
630 When the appended-assistant form is used on a model that otherwise disallows
631 assistant-turn prefill, this token also authorizes that one prefill.
632
633 fallbacks: Opt-in server-side retry on one or more substitute models when the requested
634 model declines for policy reasons. Tried in order: if the first entry also
635 declines, the second is tried, and so on. The string "default" requests the
636 requested model's server-defined default fallback configuration.
637
638 inference_geo: Specifies the geographic region for inference processing. If not specified, the
639 workspace's `default_inference_geo` is used.
640
641 mcp_servers: MCP servers to be utilized in this request
642
643 metadata: An object describing metadata about the request.
644
645 output_config: Configuration options for the model's output, such as the output format.
646
647 service_tier: Determines whether to use priority capacity (if available) or standard capacity
648 for this request.
649
650 Anthropic offers different levels of service for your API requests. See
651 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
652 details.
653
654 speed: Inference speed mode. `fast` provides significantly faster output token
655 generation at premium pricing. Not all models support `fast`; invalid
656 combinations are rejected at create time.
657
658 stop_sequences: Custom text sequences that will cause the model to stop generating.
659
660 Our models will normally stop when they have naturally completed their turn,
661 which will result in a response `stop_reason` of `"end_turn"`.
662
663 If you want the model to stop generating when it encounters custom strings of
664 text, you can use the `stop_sequences` parameter. If the model encounters one of
665 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
666 and the response `stop_sequence` value will contain the matched stop sequence.
667
668 system: System prompt.
669
670 A system prompt is a way of providing context and instructions to Claude, such
671 as specifying a particular goal or role. See our
672 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
673
674 thinking: Configuration for enabling Claude's extended thinking.
675
676 When enabled, responses include `thinking` content blocks showing Claude's
677 thinking process before the final answer. Requires a minimum budget of 1,024
678 tokens and counts towards your `max_tokens` limit.
679
680 See
681 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
682 for details.
683
684 tool_choice: How the model should use the provided tools. The model can use a specific tool,
685 any available tool, decide by itself, or not use tools at all.
686
687 tools: Definitions of tools that the model may use.
688
689 If you include `tools` in your API request, the model may return `tool_use`
690 content blocks that represent the model's use of those tools. You can then run
691 those tools using the tool input generated by the model and then optionally
692 return results back to the model using `tool_result` content blocks.
693
694 There are two types of tools: **client tools** and **server tools**. The
695 behavior described below applies to client tools. For
696 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
697 see their individual documentation as each has its own behavior (e.g., the
698 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
699
700 Each tool definition includes:
701
702 - `name`: Name of the tool.
703 - `description`: Optional, but strongly-recommended description of the tool.
704 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
705 tool `input` shape that the model will produce in `tool_use` output content
706 blocks.
707
708 For example, if you defined `tools` as:
709
710 ```json
711 [
712 {
713 "name": "get_stock_price",
714 "description": "Get the current stock price for a given ticker symbol.",
715 "input_schema": {
716 "type": "object",
717 "properties": {
718 "ticker": {
719 "type": "string",
720 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
721 }
722 },
723 "required": ["ticker"]
724 }
725 }
726 ]
727 ```
728
729 And then asked the model "What's the S&P 500 at today?", the model might produce
730 `tool_use` content blocks in the response like this:
731
732 ```json
733 [
734 {
735 "type": "tool_use",
736 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
737 "name": "get_stock_price",
738 "input": { "ticker": "^GSPC" }
739 }
740 ]
741 ```
742
743 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
744 input, and return the following back to the model in a subsequent `user`
745 message:
746
747 ```json
748 [
749 {
750 "type": "tool_result",
751 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
752 "content": "259.75 USD"
753 }
754 ]
755 ```
756
757 Tools can be used for workflows that include running client-side tools and
758 functions, or more generally whenever you want the model to produce a particular
759 JSON structure of output.
760
761 See our
762 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
763 for more details.
764
765 betas: Optional header to specify the beta version(s) you want to use.
766
767 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
768 party other than your organization. Requires the `user-profiles` beta header.
769
770 workspace_id: Optional header to select the Workspace for this request. The value is a
771 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
772
773 Only needed for credentials that can act on more than one Workspace. A
774 credential that belongs to a specific Workspace may omit it; if sent, it must
775 match that Workspace.
776
777 extra_headers: Send extra headers
778
779 extra_query: Add additional query parameters to the request
780
781 extra_body: Add additional JSON properties to the request
782
783 timeout: Override the client-level default timeout for this request, in seconds
784 """
785 ...
786
787 @overload
788 def create(
789 self,
790 *,
791 max_tokens: int,
792 messages: Iterable[BetaMessageParam],
793 model: ModelParam,
794 stream: bool,
795 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
796 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
797 container: Optional[message_create_params.Container] | Omit = omit,
798 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
799 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
800 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
801 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
802 inference_geo: Optional[str] | Omit = omit,
803 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
804 metadata: BetaMetadataParam | Omit = omit,
805 output_config: BetaOutputConfigParam | Omit = omit,
806 service_tier: Literal["auto", "standard_only"] | Omit = omit,
807 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
808 stop_sequences: SequenceNotStr[str] | Omit = omit,
809 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
810 thinking: BetaThinkingConfigParam | Omit = omit,
811 tool_choice: BetaToolChoiceParam | Omit = omit,
812 tools: Iterable[BetaToolLike] | Omit = omit,
813 betas: List[AnthropicBetaParam] | Omit = omit,
814 user_profile_id: str | Omit = omit,
815 workspace_id: str | Omit = omit,
816 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
817 # The extra values given here take precedence over values defined on the client or passed to this method.
818 extra_headers: Headers | None = None,
819 extra_query: Query | None = None,
820 extra_body: Body | None = None,
821 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
822 ) -> BetaMessage | Stream[BetaRawMessageStreamEvent]:
823 """
824 Send a structured list of input messages with text and/or image content, and the
825 model will generate the next message in the conversation.
826
827 The Messages API can be used for either single queries or stateless multi-turn
828 conversations.
829
830 Learn more about the Messages API in our
831 [user guide](https://platform.claude.com/docs/en/get-started)
832
833 Args:
834 max_tokens: The maximum number of tokens to generate before stopping.
835
836 Note that our models may stop _before_ reaching this maximum. This parameter
837 only specifies the absolute maximum number of tokens to generate.
838
839 Set to `0` to populate the
840 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
841 without generating a response.
842
843 Different models have different maximum values for this parameter. See
844 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
845 details.
846
847 messages: Input messages.
848
849 Our models are trained to operate on alternating `user` and `assistant`
850 conversational turns. When creating a new `Message`, you specify the prior
851 conversational turns with the `messages` parameter, and the model then generates
852 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
853 in your request will be combined into a single turn.
854
855 Each input message must be an object with a `role` and `content`. You can
856 specify a single `user`-role message, or you can include multiple `user` and
857 `assistant` messages.
858
859 If the final message uses the `assistant` role, the response content will
860 continue immediately from the content in that message. This can be used to
861 constrain part of the model's response.
862
863 Example with a single `user` message:
864
865 ```json
866 [{ "role": "user", "content": "Hello, Claude" }]
867 ```
868
869 Example with multiple conversational turns:
870
871 ```json
872 [
873 { "role": "user", "content": "Hello there." },
874 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
875 { "role": "user", "content": "Can you explain LLMs in plain English?" }
876 ]
877 ```
878
879 Example with a partially-filled response from Claude:
880
881 ```json
882 [
883 {
884 "role": "user",
885 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
886 },
887 { "role": "assistant", "content": "The best answer is (" }
888 ]
889 ```
890
891 Each input message `content` may be either a single `string` or an array of
892 content blocks, where each block has a specific `type`. Using a `string` for
893 `content` is shorthand for an array of one content block of type `"text"`. The
894 following input messages are equivalent:
895
896 ```json
897 { "role": "user", "content": "Hello, Claude" }
898 ```
899
900 ```json
901 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
902 ```
903
904 See
905 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
906
907 Note that if you want to include a
908 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
909 you can use the top-level `system` parameter — there is no `"system"` role for
910 input messages in the Messages API.
911
912 There is a limit of 100,000 messages in a single request.
913
914 model: The model that will complete your prompt.
915
916 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
917 details and options.
918
919 stream: Whether to incrementally stream the response using server-sent events.
920
921 See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming)
922 for details.
923
924 cache_control: Top-level cache control automatically applies a cache_control marker to the last
925 cacheable block in the request.
926
927 compaction: Compact the whole conversation and return a signed `compaction` block, alone,
928 that a later request sends back first in `messages`, in place of the messages it
929 summarizes. There is no trigger and no pause flag: sending the parameter
930 compacts, and nothing is sampled after the block.
931
932 The summarization prompt is the server's own unless `instructions` are given,
933 which then replace it for this request; a value that is empty or only whitespace
934 counts as absent.
935
936 container: Container identifier for reuse across requests.
937
938 context_management: Context management configuration.
939
940 This allows you to control how Claude manages context across multiple requests,
941 such as whether to clear function results or not.
942
943 diagnostics: Request-level diagnostics. Currently carries the previous response id for
944 prompt-cache divergence reporting.
945
946 fallback_credit_token: The `fallback_credit_token` from a prior refusal's `stop_details`.
947
948 When a preceding request was refused and returned a `fallback_credit_token`,
949 pass that code here on the retry to have the retry's cache-creation tokens for
950 the prefix that was warm on the refused model billed at the cache-read rate.
951 Must be redeemed by the same organization and workspace, with the same request
952 body (optionally extended by one appended `assistant` message whose content is
953 the partial text — with any trailing whitespace stripped from the final text
954 block — and paired server-tool blocks streamed before the refusal; the
955 appended-assistant form is not available for requests with `output_format` set
956 or forced `tool_choice`), on an eligible fallback model, on the same platform,
957 and within 5 minutes of the refusal; a mismatch is a 400. A token minted
958 mid-server-tool-loop whose partial content was continuable may only be redeemed
959 with the appended-assistant form — if an exact-body retry is rejected with a 400
960 saying the token must be redeemed by continuing the partial response, retry with
961 the appended-assistant form instead.
962
963 When the appended-assistant form is used on a model that otherwise disallows
964 assistant-turn prefill, this token also authorizes that one prefill.
965
966 fallbacks: Opt-in server-side retry on one or more substitute models when the requested
967 model declines for policy reasons. Tried in order: if the first entry also
968 declines, the second is tried, and so on. The string "default" requests the
969 requested model's server-defined default fallback configuration.
970
971 inference_geo: Specifies the geographic region for inference processing. If not specified, the
972 workspace's `default_inference_geo` is used.
973
974 mcp_servers: MCP servers to be utilized in this request
975
976 metadata: An object describing metadata about the request.
977
978 output_config: Configuration options for the model's output, such as the output format.
979
980 service_tier: Determines whether to use priority capacity (if available) or standard capacity
981 for this request.
982
983 Anthropic offers different levels of service for your API requests. See
984 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
985 details.
986
987 speed: Inference speed mode. `fast` provides significantly faster output token
988 generation at premium pricing. Not all models support `fast`; invalid
989 combinations are rejected at create time.
990
991 stop_sequences: Custom text sequences that will cause the model to stop generating.
992
993 Our models will normally stop when they have naturally completed their turn,
994 which will result in a response `stop_reason` of `"end_turn"`.
995
996 If you want the model to stop generating when it encounters custom strings of
997 text, you can use the `stop_sequences` parameter. If the model encounters one of
998 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
999 and the response `stop_sequence` value will contain the matched stop sequence.
1000
1001 system: System prompt.
1002
1003 A system prompt is a way of providing context and instructions to Claude, such
1004 as specifying a particular goal or role. See our
1005 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
1006
1007 thinking: Configuration for enabling Claude's extended thinking.
1008
1009 When enabled, responses include `thinking` content blocks showing Claude's
1010 thinking process before the final answer. Requires a minimum budget of 1,024
1011 tokens and counts towards your `max_tokens` limit.
1012
1013 See
1014 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
1015 for details.
1016
1017 tool_choice: How the model should use the provided tools. The model can use a specific tool,
1018 any available tool, decide by itself, or not use tools at all.
1019
1020 tools: Definitions of tools that the model may use.
1021
1022 If you include `tools` in your API request, the model may return `tool_use`
1023 content blocks that represent the model's use of those tools. You can then run
1024 those tools using the tool input generated by the model and then optionally
1025 return results back to the model using `tool_result` content blocks.
1026
1027 There are two types of tools: **client tools** and **server tools**. The
1028 behavior described below applies to client tools. For
1029 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
1030 see their individual documentation as each has its own behavior (e.g., the
1031 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
1032
1033 Each tool definition includes:
1034
1035 - `name`: Name of the tool.
1036 - `description`: Optional, but strongly-recommended description of the tool.
1037 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
1038 tool `input` shape that the model will produce in `tool_use` output content
1039 blocks.
1040
1041 For example, if you defined `tools` as:
1042
1043 ```json
1044 [
1045 {
1046 "name": "get_stock_price",
1047 "description": "Get the current stock price for a given ticker symbol.",
1048 "input_schema": {
1049 "type": "object",
1050 "properties": {
1051 "ticker": {
1052 "type": "string",
1053 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
1054 }
1055 },
1056 "required": ["ticker"]
1057 }
1058 }
1059 ]
1060 ```
1061
1062 And then asked the model "What's the S&P 500 at today?", the model might produce
1063 `tool_use` content blocks in the response like this:
1064
1065 ```json
1066 [
1067 {
1068 "type": "tool_use",
1069 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
1070 "name": "get_stock_price",
1071 "input": { "ticker": "^GSPC" }
1072 }
1073 ]
1074 ```
1075
1076 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
1077 input, and return the following back to the model in a subsequent `user`
1078 message:
1079
1080 ```json
1081 [
1082 {
1083 "type": "tool_result",
1084 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
1085 "content": "259.75 USD"
1086 }
1087 ]
1088 ```
1089
1090 Tools can be used for workflows that include running client-side tools and
1091 functions, or more generally whenever you want the model to produce a particular
1092 JSON structure of output.
1093
1094 See our
1095 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
1096 for more details.
1097
1098 betas: Optional header to specify the beta version(s) you want to use.
1099
1100 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
1101 party other than your organization. Requires the `user-profiles` beta header.
1102
1103 workspace_id: Optional header to select the Workspace for this request. The value is a
1104 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
1105
1106 Only needed for credentials that can act on more than one Workspace. A
1107 credential that belongs to a specific Workspace may omit it; if sent, it must
1108 match that Workspace.
1109
1110 extra_headers: Send extra headers
1111
1112 extra_query: Add additional query parameters to the request
1113
1114 extra_body: Add additional JSON properties to the request
1115
1116 timeout: Override the client-level default timeout for this request, in seconds
1117 """
1118 ...
1119
1120 @required_args(["max_tokens", "messages", "model"], ["max_tokens", "messages", "model", "stream"])
1121 def create(
1122 self,
1123 *,
1124 max_tokens: int,
1125 messages: Iterable[BetaMessageParam],
1126 model: ModelParam,
1127 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
1128 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
1129 container: Optional[message_create_params.Container] | Omit = omit,
1130 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
1131 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
1132 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
1133 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
1134 inference_geo: Optional[str] | Omit = omit,
1135 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
1136 metadata: BetaMetadataParam | Omit = omit,
1137 output_config: BetaOutputConfigParam | Omit = omit,
1138 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1139 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
1140 stop_sequences: SequenceNotStr[str] | Omit = omit,
1141 stream: Literal[False] | Literal[True] | Omit = omit,
1142 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
1143 thinking: BetaThinkingConfigParam | Omit = omit,
1144 tool_choice: BetaToolChoiceParam | Omit = omit,
1145 tools: Iterable[BetaToolLike] | Omit = omit,
1146 betas: List[AnthropicBetaParam] | Omit = omit,
1147 user_profile_id: str | Omit = omit,
1148 workspace_id: str | Omit = omit,
1149 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1150 # The extra values given here take precedence over values defined on the client or passed to this method.
1151 extra_headers: Headers | None = None,
1152 extra_query: Query | None = None,
1153 extra_body: Body | None = None,
1154 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1155 ) -> BetaMessage | Stream[BetaRawMessageStreamEvent]:
1156 if not stream and not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT:
1157 timeout = self._client._calculate_nonstreaming_timeout(
1158 max_tokens, MODEL_NONSTREAMING_TOKENS.get(model, None)
1159 )
1160
1161 if model in DEPRECATED_MODELS:
1162 warnings.warn(
1163 f"The model '{model}' is deprecated and will reach end-of-life on {DEPRECATED_MODELS[model]}.\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.",
1164 DeprecationWarning,
1165 stacklevel=3,
1166 )
1167
1168 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
1169 warnings.warn(
1170 f"Using Claude with {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",
1171 UserWarning,
1172 stacklevel=3,
1173 )
1174
1175 tools = _to_tool_params(tools)
1176 extra_headers = merge_headers(
1177 strip_not_given(
1178 {
1179 "anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else not_given,
1180 "anthropic-user-profile-id": user_profile_id,
1181 "anthropic-workspace-id": workspace_id,
1182 }
1183 ),
1184 _stainless_helper_header(tools, messages),
1185 extra_headers or {},
1186 )
1187 return self._post(
1188 "/v1/messages?beta=true",
1189 body={
1190 "max_tokens": max_tokens,
1191 "messages": messages,
1192 "model": model,
1193 "cache_control": cache_control,
1194 "compaction": compaction,
1195 "container": container,
1196 "context_management": context_management,
1197 "diagnostics": diagnostics,
1198 "fallback_credit_token": fallback_credit_token,
1199 "fallbacks": fallbacks,
1200 "inference_geo": inference_geo,
1201 "mcp_servers": mcp_servers,
1202 "metadata": metadata,
1203 "output_config": output_config,
1204 "service_tier": service_tier,
1205 "speed": speed,
1206 "stop_sequences": stop_sequences,
1207 "stream": stream,
1208 "system": system,
1209 "thinking": thinking,
1210 "tool_choice": tool_choice,
1211 "tools": tools,
1212 },
1213 options=make_request_options(
1214 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
1215 ),
1216 cast_to=BetaMessage,
1217 stream=stream or False,
1218 stream_cls=Stream[BetaRawMessageStreamEvent],
1219 )
1220
1221 def parse(
1222 self,
1223 *,
1224 max_tokens: int,
1225 messages: Iterable[BetaMessageParam],
1226 model: ModelParam,
1227 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
1228 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
1229 container: Optional[message_create_params.Container] | Omit = omit,
1230 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
1231 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
1232 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
1233 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
1234 inference_geo: Optional[str] | Omit = omit,
1235 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
1236 metadata: BetaMetadataParam | Omit = omit,
1237 output_config: BetaOutputConfigParam | Omit = omit,
1238 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
1239 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1240 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
1241 stop_sequences: SequenceNotStr[str] | Omit = omit,
1242 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
1243 thinking: BetaThinkingConfigParam | Omit = omit,
1244 tool_choice: BetaToolChoiceParam | Omit = omit,
1245 tools: Iterable[BetaToolLike] | Omit = omit,
1246 betas: List[AnthropicBetaParam] | Omit = omit,
1247 user_profile_id: str | Omit = omit,
1248 workspace_id: str | Omit = omit,
1249 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1250 # The extra values given here take precedence over values defined on the client or passed to this method.
1251 extra_headers: Headers | None = None,
1252 extra_query: Query | None = None,
1253 extra_body: Body | None = None,
1254 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1255 ) -> ParsedBetaMessage[ResponseFormatT]:
1256 _validate_output_config_conflict(output_config, output_format)
1257
1258 if not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT:
1259 timeout = self._client._calculate_nonstreaming_timeout(
1260 max_tokens, MODEL_NONSTREAMING_TOKENS.get(model, None)
1261 )
1262
1263 if model in DEPRECATED_MODELS:
1264 warnings.warn(
1265 f"The model '{model}' is deprecated and will reach end-of-life on {DEPRECATED_MODELS[model]}.\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.",
1266 DeprecationWarning,
1267 stacklevel=3,
1268 )
1269
1270 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
1271 warnings.warn(
1272 f"Using Claude with {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",
1273 UserWarning,
1274 stacklevel=3,
1275 )
1276
1277 betas = [beta for beta in betas] if is_given(betas) else []
1278
1279 if "structured-outputs-2025-12-15" not in betas:
1280 # Ensure structured outputs beta is included for parse method
1281 betas.append("structured-outputs-2025-12-15")
1282
1283 tools = _to_tool_params(tools)
1284 extra_headers = merge_headers(
1285 _helper_header("beta.messages.parse"),
1286 strip_not_given(
1287 {
1288 "anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else not_given,
1289 "anthropic-user-profile-id": user_profile_id,
1290 "anthropic-workspace-id": workspace_id,
1291 }
1292 ),
1293 _stainless_helper_header(tools, messages),
1294 extra_headers or {},
1295 )
1296
1297 if is_given(output_format) and output_format is not None:
1298 if isinstance(output_format, Mapping):
1299 raise TypeError(
1300 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
1301 )
1302 adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format)
1303
1304 try:
1305 schema = adapted_type.json_schema()
1306 transformed_output_format = BetaJSONOutputFormatParam(
1307 schema=transform_schema(schema), type="json_schema"
1308 )
1309 except pydantic.errors.PydanticSchemaGenerationError as e:
1310 raise TypeError(
1311 (
1312 "Could not generate JSON schema for the given `output_format` type. "
1313 "Use a type that works with `pydantic.TypeAdapter`"
1314 )
1315 ) from e
1316
1317 merged_output_config = _merge_output_configs(output_config, transformed_output_format)
1318 else:
1319 merged_output_config = output_config
1320
1321 def parser(response: BetaMessage) -> ParsedBetaMessage[ResponseFormatT]:
1322 return parse_beta_response(
1323 response=response,
1324 output_format=cast(
1325 ResponseFormatT,
1326 output_format if is_given(output_format) and output_format is not None else not_given,
1327 ),
1328 )
1329
1330 return self._post(
1331 "/v1/messages?beta=true",
1332 body={
1333 "max_tokens": max_tokens,
1334 "messages": messages,
1335 "model": model,
1336 "cache_control": cache_control,
1337 "compaction": compaction,
1338 "container": container,
1339 "context_management": context_management,
1340 "diagnostics": diagnostics,
1341 "fallback_credit_token": fallback_credit_token,
1342 "fallbacks": fallbacks,
1343 "inference_geo": inference_geo,
1344 "mcp_servers": mcp_servers,
1345 "metadata": metadata,
1346 "output_config": merged_output_config,
1347 "output_format": omit,
1348 "service_tier": service_tier,
1349 "speed": speed,
1350 "stop_sequences": stop_sequences,
1351 "system": system,
1352 "thinking": thinking,
1353 "tool_choice": tool_choice,
1354 "tools": tools,
1355 },
1356 options=make_request_options(
1357 extra_headers=extra_headers,
1358 extra_query=extra_query,
1359 extra_body=extra_body,
1360 timeout=timeout,
1361 post_parser=parser,
1362 ),
1363 cast_to=cast(Type[ParsedBetaMessage[ResponseFormatT]], BetaMessage),
1364 stream=False,
1365 )
1366
1367 @overload
1368 def tool_runner(
1369 self,
1370 *,
1371 max_tokens: int,
1372 messages: Iterable[BetaMessageParam],
1373 model: ModelParam,
1374 tools: Iterable[BetaRunnableTool | BetaToolUnionParam],
1375 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
1376 container: Optional[message_create_params.Container] | Omit = omit,
1377 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
1378 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
1379 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
1380 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
1381 inference_geo: Optional[str] | Omit = omit,
1382 max_iterations: int | Omit = omit,
1383 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
1384 metadata: BetaMetadataParam | Omit = omit,
1385 output_config: BetaOutputConfigParam | Omit = omit,
1386 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
1387 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1388 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
1389 stop_sequences: SequenceNotStr[str] | Omit = omit,
1390 stream: Literal[False] | Omit = omit,
1391 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
1392 thinking: BetaThinkingConfigParam | Omit = omit,
1393 tool_choice: BetaToolChoiceParam | Omit = omit,
1394 betas: List[AnthropicBetaParam] | Omit = omit,
1395 user_profile_id: str | Omit = omit,
1396 workspace_id: str | Omit = omit,
1397 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1398 # The extra values given here take precedence over values defined on the client or passed to this method.
1399 extra_headers: Headers | None = None,
1400 extra_query: Query | None = None,
1401 extra_body: Body | None = None,
1402 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1403 ) -> BetaToolRunner[ResponseFormatT]: ...
1404
1405 @overload
1406 def tool_runner(
1407 self,
1408 *,
1409 max_tokens: int,
1410 messages: Iterable[BetaMessageParam],
1411 model: ModelParam,
1412 tools: Iterable[BetaRunnableTool | BetaToolUnionParam],
1413 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
1414 stream: Literal[True],
1415 max_iterations: int | Omit = omit,
1416 container: Optional[message_create_params.Container] | Omit = omit,
1417 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
1418 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
1419 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
1420 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
1421 inference_geo: Optional[str] | Omit = omit,
1422 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
1423 metadata: BetaMetadataParam | Omit = omit,
1424 output_config: BetaOutputConfigParam | Omit = omit,
1425 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
1426 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1427 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
1428 stop_sequences: SequenceNotStr[str] | Omit = omit,
1429 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
1430 thinking: BetaThinkingConfigParam | Omit = omit,
1431 tool_choice: BetaToolChoiceParam | Omit = omit,
1432 betas: List[AnthropicBetaParam] | Omit = omit,
1433 user_profile_id: str | Omit = omit,
1434 workspace_id: str | Omit = omit,
1435 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1436 # The extra values given here take precedence over values defined on the client or passed to this method.
1437 extra_headers: Headers | None = None,
1438 extra_query: Query | None = None,
1439 extra_body: Body | None = None,
1440 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1441 ) -> BetaStreamingToolRunner[ResponseFormatT]: ...
1442
1443 @overload
1444 def tool_runner(
1445 self,
1446 *,
1447 max_tokens: int,
1448 messages: Iterable[BetaMessageParam],
1449 model: ModelParam,
1450 tools: Iterable[BetaRunnableTool | BetaToolUnionParam],
1451 stream: bool,
1452 max_iterations: int | Omit = omit,
1453 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
1454 container: Optional[message_create_params.Container] | Omit = omit,
1455 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
1456 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
1457 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
1458 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
1459 inference_geo: Optional[str] | Omit = omit,
1460 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
1461 metadata: BetaMetadataParam | Omit = omit,
1462 output_config: BetaOutputConfigParam | Omit = omit,
1463 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
1464 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1465 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
1466 stop_sequences: SequenceNotStr[str] | Omit = omit,
1467 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
1468 thinking: BetaThinkingConfigParam | Omit = omit,
1469 tool_choice: BetaToolChoiceParam | Omit = omit,
1470 betas: List[AnthropicBetaParam] | Omit = omit,
1471 user_profile_id: str | Omit = omit,
1472 workspace_id: str | Omit = omit,
1473 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1474 # The extra values given here take precedence over values defined on the client or passed to this method.
1475 extra_headers: Headers | None = None,
1476 extra_query: Query | None = None,
1477 extra_body: Body | None = None,
1478 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1479 ) -> BetaStreamingToolRunner[ResponseFormatT] | BetaToolRunner[ResponseFormatT]: ...
1480
1481 def tool_runner(
1482 self,
1483 *,
1484 max_tokens: int,
1485 messages: Iterable[BetaMessageParam],
1486 model: ModelParam,
1487 tools: Iterable[BetaRunnableTool | BetaToolUnionParam],
1488 max_iterations: int | Omit = omit,
1489 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
1490 container: Optional[message_create_params.Container] | Omit = omit,
1491 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
1492 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
1493 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
1494 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
1495 inference_geo: Optional[str] | Omit = omit,
1496 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
1497 metadata: BetaMetadataParam | Omit = omit,
1498 output_config: BetaOutputConfigParam | Omit = omit,
1499 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
1500 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1501 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
1502 stop_sequences: SequenceNotStr[str] | Omit = omit,
1503 stream: bool | Omit = omit,
1504 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
1505 thinking: BetaThinkingConfigParam | Omit = omit,
1506 tool_choice: BetaToolChoiceParam | Omit = omit,
1507 betas: List[AnthropicBetaParam] | Omit = omit,
1508 user_profile_id: str | Omit = omit,
1509 workspace_id: str | Omit = omit,
1510 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1511 # The extra values given here take precedence over values defined on the client or passed to this method.
1512 extra_headers: Headers | None = None,
1513 extra_query: Query | None = None,
1514 extra_body: Body | None = None,
1515 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1516 ) -> BetaStreamingToolRunner[ResponseFormatT] | BetaToolRunner[ResponseFormatT]:
1517 """Create a Message stream"""
1518 _validate_output_config_conflict(output_config, output_format)
1519
1520 if model in DEPRECATED_MODELS:
1521 warnings.warn(
1522 f"The model '{model}' is deprecated and will reach end-of-life on {DEPRECATED_MODELS[model]}.\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.",
1523 DeprecationWarning,
1524 stacklevel=3,
1525 )
1526
1527 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
1528 warnings.warn(
1529 f"Using Claude with {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",
1530 UserWarning,
1531 stacklevel=3,
1532 )
1533
1534 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
1535 warnings.warn(
1536 f"Using Claude with {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",
1537 UserWarning,
1538 stacklevel=3,
1539 )
1540
1541 extra_headers = merge_headers(
1542 _helper_header("BetaToolRunner"),
1543 strip_not_given(
1544 {
1545 "anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else not_given,
1546 "anthropic-user-profile-id": user_profile_id,
1547 "anthropic-workspace-id": workspace_id,
1548 }
1549 ),
1550 _stainless_helper_header(tools, messages),
1551 extra_headers or {},
1552 )
1553
1554 runnable_tools: list[BetaRunnableTool] = []
1555 raw_tools: list[BetaToolUnionParam] = []
1556
1557 for tool in tools:
1558 if isinstance(tool, (BetaFunctionTool, BetaBuiltinFunctionTool)):
1559 runnable_tools.append(tool)
1560 else:
1561 raw_tools.append(tool)
1562
1563 params = cast(
1564 message_create_params.ParseMessageCreateParamsBase[ResponseFormatT],
1565 {
1566 "max_tokens": max_tokens,
1567 "messages": messages,
1568 "model": model,
1569 "cache_control": cache_control,
1570 "container": container,
1571 "context_management": context_management,
1572 "diagnostics": diagnostics,
1573 "fallback_credit_token": fallback_credit_token,
1574 "fallbacks": fallbacks,
1575 "inference_geo": inference_geo,
1576 "mcp_servers": mcp_servers,
1577 "metadata": metadata,
1578 "output_config": output_config,
1579 "output_format": output_format,
1580 "service_tier": service_tier,
1581 "speed": speed,
1582 "stop_sequences": stop_sequences,
1583 "system": system,
1584 "thinking": thinking,
1585 "tool_choice": tool_choice,
1586 "tools": [*[tool.to_dict() for tool in runnable_tools], *raw_tools],
1587 },
1588 )
1589
1590 if stream:
1591 return BetaStreamingToolRunner[ResponseFormatT](
1592 tools=runnable_tools,
1593 params=params,
1594 options={
1595 "extra_headers": extra_headers,
1596 "extra_query": extra_query,
1597 "extra_body": extra_body,
1598 "timeout": timeout,
1599 },
1600 client=cast("Anthropic", self._client),
1601 max_iterations=max_iterations if is_given(max_iterations) else None,
1602 )
1603 return BetaToolRunner[ResponseFormatT](
1604 tools=runnable_tools,
1605 params=params,
1606 options={
1607 "extra_headers": extra_headers,
1608 "extra_query": extra_query,
1609 "extra_body": extra_body,
1610 "timeout": timeout,
1611 },
1612 client=cast("Anthropic", self._client),
1613 max_iterations=max_iterations if is_given(max_iterations) else None,
1614 )
1615
1616 def stream(
1617 self,
1618 *,
1619 max_tokens: int,
1620 messages: Iterable[BetaMessageParam],
1621 model: ModelParam,
1622 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
1623 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
1624 container: Optional[message_create_params.Container] | Omit = omit,
1625 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
1626 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
1627 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
1628 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
1629 inference_geo: Optional[str] | Omit = omit,
1630 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
1631 metadata: BetaMetadataParam | Omit = omit,
1632 output_config: BetaOutputConfigParam | Omit = omit,
1633 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
1634 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1635 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
1636 stop_sequences: SequenceNotStr[str] | Omit = omit,
1637 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
1638 thinking: BetaThinkingConfigParam | Omit = omit,
1639 tool_choice: BetaToolChoiceParam | Omit = omit,
1640 tools: Iterable[BetaToolLike] | Omit = omit,
1641 betas: List[AnthropicBetaParam] | Omit = omit,
1642 user_profile_id: str | Omit = omit,
1643 workspace_id: str | Omit = omit,
1644 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1645 # The extra values given here take precedence over values defined on the client or passed to this method.
1646 extra_headers: Headers | None = None,
1647 extra_query: Query | None = None,
1648 extra_body: Body | None = None,
1649 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1650 ) -> BetaMessageStreamManager[ResponseFormatT]:
1651 _validate_output_config_conflict(output_config, output_format)
1652
1653 if model in DEPRECATED_MODELS:
1654 warnings.warn(
1655 f"The model '{model}' is deprecated and will reach end-of-life on {DEPRECATED_MODELS[model]}.\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.",
1656 DeprecationWarning,
1657 stacklevel=3,
1658 )
1659
1660 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
1661 warnings.warn(
1662 f"Using Claude with {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",
1663 UserWarning,
1664 stacklevel=3,
1665 )
1666
1667 """Create a Message stream"""
1668 tools = _to_tool_params(tools)
1669 extra_headers = merge_headers(
1670 {
1671 _STAINLESS_HELPER_METHOD_HEADER: _HELPER_METHOD_STREAM,
1672 _STAINLESS_STREAM_HELPER_HEADER: "beta.messages",
1673 },
1674 strip_not_given(
1675 {
1676 "anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else not_given,
1677 "anthropic-user-profile-id": user_profile_id,
1678 "anthropic-workspace-id": workspace_id,
1679 }
1680 ),
1681 _stainless_helper_header(tools, messages),
1682 extra_headers or {},
1683 )
1684
1685 transformed_output_format: BetaJSONOutputFormatParam | Omit = omit
1686
1687 if is_given(output_format) and output_format is not None:
1688 if isinstance(output_format, Mapping):
1689 raise TypeError(
1690 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
1691 )
1692 adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format)
1693
1694 try:
1695 schema = adapted_type.json_schema()
1696 transformed_output_format = BetaJSONOutputFormatParam(
1697 schema=transform_schema(schema), type="json_schema"
1698 )
1699 except pydantic.errors.PydanticSchemaGenerationError as e:
1700 raise TypeError(
1701 (
1702 "Could not generate JSON schema for the given `output_format` type. "
1703 "Use a type that works with `pydantic.TypeAdapter`"
1704 )
1705 ) from e
1706
1707 merged_output_config = _merge_output_configs(output_config, transformed_output_format)
1708
1709 make_request = partial(
1710 self._post,
1711 "/v1/messages?beta=true",
1712 body={
1713 "max_tokens": max_tokens,
1714 "messages": messages,
1715 "model": model,
1716 "cache_control": cache_control,
1717 "compaction": compaction,
1718 "metadata": metadata,
1719 "output_config": merged_output_config,
1720 "output_format": omit,
1721 "container": container,
1722 "context_management": context_management,
1723 "diagnostics": diagnostics,
1724 "fallback_credit_token": fallback_credit_token,
1725 "fallbacks": fallbacks,
1726 "inference_geo": inference_geo,
1727 "mcp_servers": mcp_servers,
1728 "service_tier": service_tier,
1729 "speed": speed,
1730 "stop_sequences": stop_sequences,
1731 "system": system,
1732 "thinking": thinking,
1733 "tools": tools,
1734 "tool_choice": tool_choice,
1735 "stream": True,
1736 },
1737 options=make_request_options(
1738 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
1739 ),
1740 cast_to=BetaMessage,
1741 stream=True,
1742 stream_cls=Stream[BetaRawMessageStreamEvent],
1743 )
1744 return BetaMessageStreamManager(
1745 make_request,
1746 output_format=cast(ResponseFormatT, output_format),
1747 )
1748
1749 def count_tokens(
1750 self,
1751 *,
1752 messages: Iterable[BetaMessageParam],
1753 model: ModelParam,
1754 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
1755 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
1756 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
1757 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
1758 output_config: BetaOutputConfigParam | Omit = omit,
1759 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
1760 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
1761 thinking: BetaThinkingConfigParam | Omit = omit,
1762 tool_choice: BetaToolChoiceParam | Omit = omit,
1763 tools: Iterable[BetaToolLike] | Omit = omit,
1764 betas: List[AnthropicBetaParam] | Omit = omit,
1765 user_profile_id: str | Omit = omit,
1766 workspace_id: str | Omit = omit,
1767 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1768 # The extra values given here take precedence over values defined on the client or passed to this method.
1769 extra_headers: Headers | None = None,
1770 extra_query: Query | None = None,
1771 extra_body: Body | None = None,
1772 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1773 ) -> BetaMessageTokensCount:
1774 """
1775 Count the number of tokens in a Message.
1776
1777 The Token Count API can be used to count the number of tokens in a Message,
1778 including tools, images, and documents, without creating it.
1779
1780 Learn more about token counting in our
1781 [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting)
1782
1783 Args:
1784 messages: Input messages.
1785
1786 Our models are trained to operate on alternating `user` and `assistant`
1787 conversational turns. When creating a new `Message`, you specify the prior
1788 conversational turns with the `messages` parameter, and the model then generates
1789 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
1790 in your request will be combined into a single turn.
1791
1792 Each input message must be an object with a `role` and `content`. You can
1793 specify a single `user`-role message, or you can include multiple `user` and
1794 `assistant` messages.
1795
1796 If the final message uses the `assistant` role, the response content will
1797 continue immediately from the content in that message. This can be used to
1798 constrain part of the model's response.
1799
1800 Example with a single `user` message:
1801
1802 ```json
1803 [{ "role": "user", "content": "Hello, Claude" }]
1804 ```
1805
1806 Example with multiple conversational turns:
1807
1808 ```json
1809 [
1810 { "role": "user", "content": "Hello there." },
1811 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
1812 { "role": "user", "content": "Can you explain LLMs in plain English?" }
1813 ]
1814 ```
1815
1816 Example with a partially-filled response from Claude:
1817
1818 ```json
1819 [
1820 {
1821 "role": "user",
1822 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
1823 },
1824 { "role": "assistant", "content": "The best answer is (" }
1825 ]
1826 ```
1827
1828 Each input message `content` may be either a single `string` or an array of
1829 content blocks, where each block has a specific `type`. Using a `string` for
1830 `content` is shorthand for an array of one content block of type `"text"`. The
1831 following input messages are equivalent:
1832
1833 ```json
1834 { "role": "user", "content": "Hello, Claude" }
1835 ```
1836
1837 ```json
1838 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
1839 ```
1840
1841 See
1842 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
1843
1844 Note that if you want to include a
1845 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
1846 you can use the top-level `system` parameter — there is no `"system"` role for
1847 input messages in the Messages API.
1848
1849 There is a limit of 100,000 messages in a single request.
1850
1851 model: The model that will complete your prompt.
1852
1853 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
1854 details and options.
1855
1856 cache_control: Top-level cache control automatically applies a cache_control marker to the last
1857 cacheable block in the request.
1858
1859 compaction: Compact the whole conversation and return a signed `compaction` block, alone,
1860 that a later request sends back first in `messages`, in place of the messages it
1861 summarizes. There is no trigger and no pause flag: sending the parameter
1862 compacts, and nothing is sampled after the block.
1863
1864 The summarization prompt is the server's own unless `instructions` are given,
1865 which then replace it for this request; a value that is empty or only whitespace
1866 counts as absent.
1867
1868 context_management: Context management configuration.
1869
1870 This allows you to control how Claude manages context across multiple requests,
1871 such as whether to clear function results or not.
1872
1873 mcp_servers: MCP servers to be utilized in this request
1874
1875 output_config: Configuration options for the model's output, such as the output format.
1876
1877 speed: Inference speed mode. `fast` provides significantly faster output token
1878 generation at premium pricing. Not all models support `fast`; invalid
1879 combinations are rejected at create time.
1880
1881 system: System prompt.
1882
1883 A system prompt is a way of providing context and instructions to Claude, such
1884 as specifying a particular goal or role. See our
1885 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
1886
1887 thinking: Configuration for enabling Claude's extended thinking.
1888
1889 When enabled, responses include `thinking` content blocks showing Claude's
1890 thinking process before the final answer. Requires a minimum budget of 1,024
1891 tokens and counts towards your `max_tokens` limit.
1892
1893 See
1894 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
1895 for details.
1896
1897 tool_choice: How the model should use the provided tools. The model can use a specific tool,
1898 any available tool, decide by itself, or not use tools at all.
1899
1900 tools: Definitions of tools that the model may use.
1901
1902 If you include `tools` in your API request, the model may return `tool_use`
1903 content blocks that represent the model's use of those tools. You can then run
1904 those tools using the tool input generated by the model and then optionally
1905 return results back to the model using `tool_result` content blocks.
1906
1907 There are two types of tools: **client tools** and **server tools**. The
1908 behavior described below applies to client tools. For
1909 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
1910 see their individual documentation as each has its own behavior (e.g., the
1911 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
1912
1913 Each tool definition includes:
1914
1915 - `name`: Name of the tool.
1916 - `description`: Optional, but strongly-recommended description of the tool.
1917 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
1918 tool `input` shape that the model will produce in `tool_use` output content
1919 blocks.
1920
1921 For example, if you defined `tools` as:
1922
1923 ```json
1924 [
1925 {
1926 "name": "get_stock_price",
1927 "description": "Get the current stock price for a given ticker symbol.",
1928 "input_schema": {
1929 "type": "object",
1930 "properties": {
1931 "ticker": {
1932 "type": "string",
1933 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
1934 }
1935 },
1936 "required": ["ticker"]
1937 }
1938 }
1939 ]
1940 ```
1941
1942 And then asked the model "What's the S&P 500 at today?", the model might produce
1943 `tool_use` content blocks in the response like this:
1944
1945 ```json
1946 [
1947 {
1948 "type": "tool_use",
1949 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
1950 "name": "get_stock_price",
1951 "input": { "ticker": "^GSPC" }
1952 }
1953 ]
1954 ```
1955
1956 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
1957 input, and return the following back to the model in a subsequent `user`
1958 message:
1959
1960 ```json
1961 [
1962 {
1963 "type": "tool_result",
1964 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
1965 "content": "259.75 USD"
1966 }
1967 ]
1968 ```
1969
1970 Tools can be used for workflows that include running client-side tools and
1971 functions, or more generally whenever you want the model to produce a particular
1972 JSON structure of output.
1973
1974 See our
1975 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
1976 for more details.
1977
1978 betas: Optional header to specify the beta version(s) you want to use.
1979
1980 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
1981 party other than your organization. Requires the `user-profiles` beta header.
1982
1983 workspace_id: Optional header to select the Workspace for this request. The value is a
1984 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
1985
1986 Only needed for credentials that can act on more than one Workspace. A
1987 credential that belongs to a specific Workspace may omit it; if sent, it must
1988 match that Workspace.
1989
1990 extra_headers: Send extra headers
1991
1992 extra_query: Add additional query parameters to the request
1993
1994 extra_body: Add additional JSON properties to the request
1995
1996 timeout: Override the client-level default timeout for this request, in seconds
1997 """
1998 tools = _to_tool_params(tools)
1999 extra_headers = {
2000 **strip_not_given(
2001 {
2002 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["token-counting-2024-11-01"]))
2003 if is_given(betas)
2004 else not_given,
2005 "anthropic-user-profile-id": user_profile_id,
2006 "anthropic-workspace-id": workspace_id,
2007 }
2008 ),
2009 **(extra_headers or {}),
2010 }
2011 extra_headers = {"anthropic-beta": "token-counting-2024-11-01", **(extra_headers or {})}
2012 return self._post(
2013 "/v1/messages/count_tokens?beta=true",
2014 body={
2015 "messages": messages,
2016 "model": model,
2017 "cache_control": cache_control,
2018 "compaction": compaction,
2019 "context_management": context_management,
2020 "mcp_servers": mcp_servers,
2021 "output_config": output_config,
2022 "speed": speed,
2023 "system": system,
2024 "thinking": thinking,
2025 "tool_choice": tool_choice,
2026 "tools": tools,
2027 },
2028 options=make_request_options(
2029 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
2030 ),
2031 cast_to=BetaMessageTokensCount,
2032 )
2033
2034
2035 class AsyncMessages(AsyncAPIResource):
2036 @cached_property
2037 def batches(self) -> AsyncBatches:
2038 return AsyncBatches(self._client)
2039
2040 @cached_property
2041 def with_raw_response(self) -> AsyncMessagesWithRawResponse:
2042 """
2043 This property can be used as a prefix for any HTTP method call to return
2044 the raw response object instead of the parsed content.
2045
2046 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
2047 """
2048 return AsyncMessagesWithRawResponse(self)
2049
2050 @cached_property
2051 def with_streaming_response(self) -> AsyncMessagesWithStreamingResponse:
2052 """
2053 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
2054
2055 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
2056 """
2057 return AsyncMessagesWithStreamingResponse(self)
2058
2059 @overload
2060 async def create(
2061 self,
2062 *,
2063 max_tokens: int,
2064 messages: Iterable[BetaMessageParam],
2065 model: ModelParam,
2066 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
2067 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
2068 container: Optional[message_create_params.Container] | Omit = omit,
2069 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
2070 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
2071 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
2072 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
2073 inference_geo: Optional[str] | Omit = omit,
2074 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
2075 metadata: BetaMetadataParam | Omit = omit,
2076 output_config: BetaOutputConfigParam | Omit = omit,
2077 service_tier: Literal["auto", "standard_only"] | Omit = omit,
2078 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
2079 stop_sequences: SequenceNotStr[str] | Omit = omit,
2080 stream: Literal[False] | Omit = omit,
2081 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
2082 thinking: BetaThinkingConfigParam | Omit = omit,
2083 tool_choice: BetaToolChoiceParam | Omit = omit,
2084 tools: Iterable[BetaToolLike] | Omit = omit,
2085 betas: List[AnthropicBetaParam] | Omit = omit,
2086 user_profile_id: str | Omit = omit,
2087 workspace_id: str | Omit = omit,
2088 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
2089 # The extra values given here take precedence over values defined on the client or passed to this method.
2090 extra_headers: Headers | None = None,
2091 extra_query: Query | None = None,
2092 extra_body: Body | None = None,
2093 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
2094 ) -> BetaMessage:
2095 """
2096 Send a structured list of input messages with text and/or image content, and the
2097 model will generate the next message in the conversation.
2098
2099 The Messages API can be used for either single queries or stateless multi-turn
2100 conversations.
2101
2102 Learn more about the Messages API in our
2103 [user guide](https://platform.claude.com/docs/en/get-started)
2104
2105 Args:
2106 max_tokens: The maximum number of tokens to generate before stopping.
2107
2108 Note that our models may stop _before_ reaching this maximum. This parameter
2109 only specifies the absolute maximum number of tokens to generate.
2110
2111 Set to `0` to populate the
2112 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
2113 without generating a response.
2114
2115 Different models have different maximum values for this parameter. See
2116 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
2117 details.
2118
2119 messages: Input messages.
2120
2121 Our models are trained to operate on alternating `user` and `assistant`
2122 conversational turns. When creating a new `Message`, you specify the prior
2123 conversational turns with the `messages` parameter, and the model then generates
2124 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
2125 in your request will be combined into a single turn.
2126
2127 Each input message must be an object with a `role` and `content`. You can
2128 specify a single `user`-role message, or you can include multiple `user` and
2129 `assistant` messages.
2130
2131 If the final message uses the `assistant` role, the response content will
2132 continue immediately from the content in that message. This can be used to
2133 constrain part of the model's response.
2134
2135 Example with a single `user` message:
2136
2137 ```json
2138 [{ "role": "user", "content": "Hello, Claude" }]
2139 ```
2140
2141 Example with multiple conversational turns:
2142
2143 ```json
2144 [
2145 { "role": "user", "content": "Hello there." },
2146 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
2147 { "role": "user", "content": "Can you explain LLMs in plain English?" }
2148 ]
2149 ```
2150
2151 Example with a partially-filled response from Claude:
2152
2153 ```json
2154 [
2155 {
2156 "role": "user",
2157 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
2158 },
2159 { "role": "assistant", "content": "The best answer is (" }
2160 ]
2161 ```
2162
2163 Each input message `content` may be either a single `string` or an array of
2164 content blocks, where each block has a specific `type`. Using a `string` for
2165 `content` is shorthand for an array of one content block of type `"text"`. The
2166 following input messages are equivalent:
2167
2168 ```json
2169 { "role": "user", "content": "Hello, Claude" }
2170 ```
2171
2172 ```json
2173 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
2174 ```
2175
2176 See
2177 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
2178
2179 Note that if you want to include a
2180 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
2181 you can use the top-level `system` parameter — there is no `"system"` role for
2182 input messages in the Messages API.
2183
2184 There is a limit of 100,000 messages in a single request.
2185
2186 model: The model that will complete your prompt.
2187
2188 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
2189 details and options.
2190
2191 cache_control: Top-level cache control automatically applies a cache_control marker to the last
2192 cacheable block in the request.
2193
2194 compaction: Compact the whole conversation and return a signed `compaction` block, alone,
2195 that a later request sends back first in `messages`, in place of the messages it
2196 summarizes. There is no trigger and no pause flag: sending the parameter
2197 compacts, and nothing is sampled after the block.
2198
2199 The summarization prompt is the server's own unless `instructions` are given,
2200 which then replace it for this request; a value that is empty or only whitespace
2201 counts as absent.
2202
2203 container: Container identifier for reuse across requests.
2204
2205 context_management: Context management configuration.
2206
2207 This allows you to control how Claude manages context across multiple requests,
2208 such as whether to clear function results or not.
2209
2210 diagnostics: Request-level diagnostics. Currently carries the previous response id for
2211 prompt-cache divergence reporting.
2212
2213 fallback_credit_token: The `fallback_credit_token` from a prior refusal's `stop_details`.
2214
2215 When a preceding request was refused and returned a `fallback_credit_token`,
2216 pass that code here on the retry to have the retry's cache-creation tokens for
2217 the prefix that was warm on the refused model billed at the cache-read rate.
2218 Must be redeemed by the same organization and workspace, with the same request
2219 body (optionally extended by one appended `assistant` message whose content is
2220 the partial text — with any trailing whitespace stripped from the final text
2221 block — and paired server-tool blocks streamed before the refusal; the
2222 appended-assistant form is not available for requests with `output_format` set
2223 or forced `tool_choice`), on an eligible fallback model, on the same platform,
2224 and within 5 minutes of the refusal; a mismatch is a 400. A token minted
2225 mid-server-tool-loop whose partial content was continuable may only be redeemed
2226 with the appended-assistant form — if an exact-body retry is rejected with a 400
2227 saying the token must be redeemed by continuing the partial response, retry with
2228 the appended-assistant form instead.
2229
2230 When the appended-assistant form is used on a model that otherwise disallows
2231 assistant-turn prefill, this token also authorizes that one prefill.
2232
2233 fallbacks: Opt-in server-side retry on one or more substitute models when the requested
2234 model declines for policy reasons. Tried in order: if the first entry also
2235 declines, the second is tried, and so on. The string "default" requests the
2236 requested model's server-defined default fallback configuration.
2237
2238 inference_geo: Specifies the geographic region for inference processing. If not specified, the
2239 workspace's `default_inference_geo` is used.
2240
2241 mcp_servers: MCP servers to be utilized in this request
2242
2243 metadata: An object describing metadata about the request.
2244
2245 output_config: Configuration options for the model's output, such as the output format.
2246
2247 service_tier: Determines whether to use priority capacity (if available) or standard capacity
2248 for this request.
2249
2250 Anthropic offers different levels of service for your API requests. See
2251 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
2252 details.
2253
2254 speed: Inference speed mode. `fast` provides significantly faster output token
2255 generation at premium pricing. Not all models support `fast`; invalid
2256 combinations are rejected at create time.
2257
2258 stop_sequences: Custom text sequences that will cause the model to stop generating.
2259
2260 Our models will normally stop when they have naturally completed their turn,
2261 which will result in a response `stop_reason` of `"end_turn"`.
2262
2263 If you want the model to stop generating when it encounters custom strings of
2264 text, you can use the `stop_sequences` parameter. If the model encounters one of
2265 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
2266 and the response `stop_sequence` value will contain the matched stop sequence.
2267
2268 stream: Whether to incrementally stream the response using server-sent events.
2269
2270 See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming)
2271 for details.
2272
2273 system: System prompt.
2274
2275 A system prompt is a way of providing context and instructions to Claude, such
2276 as specifying a particular goal or role. See our
2277 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
2278
2279 thinking: Configuration for enabling Claude's extended thinking.
2280
2281 When enabled, responses include `thinking` content blocks showing Claude's
2282 thinking process before the final answer. Requires a minimum budget of 1,024
2283 tokens and counts towards your `max_tokens` limit.
2284
2285 See
2286 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
2287 for details.
2288
2289 tool_choice: How the model should use the provided tools. The model can use a specific tool,
2290 any available tool, decide by itself, or not use tools at all.
2291
2292 tools: Definitions of tools that the model may use.
2293
2294 If you include `tools` in your API request, the model may return `tool_use`
2295 content blocks that represent the model's use of those tools. You can then run
2296 those tools using the tool input generated by the model and then optionally
2297 return results back to the model using `tool_result` content blocks.
2298
2299 There are two types of tools: **client tools** and **server tools**. The
2300 behavior described below applies to client tools. For
2301 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
2302 see their individual documentation as each has its own behavior (e.g., the
2303 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
2304
2305 Each tool definition includes:
2306
2307 - `name`: Name of the tool.
2308 - `description`: Optional, but strongly-recommended description of the tool.
2309 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
2310 tool `input` shape that the model will produce in `tool_use` output content
2311 blocks.
2312
2313 For example, if you defined `tools` as:
2314
2315 ```json
2316 [
2317 {
2318 "name": "get_stock_price",
2319 "description": "Get the current stock price for a given ticker symbol.",
2320 "input_schema": {
2321 "type": "object",
2322 "properties": {
2323 "ticker": {
2324 "type": "string",
2325 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
2326 }
2327 },
2328 "required": ["ticker"]
2329 }
2330 }
2331 ]
2332 ```
2333
2334 And then asked the model "What's the S&P 500 at today?", the model might produce
2335 `tool_use` content blocks in the response like this:
2336
2337 ```json
2338 [
2339 {
2340 "type": "tool_use",
2341 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2342 "name": "get_stock_price",
2343 "input": { "ticker": "^GSPC" }
2344 }
2345 ]
2346 ```
2347
2348 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
2349 input, and return the following back to the model in a subsequent `user`
2350 message:
2351
2352 ```json
2353 [
2354 {
2355 "type": "tool_result",
2356 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2357 "content": "259.75 USD"
2358 }
2359 ]
2360 ```
2361
2362 Tools can be used for workflows that include running client-side tools and
2363 functions, or more generally whenever you want the model to produce a particular
2364 JSON structure of output.
2365
2366 See our
2367 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
2368 for more details.
2369
2370 betas: Optional header to specify the beta version(s) you want to use.
2371
2372 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
2373 party other than your organization. Requires the `user-profiles` beta header.
2374
2375 workspace_id: Optional header to select the Workspace for this request. The value is a
2376 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
2377
2378 Only needed for credentials that can act on more than one Workspace. A
2379 credential that belongs to a specific Workspace may omit it; if sent, it must
2380 match that Workspace.
2381
2382 extra_headers: Send extra headers
2383
2384 extra_query: Add additional query parameters to the request
2385
2386 extra_body: Add additional JSON properties to the request
2387
2388 timeout: Override the client-level default timeout for this request, in seconds
2389 """
2390 ...
2391
2392 @overload
2393 async def create(
2394 self,
2395 *,
2396 max_tokens: int,
2397 messages: Iterable[BetaMessageParam],
2398 model: ModelParam,
2399 stream: Literal[True],
2400 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
2401 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
2402 container: Optional[message_create_params.Container] | Omit = omit,
2403 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
2404 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
2405 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
2406 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
2407 inference_geo: Optional[str] | Omit = omit,
2408 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
2409 metadata: BetaMetadataParam | Omit = omit,
2410 output_config: BetaOutputConfigParam | Omit = omit,
2411 service_tier: Literal["auto", "standard_only"] | Omit = omit,
2412 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
2413 stop_sequences: SequenceNotStr[str] | Omit = omit,
2414 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
2415 thinking: BetaThinkingConfigParam | Omit = omit,
2416 tool_choice: BetaToolChoiceParam | Omit = omit,
2417 tools: Iterable[BetaToolLike] | Omit = omit,
2418 betas: List[AnthropicBetaParam] | Omit = omit,
2419 user_profile_id: str | Omit = omit,
2420 workspace_id: str | Omit = omit,
2421 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
2422 # The extra values given here take precedence over values defined on the client or passed to this method.
2423 extra_headers: Headers | None = None,
2424 extra_query: Query | None = None,
2425 extra_body: Body | None = None,
2426 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
2427 ) -> AsyncStream[BetaRawMessageStreamEvent]:
2428 """
2429 Send a structured list of input messages with text and/or image content, and the
2430 model will generate the next message in the conversation.
2431
2432 The Messages API can be used for either single queries or stateless multi-turn
2433 conversations.
2434
2435 Learn more about the Messages API in our
2436 [user guide](https://platform.claude.com/docs/en/get-started)
2437
2438 Args:
2439 max_tokens: The maximum number of tokens to generate before stopping.
2440
2441 Note that our models may stop _before_ reaching this maximum. This parameter
2442 only specifies the absolute maximum number of tokens to generate.
2443
2444 Set to `0` to populate the
2445 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
2446 without generating a response.
2447
2448 Different models have different maximum values for this parameter. See
2449 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
2450 details.
2451
2452 messages: Input messages.
2453
2454 Our models are trained to operate on alternating `user` and `assistant`
2455 conversational turns. When creating a new `Message`, you specify the prior
2456 conversational turns with the `messages` parameter, and the model then generates
2457 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
2458 in your request will be combined into a single turn.
2459
2460 Each input message must be an object with a `role` and `content`. You can
2461 specify a single `user`-role message, or you can include multiple `user` and
2462 `assistant` messages.
2463
2464 If the final message uses the `assistant` role, the response content will
2465 continue immediately from the content in that message. This can be used to
2466 constrain part of the model's response.
2467
2468 Example with a single `user` message:
2469
2470 ```json
2471 [{ "role": "user", "content": "Hello, Claude" }]
2472 ```
2473
2474 Example with multiple conversational turns:
2475
2476 ```json
2477 [
2478 { "role": "user", "content": "Hello there." },
2479 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
2480 { "role": "user", "content": "Can you explain LLMs in plain English?" }
2481 ]
2482 ```
2483
2484 Example with a partially-filled response from Claude:
2485
2486 ```json
2487 [
2488 {
2489 "role": "user",
2490 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
2491 },
2492 { "role": "assistant", "content": "The best answer is (" }
2493 ]
2494 ```
2495
2496 Each input message `content` may be either a single `string` or an array of
2497 content blocks, where each block has a specific `type`. Using a `string` for
2498 `content` is shorthand for an array of one content block of type `"text"`. The
2499 following input messages are equivalent:
2500
2501 ```json
2502 { "role": "user", "content": "Hello, Claude" }
2503 ```
2504
2505 ```json
2506 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
2507 ```
2508
2509 See
2510 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
2511
2512 Note that if you want to include a
2513 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
2514 you can use the top-level `system` parameter — there is no `"system"` role for
2515 input messages in the Messages API.
2516
2517 There is a limit of 100,000 messages in a single request.
2518
2519 model: The model that will complete your prompt.
2520
2521 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
2522 details and options.
2523
2524 stream: Whether to incrementally stream the response using server-sent events.
2525
2526 See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming)
2527 for details.
2528
2529 cache_control: Top-level cache control automatically applies a cache_control marker to the last
2530 cacheable block in the request.
2531
2532 compaction: Compact the whole conversation and return a signed `compaction` block, alone,
2533 that a later request sends back first in `messages`, in place of the messages it
2534 summarizes. There is no trigger and no pause flag: sending the parameter
2535 compacts, and nothing is sampled after the block.
2536
2537 The summarization prompt is the server's own unless `instructions` are given,
2538 which then replace it for this request; a value that is empty or only whitespace
2539 counts as absent.
2540
2541 container: Container identifier for reuse across requests.
2542
2543 context_management: Context management configuration.
2544
2545 This allows you to control how Claude manages context across multiple requests,
2546 such as whether to clear function results or not.
2547
2548 diagnostics: Request-level diagnostics. Currently carries the previous response id for
2549 prompt-cache divergence reporting.
2550
2551 fallback_credit_token: The `fallback_credit_token` from a prior refusal's `stop_details`.
2552
2553 When a preceding request was refused and returned a `fallback_credit_token`,
2554 pass that code here on the retry to have the retry's cache-creation tokens for
2555 the prefix that was warm on the refused model billed at the cache-read rate.
2556 Must be redeemed by the same organization and workspace, with the same request
2557 body (optionally extended by one appended `assistant` message whose content is
2558 the partial text — with any trailing whitespace stripped from the final text
2559 block — and paired server-tool blocks streamed before the refusal; the
2560 appended-assistant form is not available for requests with `output_format` set
2561 or forced `tool_choice`), on an eligible fallback model, on the same platform,
2562 and within 5 minutes of the refusal; a mismatch is a 400. A token minted
2563 mid-server-tool-loop whose partial content was continuable may only be redeemed
2564 with the appended-assistant form — if an exact-body retry is rejected with a 400
2565 saying the token must be redeemed by continuing the partial response, retry with
2566 the appended-assistant form instead.
2567
2568 When the appended-assistant form is used on a model that otherwise disallows
2569 assistant-turn prefill, this token also authorizes that one prefill.
2570
2571 fallbacks: Opt-in server-side retry on one or more substitute models when the requested
2572 model declines for policy reasons. Tried in order: if the first entry also
2573 declines, the second is tried, and so on. The string "default" requests the
2574 requested model's server-defined default fallback configuration.
2575
2576 inference_geo: Specifies the geographic region for inference processing. If not specified, the
2577 workspace's `default_inference_geo` is used.
2578
2579 mcp_servers: MCP servers to be utilized in this request
2580
2581 metadata: An object describing metadata about the request.
2582
2583 output_config: Configuration options for the model's output, such as the output format.
2584
2585 service_tier: Determines whether to use priority capacity (if available) or standard capacity
2586 for this request.
2587
2588 Anthropic offers different levels of service for your API requests. See
2589 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
2590 details.
2591
2592 speed: Inference speed mode. `fast` provides significantly faster output token
2593 generation at premium pricing. Not all models support `fast`; invalid
2594 combinations are rejected at create time.
2595
2596 stop_sequences: Custom text sequences that will cause the model to stop generating.
2597
2598 Our models will normally stop when they have naturally completed their turn,
2599 which will result in a response `stop_reason` of `"end_turn"`.
2600
2601 If you want the model to stop generating when it encounters custom strings of
2602 text, you can use the `stop_sequences` parameter. If the model encounters one of
2603 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
2604 and the response `stop_sequence` value will contain the matched stop sequence.
2605
2606 system: System prompt.
2607
2608 A system prompt is a way of providing context and instructions to Claude, such
2609 as specifying a particular goal or role. See our
2610 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
2611
2612 thinking: Configuration for enabling Claude's extended thinking.
2613
2614 When enabled, responses include `thinking` content blocks showing Claude's
2615 thinking process before the final answer. Requires a minimum budget of 1,024
2616 tokens and counts towards your `max_tokens` limit.
2617
2618 See
2619 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
2620 for details.
2621
2622 tool_choice: How the model should use the provided tools. The model can use a specific tool,
2623 any available tool, decide by itself, or not use tools at all.
2624
2625 tools: Definitions of tools that the model may use.
2626
2627 If you include `tools` in your API request, the model may return `tool_use`
2628 content blocks that represent the model's use of those tools. You can then run
2629 those tools using the tool input generated by the model and then optionally
2630 return results back to the model using `tool_result` content blocks.
2631
2632 There are two types of tools: **client tools** and **server tools**. The
2633 behavior described below applies to client tools. For
2634 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
2635 see their individual documentation as each has its own behavior (e.g., the
2636 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
2637
2638 Each tool definition includes:
2639
2640 - `name`: Name of the tool.
2641 - `description`: Optional, but strongly-recommended description of the tool.
2642 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
2643 tool `input` shape that the model will produce in `tool_use` output content
2644 blocks.
2645
2646 For example, if you defined `tools` as:
2647
2648 ```json
2649 [
2650 {
2651 "name": "get_stock_price",
2652 "description": "Get the current stock price for a given ticker symbol.",
2653 "input_schema": {
2654 "type": "object",
2655 "properties": {
2656 "ticker": {
2657 "type": "string",
2658 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
2659 }
2660 },
2661 "required": ["ticker"]
2662 }
2663 }
2664 ]
2665 ```
2666
2667 And then asked the model "What's the S&P 500 at today?", the model might produce
2668 `tool_use` content blocks in the response like this:
2669
2670 ```json
2671 [
2672 {
2673 "type": "tool_use",
2674 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2675 "name": "get_stock_price",
2676 "input": { "ticker": "^GSPC" }
2677 }
2678 ]
2679 ```
2680
2681 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
2682 input, and return the following back to the model in a subsequent `user`
2683 message:
2684
2685 ```json
2686 [
2687 {
2688 "type": "tool_result",
2689 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2690 "content": "259.75 USD"
2691 }
2692 ]
2693 ```
2694
2695 Tools can be used for workflows that include running client-side tools and
2696 functions, or more generally whenever you want the model to produce a particular
2697 JSON structure of output.
2698
2699 See our
2700 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
2701 for more details.
2702
2703 betas: Optional header to specify the beta version(s) you want to use.
2704
2705 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
2706 party other than your organization. Requires the `user-profiles` beta header.
2707
2708 workspace_id: Optional header to select the Workspace for this request. The value is a
2709 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
2710
2711 Only needed for credentials that can act on more than one Workspace. A
2712 credential that belongs to a specific Workspace may omit it; if sent, it must
2713 match that Workspace.
2714
2715 extra_headers: Send extra headers
2716
2717 extra_query: Add additional query parameters to the request
2718
2719 extra_body: Add additional JSON properties to the request
2720
2721 timeout: Override the client-level default timeout for this request, in seconds
2722 """
2723 ...
2724
2725 @overload
2726 async def create(
2727 self,
2728 *,
2729 max_tokens: int,
2730 messages: Iterable[BetaMessageParam],
2731 model: ModelParam,
2732 stream: bool,
2733 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
2734 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
2735 container: Optional[message_create_params.Container] | Omit = omit,
2736 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
2737 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
2738 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
2739 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
2740 inference_geo: Optional[str] | Omit = omit,
2741 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
2742 metadata: BetaMetadataParam | Omit = omit,
2743 output_config: BetaOutputConfigParam | Omit = omit,
2744 service_tier: Literal["auto", "standard_only"] | Omit = omit,
2745 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
2746 stop_sequences: SequenceNotStr[str] | Omit = omit,
2747 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
2748 thinking: BetaThinkingConfigParam | Omit = omit,
2749 tool_choice: BetaToolChoiceParam | Omit = omit,
2750 tools: Iterable[BetaToolLike] | Omit = omit,
2751 betas: List[AnthropicBetaParam] | Omit = omit,
2752 user_profile_id: str | Omit = omit,
2753 workspace_id: str | Omit = omit,
2754 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
2755 # The extra values given here take precedence over values defined on the client or passed to this method.
2756 extra_headers: Headers | None = None,
2757 extra_query: Query | None = None,
2758 extra_body: Body | None = None,
2759 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
2760 ) -> BetaMessage | AsyncStream[BetaRawMessageStreamEvent]:
2761 """
2762 Send a structured list of input messages with text and/or image content, and the
2763 model will generate the next message in the conversation.
2764
2765 The Messages API can be used for either single queries or stateless multi-turn
2766 conversations.
2767
2768 Learn more about the Messages API in our
2769 [user guide](https://platform.claude.com/docs/en/get-started)
2770
2771 Args:
2772 max_tokens: The maximum number of tokens to generate before stopping.
2773
2774 Note that our models may stop _before_ reaching this maximum. This parameter
2775 only specifies the absolute maximum number of tokens to generate.
2776
2777 Set to `0` to populate the
2778 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
2779 without generating a response.
2780
2781 Different models have different maximum values for this parameter. See
2782 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
2783 details.
2784
2785 messages: Input messages.
2786
2787 Our models are trained to operate on alternating `user` and `assistant`
2788 conversational turns. When creating a new `Message`, you specify the prior
2789 conversational turns with the `messages` parameter, and the model then generates
2790 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
2791 in your request will be combined into a single turn.
2792
2793 Each input message must be an object with a `role` and `content`. You can
2794 specify a single `user`-role message, or you can include multiple `user` and
2795 `assistant` messages.
2796
2797 If the final message uses the `assistant` role, the response content will
2798 continue immediately from the content in that message. This can be used to
2799 constrain part of the model's response.
2800
2801 Example with a single `user` message:
2802
2803 ```json
2804 [{ "role": "user", "content": "Hello, Claude" }]
2805 ```
2806
2807 Example with multiple conversational turns:
2808
2809 ```json
2810 [
2811 { "role": "user", "content": "Hello there." },
2812 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
2813 { "role": "user", "content": "Can you explain LLMs in plain English?" }
2814 ]
2815 ```
2816
2817 Example with a partially-filled response from Claude:
2818
2819 ```json
2820 [
2821 {
2822 "role": "user",
2823 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
2824 },
2825 { "role": "assistant", "content": "The best answer is (" }
2826 ]
2827 ```
2828
2829 Each input message `content` may be either a single `string` or an array of
2830 content blocks, where each block has a specific `type`. Using a `string` for
2831 `content` is shorthand for an array of one content block of type `"text"`. The
2832 following input messages are equivalent:
2833
2834 ```json
2835 { "role": "user", "content": "Hello, Claude" }
2836 ```
2837
2838 ```json
2839 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
2840 ```
2841
2842 See
2843 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
2844
2845 Note that if you want to include a
2846 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
2847 you can use the top-level `system` parameter — there is no `"system"` role for
2848 input messages in the Messages API.
2849
2850 There is a limit of 100,000 messages in a single request.
2851
2852 model: The model that will complete your prompt.
2853
2854 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
2855 details and options.
2856
2857 stream: Whether to incrementally stream the response using server-sent events.
2858
2859 See [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming)
2860 for details.
2861
2862 cache_control: Top-level cache control automatically applies a cache_control marker to the last
2863 cacheable block in the request.
2864
2865 compaction: Compact the whole conversation and return a signed `compaction` block, alone,
2866 that a later request sends back first in `messages`, in place of the messages it
2867 summarizes. There is no trigger and no pause flag: sending the parameter
2868 compacts, and nothing is sampled after the block.
2869
2870 The summarization prompt is the server's own unless `instructions` are given,
2871 which then replace it for this request; a value that is empty or only whitespace
2872 counts as absent.
2873
2874 container: Container identifier for reuse across requests.
2875
2876 context_management: Context management configuration.
2877
2878 This allows you to control how Claude manages context across multiple requests,
2879 such as whether to clear function results or not.
2880
2881 diagnostics: Request-level diagnostics. Currently carries the previous response id for
2882 prompt-cache divergence reporting.
2883
2884 fallback_credit_token: The `fallback_credit_token` from a prior refusal's `stop_details`.
2885
2886 When a preceding request was refused and returned a `fallback_credit_token`,
2887 pass that code here on the retry to have the retry's cache-creation tokens for
2888 the prefix that was warm on the refused model billed at the cache-read rate.
2889 Must be redeemed by the same organization and workspace, with the same request
2890 body (optionally extended by one appended `assistant` message whose content is
2891 the partial text — with any trailing whitespace stripped from the final text
2892 block — and paired server-tool blocks streamed before the refusal; the
2893 appended-assistant form is not available for requests with `output_format` set
2894 or forced `tool_choice`), on an eligible fallback model, on the same platform,
2895 and within 5 minutes of the refusal; a mismatch is a 400. A token minted
2896 mid-server-tool-loop whose partial content was continuable may only be redeemed
2897 with the appended-assistant form — if an exact-body retry is rejected with a 400
2898 saying the token must be redeemed by continuing the partial response, retry with
2899 the appended-assistant form instead.
2900
2901 When the appended-assistant form is used on a model that otherwise disallows
2902 assistant-turn prefill, this token also authorizes that one prefill.
2903
2904 fallbacks: Opt-in server-side retry on one or more substitute models when the requested
2905 model declines for policy reasons. Tried in order: if the first entry also
2906 declines, the second is tried, and so on. The string "default" requests the
2907 requested model's server-defined default fallback configuration.
2908
2909 inference_geo: Specifies the geographic region for inference processing. If not specified, the
2910 workspace's `default_inference_geo` is used.
2911
2912 mcp_servers: MCP servers to be utilized in this request
2913
2914 metadata: An object describing metadata about the request.
2915
2916 output_config: Configuration options for the model's output, such as the output format.
2917
2918 service_tier: Determines whether to use priority capacity (if available) or standard capacity
2919 for this request.
2920
2921 Anthropic offers different levels of service for your API requests. See
2922 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
2923 details.
2924
2925 speed: Inference speed mode. `fast` provides significantly faster output token
2926 generation at premium pricing. Not all models support `fast`; invalid
2927 combinations are rejected at create time.
2928
2929 stop_sequences: Custom text sequences that will cause the model to stop generating.
2930
2931 Our models will normally stop when they have naturally completed their turn,
2932 which will result in a response `stop_reason` of `"end_turn"`.
2933
2934 If you want the model to stop generating when it encounters custom strings of
2935 text, you can use the `stop_sequences` parameter. If the model encounters one of
2936 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
2937 and the response `stop_sequence` value will contain the matched stop sequence.
2938
2939 system: System prompt.
2940
2941 A system prompt is a way of providing context and instructions to Claude, such
2942 as specifying a particular goal or role. See our
2943 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
2944
2945 thinking: Configuration for enabling Claude's extended thinking.
2946
2947 When enabled, responses include `thinking` content blocks showing Claude's
2948 thinking process before the final answer. Requires a minimum budget of 1,024
2949 tokens and counts towards your `max_tokens` limit.
2950
2951 See
2952 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
2953 for details.
2954
2955 tool_choice: How the model should use the provided tools. The model can use a specific tool,
2956 any available tool, decide by itself, or not use tools at all.
2957
2958 tools: Definitions of tools that the model may use.
2959
2960 If you include `tools` in your API request, the model may return `tool_use`
2961 content blocks that represent the model's use of those tools. You can then run
2962 those tools using the tool input generated by the model and then optionally
2963 return results back to the model using `tool_result` content blocks.
2964
2965 There are two types of tools: **client tools** and **server tools**. The
2966 behavior described below applies to client tools. For
2967 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
2968 see their individual documentation as each has its own behavior (e.g., the
2969 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
2970
2971 Each tool definition includes:
2972
2973 - `name`: Name of the tool.
2974 - `description`: Optional, but strongly-recommended description of the tool.
2975 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
2976 tool `input` shape that the model will produce in `tool_use` output content
2977 blocks.
2978
2979 For example, if you defined `tools` as:
2980
2981 ```json
2982 [
2983 {
2984 "name": "get_stock_price",
2985 "description": "Get the current stock price for a given ticker symbol.",
2986 "input_schema": {
2987 "type": "object",
2988 "properties": {
2989 "ticker": {
2990 "type": "string",
2991 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
2992 }
2993 },
2994 "required": ["ticker"]
2995 }
2996 }
2997 ]
2998 ```
2999
3000 And then asked the model "What's the S&P 500 at today?", the model might produce
3001 `tool_use` content blocks in the response like this:
3002
3003 ```json
3004 [
3005 {
3006 "type": "tool_use",
3007 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
3008 "name": "get_stock_price",
3009 "input": { "ticker": "^GSPC" }
3010 }
3011 ]
3012 ```
3013
3014 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
3015 input, and return the following back to the model in a subsequent `user`
3016 message:
3017
3018 ```json
3019 [
3020 {
3021 "type": "tool_result",
3022 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
3023 "content": "259.75 USD"
3024 }
3025 ]
3026 ```
3027
3028 Tools can be used for workflows that include running client-side tools and
3029 functions, or more generally whenever you want the model to produce a particular
3030 JSON structure of output.
3031
3032 See our
3033 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
3034 for more details.
3035
3036 betas: Optional header to specify the beta version(s) you want to use.
3037
3038 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
3039 party other than your organization. Requires the `user-profiles` beta header.
3040
3041 workspace_id: Optional header to select the Workspace for this request. The value is a
3042 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
3043
3044 Only needed for credentials that can act on more than one Workspace. A
3045 credential that belongs to a specific Workspace may omit it; if sent, it must
3046 match that Workspace.
3047
3048 extra_headers: Send extra headers
3049
3050 extra_query: Add additional query parameters to the request
3051
3052 extra_body: Add additional JSON properties to the request
3053
3054 timeout: Override the client-level default timeout for this request, in seconds
3055 """
3056 ...
3057
3058 @required_args(["max_tokens", "messages", "model"], ["max_tokens", "messages", "model", "stream"])
3059 async def create(
3060 self,
3061 *,
3062 max_tokens: int,
3063 messages: Iterable[BetaMessageParam],
3064 model: ModelParam,
3065 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
3066 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
3067 container: Optional[message_create_params.Container] | Omit = omit,
3068 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
3069 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
3070 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
3071 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
3072 inference_geo: Optional[str] | Omit = omit,
3073 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
3074 metadata: BetaMetadataParam | Omit = omit,
3075 output_config: BetaOutputConfigParam | Omit = omit,
3076 service_tier: Literal["auto", "standard_only"] | Omit = omit,
3077 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
3078 stop_sequences: SequenceNotStr[str] | Omit = omit,
3079 stream: Literal[False] | Literal[True] | Omit = omit,
3080 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
3081 thinking: BetaThinkingConfigParam | Omit = omit,
3082 tool_choice: BetaToolChoiceParam | Omit = omit,
3083 tools: Iterable[BetaToolLike] | Omit = omit,
3084 betas: List[AnthropicBetaParam] | Omit = omit,
3085 user_profile_id: str | Omit = omit,
3086 workspace_id: str | Omit = omit,
3087 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
3088 # The extra values given here take precedence over values defined on the client or passed to this method.
3089 extra_headers: Headers | None = None,
3090 extra_query: Query | None = None,
3091 extra_body: Body | None = None,
3092 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
3093 ) -> BetaMessage | AsyncStream[BetaRawMessageStreamEvent]:
3094 if not stream and not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT:
3095 timeout = self._client._calculate_nonstreaming_timeout(
3096 max_tokens, MODEL_NONSTREAMING_TOKENS.get(model, None)
3097 )
3098
3099 if model in DEPRECATED_MODELS:
3100 warnings.warn(
3101 f"The model '{model}' is deprecated and will reach end-of-life on {DEPRECATED_MODELS[model]}.\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.",
3102 DeprecationWarning,
3103 stacklevel=3,
3104 )
3105
3106 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
3107 warnings.warn(
3108 f"Using Claude with {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",
3109 UserWarning,
3110 stacklevel=3,
3111 )
3112
3113 tools = _to_tool_params(tools)
3114 extra_headers = merge_headers(
3115 strip_not_given(
3116 {
3117 "anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else not_given,
3118 "anthropic-user-profile-id": user_profile_id,
3119 "anthropic-workspace-id": workspace_id,
3120 }
3121 ),
3122 _stainless_helper_header(tools, messages),
3123 extra_headers or {},
3124 )
3125 return await self._post(
3126 "/v1/messages?beta=true",
3127 body={
3128 "max_tokens": max_tokens,
3129 "messages": messages,
3130 "model": model,
3131 "cache_control": cache_control,
3132 "compaction": compaction,
3133 "container": container,
3134 "context_management": context_management,
3135 "diagnostics": diagnostics,
3136 "fallback_credit_token": fallback_credit_token,
3137 "fallbacks": fallbacks,
3138 "inference_geo": inference_geo,
3139 "mcp_servers": mcp_servers,
3140 "metadata": metadata,
3141 "output_config": output_config,
3142 "service_tier": service_tier,
3143 "speed": speed,
3144 "stop_sequences": stop_sequences,
3145 "stream": stream,
3146 "system": system,
3147 "thinking": thinking,
3148 "tool_choice": tool_choice,
3149 "tools": tools,
3150 },
3151 options=make_request_options(
3152 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
3153 ),
3154 cast_to=BetaMessage,
3155 stream=stream or False,
3156 stream_cls=AsyncStream[BetaRawMessageStreamEvent],
3157 )
3158
3159 async def parse(
3160 self,
3161 *,
3162 max_tokens: int,
3163 messages: Iterable[BetaMessageParam],
3164 model: ModelParam,
3165 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
3166 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
3167 container: Optional[message_create_params.Container] | Omit = omit,
3168 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
3169 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
3170 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
3171 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
3172 inference_geo: Optional[str] | Omit = omit,
3173 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
3174 metadata: BetaMetadataParam | Omit = omit,
3175 output_config: BetaOutputConfigParam | Omit = omit,
3176 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
3177 service_tier: Literal["auto", "standard_only"] | Omit = omit,
3178 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
3179 stop_sequences: SequenceNotStr[str] | Omit = omit,
3180 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
3181 thinking: BetaThinkingConfigParam | Omit = omit,
3182 tool_choice: BetaToolChoiceParam | Omit = omit,
3183 tools: Iterable[BetaToolLike] | Omit = omit,
3184 betas: List[AnthropicBetaParam] | Omit = omit,
3185 user_profile_id: str | Omit = omit,
3186 workspace_id: str | Omit = omit,
3187 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
3188 # The extra values given here take precedence over values defined on the client or passed to this method.
3189 extra_headers: Headers | None = None,
3190 extra_query: Query | None = None,
3191 extra_body: Body | None = None,
3192 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
3193 ) -> ParsedBetaMessage[ResponseFormatT]:
3194 _validate_output_config_conflict(output_config, output_format)
3195
3196 if not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT:
3197 timeout = self._client._calculate_nonstreaming_timeout(
3198 max_tokens, MODEL_NONSTREAMING_TOKENS.get(model, None)
3199 )
3200
3201 if model in DEPRECATED_MODELS:
3202 warnings.warn(
3203 f"The model '{model}' is deprecated and will reach end-of-life on {DEPRECATED_MODELS[model]}.\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.",
3204 DeprecationWarning,
3205 stacklevel=3,
3206 )
3207
3208 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
3209 warnings.warn(
3210 f"Using Claude with {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",
3211 UserWarning,
3212 stacklevel=3,
3213 )
3214 betas = [beta for beta in betas] if is_given(betas) else []
3215
3216 if "structured-outputs-2025-12-15" not in betas:
3217 # Ensure structured outputs beta is included for parse method
3218 betas.append("structured-outputs-2025-12-15")
3219
3220 tools = _to_tool_params(tools)
3221 extra_headers = merge_headers(
3222 _helper_header("beta.messages.parse"),
3223 strip_not_given(
3224 {
3225 "anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else not_given,
3226 "anthropic-user-profile-id": user_profile_id,
3227 "anthropic-workspace-id": workspace_id,
3228 }
3229 ),
3230 _stainless_helper_header(tools, messages),
3231 extra_headers or {},
3232 )
3233
3234 if is_given(output_format) and output_format is not None:
3235 if isinstance(output_format, Mapping):
3236 raise TypeError(
3237 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
3238 )
3239 adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format)
3240
3241 try:
3242 schema = adapted_type.json_schema()
3243 transformed_output_format = BetaJSONOutputFormatParam(
3244 schema=transform_schema(schema), type="json_schema"
3245 )
3246 except pydantic.errors.PydanticSchemaGenerationError as e:
3247 raise TypeError(
3248 (
3249 "Could not generate JSON schema for the given `output_format` type. "
3250 "Use a type that works with `pydantic.TypeAdapter`"
3251 )
3252 ) from e
3253
3254 merged_output_config = _merge_output_configs(output_config, transformed_output_format)
3255 else:
3256 merged_output_config = output_config
3257
3258 def parser(response: BetaMessage) -> ParsedBetaMessage[ResponseFormatT]:
3259 return parse_beta_response(
3260 response=response,
3261 output_format=cast(
3262 ResponseFormatT,
3263 output_format if is_given(output_format) and output_format is not None else not_given,
3264 ),
3265 )
3266
3267 return await self._post(
3268 "/v1/messages?beta=true",
3269 body={
3270 "max_tokens": max_tokens,
3271 "messages": messages,
3272 "model": model,
3273 "cache_control": cache_control,
3274 "compaction": compaction,
3275 "container": container,
3276 "context_management": context_management,
3277 "diagnostics": diagnostics,
3278 "fallback_credit_token": fallback_credit_token,
3279 "fallbacks": fallbacks,
3280 "inference_geo": inference_geo,
3281 "mcp_servers": mcp_servers,
3282 "output_config": merged_output_config,
3283 "metadata": metadata,
3284 "output_format": omit,
3285 "service_tier": service_tier,
3286 "speed": speed,
3287 "stop_sequences": stop_sequences,
3288 "system": system,
3289 "thinking": thinking,
3290 "tool_choice": tool_choice,
3291 "tools": tools,
3292 },
3293 options=make_request_options(
3294 extra_headers=extra_headers,
3295 extra_query=extra_query,
3296 extra_body=extra_body,
3297 timeout=timeout,
3298 post_parser=parser,
3299 ),
3300 cast_to=cast(Type[ParsedBetaMessage[ResponseFormatT]], BetaMessage),
3301 stream=False,
3302 )
3303
3304 @overload
3305 def tool_runner(
3306 self,
3307 *,
3308 max_tokens: int,
3309 messages: Iterable[BetaMessageParam],
3310 model: ModelParam,
3311 tools: Iterable[BetaAsyncRunnableTool | BetaToolUnionParam],
3312 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
3313 max_iterations: int | Omit = omit,
3314 container: Optional[message_create_params.Container] | Omit = omit,
3315 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
3316 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
3317 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
3318 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
3319 inference_geo: Optional[str] | Omit = omit,
3320 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
3321 metadata: BetaMetadataParam | Omit = omit,
3322 output_config: BetaOutputConfigParam | Omit = omit,
3323 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
3324 service_tier: Literal["auto", "standard_only"] | Omit = omit,
3325 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
3326 stop_sequences: SequenceNotStr[str] | Omit = omit,
3327 stream: Literal[False] | Omit = omit,
3328 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
3329 thinking: BetaThinkingConfigParam | Omit = omit,
3330 tool_choice: BetaToolChoiceParam | Omit = omit,
3331 betas: List[AnthropicBetaParam] | Omit = omit,
3332 user_profile_id: str | Omit = omit,
3333 workspace_id: str | Omit = omit,
3334 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
3335 # The extra values given here take precedence over values defined on the client or passed to this method.
3336 extra_headers: Headers | None = None,
3337 extra_query: Query | None = None,
3338 extra_body: Body | None = None,
3339 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
3340 ) -> BetaAsyncToolRunner[ResponseFormatT]: ...
3341
3342 @overload
3343 def tool_runner(
3344 self,
3345 *,
3346 max_tokens: int,
3347 messages: Iterable[BetaMessageParam],
3348 model: ModelParam,
3349 tools: Iterable[BetaAsyncRunnableTool | BetaToolUnionParam],
3350 stream: Literal[True],
3351 max_iterations: int | Omit = omit,
3352 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
3353 container: Optional[message_create_params.Container] | Omit = omit,
3354 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
3355 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
3356 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
3357 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
3358 inference_geo: Optional[str] | Omit = omit,
3359 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
3360 metadata: BetaMetadataParam | Omit = omit,
3361 output_config: BetaOutputConfigParam | Omit = omit,
3362 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
3363 service_tier: Literal["auto", "standard_only"] | Omit = omit,
3364 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
3365 stop_sequences: SequenceNotStr[str] | Omit = omit,
3366 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
3367 thinking: BetaThinkingConfigParam | Omit = omit,
3368 tool_choice: BetaToolChoiceParam | Omit = omit,
3369 betas: List[AnthropicBetaParam] | Omit = omit,
3370 user_profile_id: str | Omit = omit,
3371 workspace_id: str | Omit = omit,
3372 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
3373 # The extra values given here take precedence over values defined on the client or passed to this method.
3374 extra_headers: Headers | None = None,
3375 extra_query: Query | None = None,
3376 extra_body: Body | None = None,
3377 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
3378 ) -> BetaAsyncStreamingToolRunner[ResponseFormatT]: ...
3379
3380 @overload
3381 def tool_runner(
3382 self,
3383 *,
3384 max_tokens: int,
3385 messages: Iterable[BetaMessageParam],
3386 model: ModelParam,
3387 tools: Iterable[BetaAsyncRunnableTool | BetaToolUnionParam],
3388 stream: bool,
3389 max_iterations: int | Omit = omit,
3390 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
3391 container: Optional[message_create_params.Container] | Omit = omit,
3392 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
3393 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
3394 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
3395 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
3396 inference_geo: Optional[str] | Omit = omit,
3397 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
3398 metadata: BetaMetadataParam | Omit = omit,
3399 output_config: BetaOutputConfigParam | Omit = omit,
3400 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
3401 service_tier: Literal["auto", "standard_only"] | Omit = omit,
3402 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
3403 stop_sequences: SequenceNotStr[str] | Omit = omit,
3404 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
3405 thinking: BetaThinkingConfigParam | Omit = omit,
3406 tool_choice: BetaToolChoiceParam | Omit = omit,
3407 betas: List[AnthropicBetaParam] | Omit = omit,
3408 user_profile_id: str | Omit = omit,
3409 workspace_id: str | Omit = omit,
3410 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
3411 # The extra values given here take precedence over values defined on the client or passed to this method.
3412 extra_headers: Headers | None = None,
3413 extra_query: Query | None = None,
3414 extra_body: Body | None = None,
3415 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
3416 ) -> BetaAsyncStreamingToolRunner[ResponseFormatT] | BetaAsyncToolRunner[ResponseFormatT]: ...
3417
3418 def tool_runner(
3419 self,
3420 *,
3421 max_tokens: int,
3422 messages: Iterable[BetaMessageParam],
3423 model: ModelParam,
3424 tools: Iterable[BetaAsyncRunnableTool | BetaToolUnionParam],
3425 max_iterations: int | Omit = omit,
3426 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
3427 container: Optional[message_create_params.Container] | Omit = omit,
3428 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
3429 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
3430 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
3431 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
3432 inference_geo: Optional[str] | Omit = omit,
3433 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
3434 metadata: BetaMetadataParam | Omit = omit,
3435 output_config: BetaOutputConfigParam | Omit = omit,
3436 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
3437 service_tier: Literal["auto", "standard_only"] | Omit = omit,
3438 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
3439 stop_sequences: SequenceNotStr[str] | Omit = omit,
3440 stream: Literal[True] | Literal[False] | Omit = omit,
3441 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
3442 thinking: BetaThinkingConfigParam | Omit = omit,
3443 tool_choice: BetaToolChoiceParam | Omit = omit,
3444 betas: List[AnthropicBetaParam] | Omit = omit,
3445 user_profile_id: str | Omit = omit,
3446 workspace_id: str | Omit = omit,
3447 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
3448 # The extra values given here take precedence over values defined on the client or passed to this method.
3449 extra_headers: Headers | None = None,
3450 extra_query: Query | None = None,
3451 extra_body: Body | None = None,
3452 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
3453 ) -> BetaAsyncToolRunner[ResponseFormatT] | BetaAsyncStreamingToolRunner[ResponseFormatT]:
3454 """Create a Message stream"""
3455 _validate_output_config_conflict(output_config, output_format)
3456
3457 if model in DEPRECATED_MODELS:
3458 warnings.warn(
3459 f"The model '{model}' is deprecated and will reach end-of-life on {DEPRECATED_MODELS[model]}.\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.",
3460 DeprecationWarning,
3461 stacklevel=3,
3462 )
3463
3464 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
3465 warnings.warn(
3466 f"Using Claude with {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",
3467 UserWarning,
3468 stacklevel=3,
3469 )
3470
3471 extra_headers = merge_headers(
3472 _helper_header("BetaToolRunner"),
3473 strip_not_given(
3474 {
3475 "anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else not_given,
3476 "anthropic-user-profile-id": user_profile_id,
3477 "anthropic-workspace-id": workspace_id,
3478 }
3479 ),
3480 _stainless_helper_header(tools, messages),
3481 extra_headers or {},
3482 )
3483
3484 runnable_tools: list[BetaAsyncRunnableTool] = []
3485 raw_tools: list[BetaToolUnionParam] = []
3486
3487 for tool in tools:
3488 if isinstance(tool, (BetaAsyncFunctionTool, BetaAsyncBuiltinFunctionTool)):
3489 runnable_tools.append(tool)
3490 else:
3491 raw_tools.append(tool)
3492
3493 params = cast(
3494 message_create_params.ParseMessageCreateParamsBase[ResponseFormatT],
3495 {
3496 "max_tokens": max_tokens,
3497 "messages": messages,
3498 "model": model,
3499 "cache_control": cache_control,
3500 "container": container,
3501 "context_management": context_management,
3502 "diagnostics": diagnostics,
3503 "fallback_credit_token": fallback_credit_token,
3504 "fallbacks": fallbacks,
3505 "inference_geo": inference_geo,
3506 "mcp_servers": mcp_servers,
3507 "metadata": metadata,
3508 "output_config": output_config,
3509 "output_format": output_format,
3510 "service_tier": service_tier,
3511 "speed": speed,
3512 "stop_sequences": stop_sequences,
3513 "system": system,
3514 "thinking": thinking,
3515 "tool_choice": tool_choice,
3516 "tools": [*[tool.to_dict() for tool in runnable_tools], *raw_tools],
3517 },
3518 )
3519
3520 if stream:
3521 return BetaAsyncStreamingToolRunner[ResponseFormatT](
3522 tools=runnable_tools,
3523 params=params,
3524 options={
3525 "extra_headers": extra_headers,
3526 "extra_query": extra_query,
3527 "extra_body": extra_body,
3528 "timeout": timeout,
3529 },
3530 client=cast("AsyncAnthropic", self._client),
3531 max_iterations=max_iterations if is_given(max_iterations) else None,
3532 )
3533 return BetaAsyncToolRunner[ResponseFormatT](
3534 tools=runnable_tools,
3535 params=params,
3536 options={
3537 "extra_headers": extra_headers,
3538 "extra_query": extra_query,
3539 "extra_body": extra_body,
3540 "timeout": timeout,
3541 },
3542 client=cast("AsyncAnthropic", self._client),
3543 max_iterations=max_iterations if is_given(max_iterations) else None,
3544 )
3545
3546 def stream(
3547 self,
3548 *,
3549 max_tokens: int,
3550 messages: Iterable[BetaMessageParam],
3551 model: ModelParam,
3552 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
3553 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
3554 metadata: BetaMetadataParam | Omit = omit,
3555 output_config: BetaOutputConfigParam | Omit = omit,
3556 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
3557 container: Optional[message_create_params.Container] | Omit = omit,
3558 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
3559 diagnostics: Optional[BetaDiagnosticsParam] | Omit = omit,
3560 fallback_credit_token: Optional[message_create_params.FallbackCreditToken] | Omit = omit,
3561 fallbacks: Optional[BetaFallbacksParam] | Omit = omit,
3562 inference_geo: Optional[str] | Omit = omit,
3563 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
3564 service_tier: Literal["auto", "standard_only"] | Omit = omit,
3565 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
3566 stop_sequences: SequenceNotStr[str] | Omit = omit,
3567 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
3568 thinking: BetaThinkingConfigParam | Omit = omit,
3569 tool_choice: BetaToolChoiceParam | Omit = omit,
3570 tools: Iterable[BetaToolLike] | Omit = omit,
3571 betas: List[AnthropicBetaParam] | Omit = omit,
3572 user_profile_id: str | Omit = omit,
3573 workspace_id: str | Omit = omit,
3574 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
3575 # The extra values given here take precedence over values defined on the client or passed to this method.
3576 extra_headers: Headers | None = None,
3577 extra_query: Query | None = None,
3578 extra_body: Body | None = None,
3579 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
3580 ) -> BetaAsyncMessageStreamManager[ResponseFormatT]:
3581 _validate_output_config_conflict(output_config, output_format)
3582
3583 if model in DEPRECATED_MODELS:
3584 warnings.warn(
3585 f"The model '{model}' is deprecated and will reach end-of-life on {DEPRECATED_MODELS[model]}.\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.",
3586 DeprecationWarning,
3587 stacklevel=3,
3588 )
3589
3590 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
3591 warnings.warn(
3592 f"Using Claude with {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",
3593 UserWarning,
3594 stacklevel=3,
3595 )
3596
3597 tools = _to_tool_params(tools)
3598 extra_headers = merge_headers(
3599 {
3600 _STAINLESS_HELPER_METHOD_HEADER: _HELPER_METHOD_STREAM,
3601 _STAINLESS_STREAM_HELPER_HEADER: "beta.messages",
3602 },
3603 strip_not_given(
3604 {
3605 "anthropic-beta": ",".join(str(e) for e in betas) if is_given(betas) else not_given,
3606 "anthropic-user-profile-id": user_profile_id,
3607 "anthropic-workspace-id": workspace_id,
3608 }
3609 ),
3610 _stainless_helper_header(tools, messages),
3611 extra_headers or {},
3612 )
3613
3614 transformed_output_format: BetaJSONOutputFormatParam | Omit = omit
3615
3616 if is_given(output_format) and output_format is not None:
3617 if isinstance(output_format, Mapping):
3618 raise TypeError(
3619 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
3620 )
3621 adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format)
3622
3623 try:
3624 schema = adapted_type.json_schema()
3625 transformed_output_format = BetaJSONOutputFormatParam(
3626 schema=transform_schema(schema), type="json_schema"
3627 )
3628 except pydantic.errors.PydanticSchemaGenerationError as e:
3629 raise TypeError(
3630 (
3631 "Could not generate JSON schema for the given `output_format` type. "
3632 "Use a type that works with `pydantic.TypeAdapter`"
3633 )
3634 ) from e
3635
3636 merged_output_config = _merge_output_configs(output_config, transformed_output_format)
3637
3638 request = self._post(
3639 "/v1/messages?beta=true",
3640 body={
3641 "max_tokens": max_tokens,
3642 "messages": messages,
3643 "model": model,
3644 "cache_control": cache_control,
3645 "compaction": compaction,
3646 "metadata": metadata,
3647 "output_config": merged_output_config,
3648 "output_format": omit,
3649 "container": container,
3650 "context_management": context_management,
3651 "diagnostics": diagnostics,
3652 "fallback_credit_token": fallback_credit_token,
3653 "fallbacks": fallbacks,
3654 "inference_geo": inference_geo,
3655 "mcp_servers": mcp_servers,
3656 "service_tier": service_tier,
3657 "speed": speed,
3658 "stop_sequences": stop_sequences,
3659 "system": system,
3660 "thinking": thinking,
3661 "tools": tools,
3662 "tool_choice": tool_choice,
3663 "stream": True,
3664 },
3665 options=make_request_options(
3666 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
3667 ),
3668 cast_to=BetaMessage,
3669 stream=True,
3670 stream_cls=AsyncStream[BetaRawMessageStreamEvent],
3671 )
3672 return BetaAsyncMessageStreamManager(
3673 request,
3674 output_format=cast(ResponseFormatT, output_format),
3675 )
3676
3677 async def count_tokens(
3678 self,
3679 *,
3680 messages: Iterable[BetaMessageParam],
3681 model: ModelParam,
3682 cache_control: Optional[BetaCacheControlEphemeralParam] | Omit = omit,
3683 compaction: Optional[BetaCompactionConfigParam] | Omit = omit,
3684 context_management: Optional[BetaContextManagementConfigParam] | Omit = omit,
3685 mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] | Omit = omit,
3686 output_config: BetaOutputConfigParam | Omit = omit,
3687 speed: Optional[Literal["standard", "fast"]] | Omit = omit,
3688 system: Union[str, Iterable[BetaTextBlockParam]] | Omit = omit,
3689 thinking: BetaThinkingConfigParam | Omit = omit,
3690 tool_choice: BetaToolChoiceParam | Omit = omit,
3691 tools: Iterable[BetaToolLike] | Omit = omit,
3692 betas: List[AnthropicBetaParam] | Omit = omit,
3693 user_profile_id: str | Omit = omit,
3694 workspace_id: str | Omit = omit,
3695 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
3696 # The extra values given here take precedence over values defined on the client or passed to this method.
3697 extra_headers: Headers | None = None,
3698 extra_query: Query | None = None,
3699 extra_body: Body | None = None,
3700 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
3701 ) -> BetaMessageTokensCount:
3702 """
3703 Count the number of tokens in a Message.
3704
3705 The Token Count API can be used to count the number of tokens in a Message,
3706 including tools, images, and documents, without creating it.
3707
3708 Learn more about token counting in our
3709 [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting)
3710
3711 Args:
3712 messages: Input messages.
3713
3714 Our models are trained to operate on alternating `user` and `assistant`
3715 conversational turns. When creating a new `Message`, you specify the prior
3716 conversational turns with the `messages` parameter, and the model then generates
3717 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
3718 in your request will be combined into a single turn.
3719
3720 Each input message must be an object with a `role` and `content`. You can
3721 specify a single `user`-role message, or you can include multiple `user` and
3722 `assistant` messages.
3723
3724 If the final message uses the `assistant` role, the response content will
3725 continue immediately from the content in that message. This can be used to
3726 constrain part of the model's response.
3727
3728 Example with a single `user` message:
3729
3730 ```json
3731 [{ "role": "user", "content": "Hello, Claude" }]
3732 ```
3733
3734 Example with multiple conversational turns:
3735
3736 ```json
3737 [
3738 { "role": "user", "content": "Hello there." },
3739 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
3740 { "role": "user", "content": "Can you explain LLMs in plain English?" }
3741 ]
3742 ```
3743
3744 Example with a partially-filled response from Claude:
3745
3746 ```json
3747 [
3748 {
3749 "role": "user",
3750 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
3751 },
3752 { "role": "assistant", "content": "The best answer is (" }
3753 ]
3754 ```
3755
3756 Each input message `content` may be either a single `string` or an array of
3757 content blocks, where each block has a specific `type`. Using a `string` for
3758 `content` is shorthand for an array of one content block of type `"text"`. The
3759 following input messages are equivalent:
3760
3761 ```json
3762 { "role": "user", "content": "Hello, Claude" }
3763 ```
3764
3765 ```json
3766 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
3767 ```
3768
3769 See
3770 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
3771
3772 Note that if you want to include a
3773 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
3774 you can use the top-level `system` parameter — there is no `"system"` role for
3775 input messages in the Messages API.
3776
3777 There is a limit of 100,000 messages in a single request.
3778
3779 model: The model that will complete your prompt.
3780
3781 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
3782 details and options.
3783
3784 cache_control: Top-level cache control automatically applies a cache_control marker to the last
3785 cacheable block in the request.
3786
3787 compaction: Compact the whole conversation and return a signed `compaction` block, alone,
3788 that a later request sends back first in `messages`, in place of the messages it
3789 summarizes. There is no trigger and no pause flag: sending the parameter
3790 compacts, and nothing is sampled after the block.
3791
3792 The summarization prompt is the server's own unless `instructions` are given,
3793 which then replace it for this request; a value that is empty or only whitespace
3794 counts as absent.
3795
3796 context_management: Context management configuration.
3797
3798 This allows you to control how Claude manages context across multiple requests,
3799 such as whether to clear function results or not.
3800
3801 mcp_servers: MCP servers to be utilized in this request
3802
3803 output_config: Configuration options for the model's output, such as the output format.
3804
3805 speed: Inference speed mode. `fast` provides significantly faster output token
3806 generation at premium pricing. Not all models support `fast`; invalid
3807 combinations are rejected at create time.
3808
3809 system: System prompt.
3810
3811 A system prompt is a way of providing context and instructions to Claude, such
3812 as specifying a particular goal or role. See our
3813 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
3814
3815 thinking: Configuration for enabling Claude's extended thinking.
3816
3817 When enabled, responses include `thinking` content blocks showing Claude's
3818 thinking process before the final answer. Requires a minimum budget of 1,024
3819 tokens and counts towards your `max_tokens` limit.
3820
3821 See
3822 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
3823 for details.
3824
3825 tool_choice: How the model should use the provided tools. The model can use a specific tool,
3826 any available tool, decide by itself, or not use tools at all.
3827
3828 tools: Definitions of tools that the model may use.
3829
3830 If you include `tools` in your API request, the model may return `tool_use`
3831 content blocks that represent the model's use of those tools. You can then run
3832 those tools using the tool input generated by the model and then optionally
3833 return results back to the model using `tool_result` content blocks.
3834
3835 There are two types of tools: **client tools** and **server tools**. The
3836 behavior described below applies to client tools. For
3837 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
3838 see their individual documentation as each has its own behavior (e.g., the
3839 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
3840
3841 Each tool definition includes:
3842
3843 - `name`: Name of the tool.
3844 - `description`: Optional, but strongly-recommended description of the tool.
3845 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
3846 tool `input` shape that the model will produce in `tool_use` output content
3847 blocks.
3848
3849 For example, if you defined `tools` as:
3850
3851 ```json
3852 [
3853 {
3854 "name": "get_stock_price",
3855 "description": "Get the current stock price for a given ticker symbol.",
3856 "input_schema": {
3857 "type": "object",
3858 "properties": {
3859 "ticker": {
3860 "type": "string",
3861 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
3862 }
3863 },
3864 "required": ["ticker"]
3865 }
3866 }
3867 ]
3868 ```
3869
3870 And then asked the model "What's the S&P 500 at today?", the model might produce
3871 `tool_use` content blocks in the response like this:
3872
3873 ```json
3874 [
3875 {
3876 "type": "tool_use",
3877 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
3878 "name": "get_stock_price",
3879 "input": { "ticker": "^GSPC" }
3880 }
3881 ]
3882 ```
3883
3884 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
3885 input, and return the following back to the model in a subsequent `user`
3886 message:
3887
3888 ```json
3889 [
3890 {
3891 "type": "tool_result",
3892 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
3893 "content": "259.75 USD"
3894 }
3895 ]
3896 ```
3897
3898 Tools can be used for workflows that include running client-side tools and
3899 functions, or more generally whenever you want the model to produce a particular
3900 JSON structure of output.
3901
3902 See our
3903 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
3904 for more details.
3905
3906 betas: Optional header to specify the beta version(s) you want to use.
3907
3908 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
3909 party other than your organization. Requires the `user-profiles` beta header.
3910
3911 workspace_id: Optional header to select the Workspace for this request. The value is a
3912 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
3913
3914 Only needed for credentials that can act on more than one Workspace. A
3915 credential that belongs to a specific Workspace may omit it; if sent, it must
3916 match that Workspace.
3917
3918 extra_headers: Send extra headers
3919
3920 extra_query: Add additional query parameters to the request
3921
3922 extra_body: Add additional JSON properties to the request
3923
3924 timeout: Override the client-level default timeout for this request, in seconds
3925 """
3926 tools = _to_tool_params(tools)
3927 extra_headers = {
3928 **strip_not_given(
3929 {
3930 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["token-counting-2024-11-01"]))
3931 if is_given(betas)
3932 else not_given,
3933 "anthropic-user-profile-id": user_profile_id,
3934 "anthropic-workspace-id": workspace_id,
3935 }
3936 ),
3937 **(extra_headers or {}),
3938 }
3939 extra_headers = {"anthropic-beta": "token-counting-2024-11-01", **(extra_headers or {})}
3940 return await self._post(
3941 "/v1/messages/count_tokens?beta=true",
3942 body={
3943 "messages": messages,
3944 "model": model,
3945 "cache_control": cache_control,
3946 "compaction": compaction,
3947 "context_management": context_management,
3948 "mcp_servers": mcp_servers,
3949 "output_config": output_config,
3950 "speed": speed,
3951 "system": system,
3952 "thinking": thinking,
3953 "tool_choice": tool_choice,
3954 "tools": tools,
3955 },
3956 options=make_request_options(
3957 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
3958 ),
3959 cast_to=BetaMessageTokensCount,
3960 )
3961
3962
3963 class MessagesWithRawResponse:
3964 def __init__(self, messages: Messages) -> None:
3965 self._messages = messages
3966
3967 self.create = to_raw_response_wrapper(
3968 messages.create,
3969 )
3970 self.parse = to_raw_response_wrapper(
3971 messages.parse,
3972 )
3973 self.count_tokens = to_raw_response_wrapper(
3974 messages.count_tokens,
3975 )
3976
3977 @cached_property
3978 def batches(self) -> BatchesWithRawResponse:
3979 return BatchesWithRawResponse(self._messages.batches)
3980
3981
3982 class AsyncMessagesWithRawResponse:
3983 def __init__(self, messages: AsyncMessages) -> None:
3984 self._messages = messages
3985
3986 self.create = async_to_raw_response_wrapper(
3987 messages.create,
3988 )
3989 self.parse = async_to_raw_response_wrapper(
3990 messages.parse,
3991 )
3992 self.count_tokens = async_to_raw_response_wrapper(
3993 messages.count_tokens,
3994 )
3995
3996 @cached_property
3997 def batches(self) -> AsyncBatchesWithRawResponse:
3998 return AsyncBatchesWithRawResponse(self._messages.batches)
3999
4000
4001 class MessagesWithStreamingResponse:
4002 def __init__(self, messages: Messages) -> None:
4003 self._messages = messages
4004
4005 self.create = to_streamed_response_wrapper(
4006 messages.create,
4007 )
4008 self.count_tokens = to_streamed_response_wrapper(
4009 messages.count_tokens,
4010 )
4011
4012 @cached_property
4013 def batches(self) -> BatchesWithStreamingResponse:
4014 return BatchesWithStreamingResponse(self._messages.batches)
4015
4016
4017 class AsyncMessagesWithStreamingResponse:
4018 def __init__(self, messages: AsyncMessages) -> None:
4019 self._messages = messages
4020
4021 self.create = async_to_streamed_response_wrapper(
4022 messages.create,
4023 )
4024 self.count_tokens = async_to_streamed_response_wrapper(
4025 messages.count_tokens,
4026 )
4027
4028 @cached_property
4029 def batches(self) -> AsyncBatchesWithStreamingResponse:
4030 return AsyncBatchesWithStreamingResponse(self._messages.batches)
4031
4032
4033 def _validate_output_config_conflict(
4034 output_config: BetaOutputConfigParam | Omit,
4035 output_format: object,
4036 ) -> None:
4037 if is_given(output_format) and output_format is not None and is_given(output_config):
4038 if "format" in output_config and output_config["format"] is not None:
4039 raise AnthropicError(
4040 "Both output_format and output_config.format were provided. "
4041 "Please use only output_config.format (output_format is deprecated).",
4042 )
4043
4044
4045 def _merge_output_configs(
4046 output_config: BetaOutputConfigParam | Omit,
4047 output_format: Optional[BetaJSONOutputFormatParam] | Omit,
4048 ) -> BetaOutputConfigParam | Omit:
4049 if is_given(output_format):
4050 if is_given(output_config):
4051 return {**output_config, "format": output_format}
4052 else:
4053 return {"format": output_format}
4054 return output_config