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