Debian Codegraph @

src/anthropic/resources/messages/messages.py

raw
1 from __future__ import annotations
2
3 import warnings
4 from typing import Type, Union, Mapping, Iterable, Optional, cast
5 from functools import partial
6 from typing_extensions import Literal, overload
7
8 import httpx2
9 import pydantic
10
11 from ...types import (
12 DiagnosticsParam,
13 ThinkingConfigParam,
14 )
15 from .batches import (
16 Batches,
17 AsyncBatches,
18 BatchesWithRawResponse,
19 AsyncBatchesWithRawResponse,
20 BatchesWithStreamingResponse,
21 AsyncBatchesWithStreamingResponse,
22 )
23 from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
24 from ..._utils import is_given, required_args, strip_not_given
25 from ..._compat import cached_property
26 from ..._models import TypeAdapter
27 from ..._resource import SyncAPIResource, AsyncAPIResource
28 from ..._response import (
29 to_raw_response_wrapper,
30 to_streamed_response_wrapper,
31 async_to_raw_response_wrapper,
32 async_to_streamed_response_wrapper,
33 )
34 from ..._constants import DEFAULT_TIMEOUT, MODEL_NONSTREAMING_TOKENS
35 from ..._streaming import Stream, AsyncStream
36 from ..._base_client import (
37 merge_headers,
38 make_request_options,
39 )
40 from ...lib.streaming import MessageStreamManager, AsyncMessageStreamManager
41 from ...types.message import Message
42 from ...types.model_param import ModelParam
43 from ...types.message_param import MessageParam
44 from ...lib._parse._response import ResponseFormatT, parse_response
45 from ...types.metadata_param import MetadataParam
46 from ...types.parsed_message import ParsedMessage
47 from ...lib._parse._transform import transform_schema
48 from ...lib._stainless_helpers import (
49 HELPER_METHOD_STREAM as _HELPER_METHOD_STREAM,
50 STAINLESS_HELPER_METHOD_HEADER as _STAINLESS_HELPER_METHOD_HEADER,
51 STAINLESS_STREAM_HELPER_HEADER as _STAINLESS_STREAM_HELPER_HEADER,
52 helper_header as _helper_header,
53 )
54 from ...types.text_block_param import TextBlockParam
55 from ...types.tool_union_param import ToolUnionParam
56 from ...types.diagnostics_param import DiagnosticsParam
57 from ...types.tool_choice_param import ToolChoiceParam
58 from ...types.output_config_param import OutputConfigParam
59 from ...types.message_tokens_count import MessageTokensCount
60 from ...types.thinking_config_param import ThinkingConfigParam
61 from ...types.json_output_format_param import JSONOutputFormatParam
62 from ...types.raw_message_stream_event import RawMessageStreamEvent
63 from ...types.cache_control_ephemeral_param import CacheControlEphemeralParam
64 from ...types.message_count_tokens_tool_param import MessageCountTokensToolParam
65 from ...types.message_create_params_container_param import MessageCreateParamsContainerParam
66
67 __all__ = ["Messages", "AsyncMessages"]
68
69
70 DEPRECATED_MODELS = {
71 "claude-1.3": "November 6th, 2024",
72 "claude-1.3-100k": "November 6th, 2024",
73 "claude-instant-1.1": "November 6th, 2024",
74 "claude-instant-1.1-100k": "November 6th, 2024",
75 "claude-instant-1.2": "November 6th, 2024",
76 "claude-3-sonnet-20240229": "July 21st, 2025",
77 "claude-3-opus-20240229": "January 5th, 2026",
78 "claude-2.1": "July 21st, 2025",
79 "claude-2.0": "July 21st, 2025",
80 "claude-3-7-sonnet-latest": "February 19th, 2026",
81 "claude-3-7-sonnet-20250219": "February 19th, 2026",
82 "claude-3-5-haiku-latest": "February 19th, 2026",
83 "claude-3-5-haiku-20241022": "February 19th, 2026",
84 "claude-opus-4-0": "June 15th, 2026",
85 "claude-opus-4-20250514": "June 15th, 2026",
86 "claude-sonnet-4-0": "June 15th, 2026",
87 "claude-sonnet-4-20250514": "June 15th, 2026",
88 "claude-mythos-preview": "June 30th, 2026",
89 }
90
91 MODELS_TO_WARN_WITH_THINKING_ENABLED = ["claude-opus-4-6", "claude-mythos-preview"]
92
93
94 class Messages(SyncAPIResource):
95 @cached_property
96 def batches(self) -> Batches:
97 return Batches(self._client)
98
99 @cached_property
100 def with_raw_response(self) -> MessagesWithRawResponse:
101 """
102 This property can be used as a prefix for any HTTP method call to return
103 the raw response object instead of the parsed content.
104
105 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
106 """
107 return MessagesWithRawResponse(self)
108
109 @cached_property
110 def with_streaming_response(self) -> MessagesWithStreamingResponse:
111 """
112 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
113
114 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
115 """
116 return MessagesWithStreamingResponse(self)
117
118 @overload
119 def create(
120 self,
121 *,
122 max_tokens: int,
123 messages: Iterable[MessageParam],
124 model: ModelParam,
125 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
126 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
127 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
128 inference_geo: Optional[str] | Omit = omit,
129 metadata: MetadataParam | Omit = omit,
130 output_config: OutputConfigParam | Omit = omit,
131 service_tier: Literal["auto", "standard_only"] | Omit = omit,
132 stop_sequences: SequenceNotStr[str] | Omit = omit,
133 stream: Literal[False] | Omit = omit,
134 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
135 thinking: ThinkingConfigParam | Omit = omit,
136 tool_choice: ToolChoiceParam | Omit = omit,
137 tools: Iterable[ToolUnionParam] | Omit = omit,
138 user_profile_id: str | Omit = omit,
139 workspace_id: str | Omit = omit,
140 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
141 # The extra values given here take precedence over values defined on the client or passed to this method.
142 extra_headers: Headers | None = None,
143 extra_query: Query | None = None,
144 extra_body: Body | None = None,
145 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
146 ) -> Message:
147 """
148 Send a structured list of input messages with text and/or image content, and the
149 model will generate the next message in the conversation.
150
151 The Messages API can be used for either single queries or stateless multi-turn
152 conversations.
153
154 Learn more about the Messages API in our
155 [user guide](https://platform.claude.com/docs/en/get-started)
156
157 Args:
158 max_tokens: The maximum number of tokens to generate before stopping.
159
160 Note that our models may stop _before_ reaching this maximum. This parameter
161 only specifies the absolute maximum number of tokens to generate.
162
163 Set to `0` to populate the
164 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
165 without generating a response.
166
167 Different models have different maximum values for this parameter. See
168 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
169 details.
170
171 messages: Input messages.
172
173 Our models are trained to operate on alternating `user` and `assistant`
174 conversational turns. When creating a new `Message`, you specify the prior
175 conversational turns with the `messages` parameter, and the model then generates
176 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
177 in your request will be combined into a single turn.
178
179 Each input message must be an object with a `role` and `content`. You can
180 specify a single `user`-role message, or you can include multiple `user` and
181 `assistant` messages.
182
183 If the final message uses the `assistant` role, the response content will
184 continue immediately from the content in that message. This can be used to
185 constrain part of the model's response.
186
187 Example with a single `user` message:
188
189 ```json
190 [{ "role": "user", "content": "Hello, Claude" }]
191 ```
192
193 Example with multiple conversational turns:
194
195 ```json
196 [
197 { "role": "user", "content": "Hello there." },
198 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
199 { "role": "user", "content": "Can you explain LLMs in plain English?" }
200 ]
201 ```
202
203 Example with a partially-filled response from Claude:
204
205 ```json
206 [
207 {
208 "role": "user",
209 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
210 },
211 { "role": "assistant", "content": "The best answer is (" }
212 ]
213 ```
214
215 Each input message `content` may be either a single `string` or an array of
216 content blocks, where each block has a specific `type`. Using a `string` for
217 `content` is shorthand for an array of one content block of type `"text"`. The
218 following input messages are equivalent:
219
220 ```json
221 { "role": "user", "content": "Hello, Claude" }
222 ```
223
224 ```json
225 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
226 ```
227
228 See
229 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
230
231 Note that if you want to include a
232 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
233 you can use the top-level `system` parameter — there is no `"system"` role for
234 input messages in the Messages API.
235
236 There is a limit of 100,000 messages in a single request.
237
238 model: The model that will complete your prompt.
239
240 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
241 details and options.
242
243 cache_control: Top-level cache control automatically applies a cache_control marker to the last
244 cacheable block in the request.
245
246 container: Container identifier for reuse across requests.
247
248 diagnostics: Request-level diagnostics. Supply `previous_message_id` to have the response
249 include `diagnostics.cache_miss_reason` explaining any prompt-cache divergence
250 from that prior request.
251
252 inference_geo: Specifies the geographic region for inference processing. If not specified, the
253 workspace's `default_inference_geo` is used.
254
255 metadata: An object describing metadata about the request.
256
257 output_config: Configuration options for the model's output, such as the output format.
258
259 service_tier: Determines whether to use priority capacity (if available) or standard capacity
260 for this request.
261
262 Anthropic offers different levels of service for your API requests. See
263 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
264 details.
265
266 stop_sequences: Custom text sequences that will cause the model to stop generating.
267
268 Our models will normally stop when they have naturally completed their turn,
269 which will result in a response `stop_reason` of `"end_turn"`.
270
271 If you want the model to stop generating when it encounters custom strings of
272 text, you can use the `stop_sequences` parameter. If the model encounters one of
273 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
274 and the response `stop_sequence` value will contain the matched stop sequence.
275
276 stream: Whether to incrementally stream the response using server-sent events. When
277 `true`, SDKs return a raw event stream.
278
279 In the TypeScript, Python and Ruby SDKs, the recommended way to stream is
280 `messages.stream()`. It sets `stream` for you and accumulates the events into
281 the final message. See
282 [Streaming with SDKs](https://platform.claude.com/docs/en/build-with-claude/streaming#streaming-with-sdks)
283 for an example in each language.
284
285 system: System prompt.
286
287 A system prompt is a way of providing context and instructions to Claude, such
288 as specifying a particular goal or role. See our
289 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
290
291 thinking: Configuration for enabling Claude's extended thinking.
292
293 When enabled, responses include `thinking` content blocks showing Claude's
294 thinking process before the final answer. Requires a minimum budget of 1,024
295 tokens and counts towards your `max_tokens` limit.
296
297 See
298 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
299 for details.
300
301 tool_choice: How the model should use the provided tools. The model can use a specific tool,
302 any available tool, decide by itself, or not use tools at all.
303
304 tools: Definitions of tools that the model may use.
305
306 If you include `tools` in your API request, the model may return `tool_use`
307 content blocks that represent the model's use of those tools. You can then run
308 those tools using the tool input generated by the model and then optionally
309 return results back to the model using `tool_result` content blocks.
310
311 There are two types of tools: **client tools** and **server tools**. The
312 behavior described below applies to client tools. For
313 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
314 see their individual documentation as each has its own behavior (e.g., the
315 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
316
317 Each tool definition includes:
318
319 - `name`: Name of the tool.
320 - `description`: Optional, but strongly-recommended description of the tool.
321 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
322 tool `input` shape that the model will produce in `tool_use` output content
323 blocks.
324
325 For example, if you defined `tools` as:
326
327 ```json
328 [
329 {
330 "name": "get_stock_price",
331 "description": "Get the current stock price for a given ticker symbol.",
332 "input_schema": {
333 "type": "object",
334 "properties": {
335 "ticker": {
336 "type": "string",
337 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
338 }
339 },
340 "required": ["ticker"]
341 }
342 }
343 ]
344 ```
345
346 And then asked the model "What's the S&P 500 at today?", the model might produce
347 `tool_use` content blocks in the response like this:
348
349 ```json
350 [
351 {
352 "type": "tool_use",
353 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
354 "name": "get_stock_price",
355 "input": { "ticker": "^GSPC" }
356 }
357 ]
358 ```
359
360 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
361 input, and return the following back to the model in a subsequent `user`
362 message:
363
364 ```json
365 [
366 {
367 "type": "tool_result",
368 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
369 "content": "259.75 USD"
370 }
371 ]
372 ```
373
374 Tools can be used for workflows that include running client-side tools and
375 functions, or more generally whenever you want the model to produce a particular
376 JSON structure of output.
377
378 See our
379 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
380 for more details.
381
382 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
383 party other than your organization. Requires the `user-profiles` beta header.
384
385 workspace_id: Optional header to select the Workspace for this request. The value is a
386 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
387
388 Only needed for credentials that can act on more than one Workspace. A
389 credential that belongs to a specific Workspace may omit it; if sent, it must
390 match that Workspace.
391
392 extra_headers: Send extra headers
393
394 extra_query: Add additional query parameters to the request
395
396 extra_body: Add additional JSON properties to the request
397
398 timeout: Override the client-level default timeout for this request, in seconds
399 """
400 ...
401
402 @overload
403 def create(
404 self,
405 *,
406 max_tokens: int,
407 messages: Iterable[MessageParam],
408 model: ModelParam,
409 stream: Literal[True],
410 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
411 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
412 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
413 inference_geo: Optional[str] | Omit = omit,
414 metadata: MetadataParam | Omit = omit,
415 output_config: OutputConfigParam | Omit = omit,
416 service_tier: Literal["auto", "standard_only"] | Omit = omit,
417 stop_sequences: SequenceNotStr[str] | Omit = omit,
418 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
419 thinking: ThinkingConfigParam | Omit = omit,
420 tool_choice: ToolChoiceParam | Omit = omit,
421 tools: Iterable[ToolUnionParam] | Omit = omit,
422 user_profile_id: str | Omit = omit,
423 workspace_id: str | Omit = omit,
424 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
425 # The extra values given here take precedence over values defined on the client or passed to this method.
426 extra_headers: Headers | None = None,
427 extra_query: Query | None = None,
428 extra_body: Body | None = None,
429 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
430 ) -> Stream[RawMessageStreamEvent]:
431 """
432 Send a structured list of input messages with text and/or image content, and the
433 model will generate the next message in the conversation.
434
435 The Messages API can be used for either single queries or stateless multi-turn
436 conversations.
437
438 Learn more about the Messages API in our
439 [user guide](https://platform.claude.com/docs/en/get-started)
440
441 Args:
442 max_tokens: The maximum number of tokens to generate before stopping.
443
444 Note that our models may stop _before_ reaching this maximum. This parameter
445 only specifies the absolute maximum number of tokens to generate.
446
447 Set to `0` to populate the
448 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
449 without generating a response.
450
451 Different models have different maximum values for this parameter. See
452 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
453 details.
454
455 messages: Input messages.
456
457 Our models are trained to operate on alternating `user` and `assistant`
458 conversational turns. When creating a new `Message`, you specify the prior
459 conversational turns with the `messages` parameter, and the model then generates
460 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
461 in your request will be combined into a single turn.
462
463 Each input message must be an object with a `role` and `content`. You can
464 specify a single `user`-role message, or you can include multiple `user` and
465 `assistant` messages.
466
467 If the final message uses the `assistant` role, the response content will
468 continue immediately from the content in that message. This can be used to
469 constrain part of the model's response.
470
471 Example with a single `user` message:
472
473 ```json
474 [{ "role": "user", "content": "Hello, Claude" }]
475 ```
476
477 Example with multiple conversational turns:
478
479 ```json
480 [
481 { "role": "user", "content": "Hello there." },
482 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
483 { "role": "user", "content": "Can you explain LLMs in plain English?" }
484 ]
485 ```
486
487 Example with a partially-filled response from Claude:
488
489 ```json
490 [
491 {
492 "role": "user",
493 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
494 },
495 { "role": "assistant", "content": "The best answer is (" }
496 ]
497 ```
498
499 Each input message `content` may be either a single `string` or an array of
500 content blocks, where each block has a specific `type`. Using a `string` for
501 `content` is shorthand for an array of one content block of type `"text"`. The
502 following input messages are equivalent:
503
504 ```json
505 { "role": "user", "content": "Hello, Claude" }
506 ```
507
508 ```json
509 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
510 ```
511
512 See
513 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
514
515 Note that if you want to include a
516 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
517 you can use the top-level `system` parameter — there is no `"system"` role for
518 input messages in the Messages API.
519
520 There is a limit of 100,000 messages in a single request.
521
522 model: The model that will complete your prompt.
523
524 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
525 details and options.
526
527 stream: Whether to incrementally stream the response using server-sent events. When
528 `true`, SDKs return a raw event stream.
529
530 In the TypeScript, Python and Ruby SDKs, the recommended way to stream is
531 `messages.stream()`. It sets `stream` for you and accumulates the events into
532 the final message. See
533 [Streaming with SDKs](https://platform.claude.com/docs/en/build-with-claude/streaming#streaming-with-sdks)
534 for an example in each language.
535
536 cache_control: Top-level cache control automatically applies a cache_control marker to the last
537 cacheable block in the request.
538
539 container: Container identifier for reuse across requests.
540
541 diagnostics: Request-level diagnostics. Supply `previous_message_id` to have the response
542 include `diagnostics.cache_miss_reason` explaining any prompt-cache divergence
543 from that prior request.
544
545 inference_geo: Specifies the geographic region for inference processing. If not specified, the
546 workspace's `default_inference_geo` is used.
547
548 metadata: An object describing metadata about the request.
549
550 output_config: Configuration options for the model's output, such as the output format.
551
552 service_tier: Determines whether to use priority capacity (if available) or standard capacity
553 for this request.
554
555 Anthropic offers different levels of service for your API requests. See
556 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
557 details.
558
559 stop_sequences: Custom text sequences that will cause the model to stop generating.
560
561 Our models will normally stop when they have naturally completed their turn,
562 which will result in a response `stop_reason` of `"end_turn"`.
563
564 If you want the model to stop generating when it encounters custom strings of
565 text, you can use the `stop_sequences` parameter. If the model encounters one of
566 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
567 and the response `stop_sequence` value will contain the matched stop sequence.
568
569 system: System prompt.
570
571 A system prompt is a way of providing context and instructions to Claude, such
572 as specifying a particular goal or role. See our
573 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
574
575 thinking: Configuration for enabling Claude's extended thinking.
576
577 When enabled, responses include `thinking` content blocks showing Claude's
578 thinking process before the final answer. Requires a minimum budget of 1,024
579 tokens and counts towards your `max_tokens` limit.
580
581 See
582 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
583 for details.
584
585 tool_choice: How the model should use the provided tools. The model can use a specific tool,
586 any available tool, decide by itself, or not use tools at all.
587
588 tools: Definitions of tools that the model may use.
589
590 If you include `tools` in your API request, the model may return `tool_use`
591 content blocks that represent the model's use of those tools. You can then run
592 those tools using the tool input generated by the model and then optionally
593 return results back to the model using `tool_result` content blocks.
594
595 There are two types of tools: **client tools** and **server tools**. The
596 behavior described below applies to client tools. For
597 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
598 see their individual documentation as each has its own behavior (e.g., the
599 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
600
601 Each tool definition includes:
602
603 - `name`: Name of the tool.
604 - `description`: Optional, but strongly-recommended description of the tool.
605 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
606 tool `input` shape that the model will produce in `tool_use` output content
607 blocks.
608
609 For example, if you defined `tools` as:
610
611 ```json
612 [
613 {
614 "name": "get_stock_price",
615 "description": "Get the current stock price for a given ticker symbol.",
616 "input_schema": {
617 "type": "object",
618 "properties": {
619 "ticker": {
620 "type": "string",
621 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
622 }
623 },
624 "required": ["ticker"]
625 }
626 }
627 ]
628 ```
629
630 And then asked the model "What's the S&P 500 at today?", the model might produce
631 `tool_use` content blocks in the response like this:
632
633 ```json
634 [
635 {
636 "type": "tool_use",
637 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
638 "name": "get_stock_price",
639 "input": { "ticker": "^GSPC" }
640 }
641 ]
642 ```
643
644 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
645 input, and return the following back to the model in a subsequent `user`
646 message:
647
648 ```json
649 [
650 {
651 "type": "tool_result",
652 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
653 "content": "259.75 USD"
654 }
655 ]
656 ```
657
658 Tools can be used for workflows that include running client-side tools and
659 functions, or more generally whenever you want the model to produce a particular
660 JSON structure of output.
661
662 See our
663 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
664 for more details.
665
666 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
667 party other than your organization. Requires the `user-profiles` beta header.
668
669 workspace_id: Optional header to select the Workspace for this request. The value is a
670 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
671
672 Only needed for credentials that can act on more than one Workspace. A
673 credential that belongs to a specific Workspace may omit it; if sent, it must
674 match that Workspace.
675
676 extra_headers: Send extra headers
677
678 extra_query: Add additional query parameters to the request
679
680 extra_body: Add additional JSON properties to the request
681
682 timeout: Override the client-level default timeout for this request, in seconds
683 """
684 ...
685
686 @overload
687 def create(
688 self,
689 *,
690 max_tokens: int,
691 messages: Iterable[MessageParam],
692 model: ModelParam,
693 stream: bool,
694 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
695 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
696 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
697 inference_geo: Optional[str] | Omit = omit,
698 metadata: MetadataParam | Omit = omit,
699 output_config: OutputConfigParam | Omit = omit,
700 service_tier: Literal["auto", "standard_only"] | Omit = omit,
701 stop_sequences: SequenceNotStr[str] | Omit = omit,
702 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
703 thinking: ThinkingConfigParam | Omit = omit,
704 tool_choice: ToolChoiceParam | Omit = omit,
705 tools: Iterable[ToolUnionParam] | Omit = omit,
706 user_profile_id: str | Omit = omit,
707 workspace_id: str | Omit = omit,
708 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
709 # The extra values given here take precedence over values defined on the client or passed to this method.
710 extra_headers: Headers | None = None,
711 extra_query: Query | None = None,
712 extra_body: Body | None = None,
713 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
714 ) -> Message | Stream[RawMessageStreamEvent]:
715 """
716 Send a structured list of input messages with text and/or image content, and the
717 model will generate the next message in the conversation.
718
719 The Messages API can be used for either single queries or stateless multi-turn
720 conversations.
721
722 Learn more about the Messages API in our
723 [user guide](https://platform.claude.com/docs/en/get-started)
724
725 Args:
726 max_tokens: The maximum number of tokens to generate before stopping.
727
728 Note that our models may stop _before_ reaching this maximum. This parameter
729 only specifies the absolute maximum number of tokens to generate.
730
731 Set to `0` to populate the
732 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
733 without generating a response.
734
735 Different models have different maximum values for this parameter. See
736 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
737 details.
738
739 messages: Input messages.
740
741 Our models are trained to operate on alternating `user` and `assistant`
742 conversational turns. When creating a new `Message`, you specify the prior
743 conversational turns with the `messages` parameter, and the model then generates
744 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
745 in your request will be combined into a single turn.
746
747 Each input message must be an object with a `role` and `content`. You can
748 specify a single `user`-role message, or you can include multiple `user` and
749 `assistant` messages.
750
751 If the final message uses the `assistant` role, the response content will
752 continue immediately from the content in that message. This can be used to
753 constrain part of the model's response.
754
755 Example with a single `user` message:
756
757 ```json
758 [{ "role": "user", "content": "Hello, Claude" }]
759 ```
760
761 Example with multiple conversational turns:
762
763 ```json
764 [
765 { "role": "user", "content": "Hello there." },
766 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
767 { "role": "user", "content": "Can you explain LLMs in plain English?" }
768 ]
769 ```
770
771 Example with a partially-filled response from Claude:
772
773 ```json
774 [
775 {
776 "role": "user",
777 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
778 },
779 { "role": "assistant", "content": "The best answer is (" }
780 ]
781 ```
782
783 Each input message `content` may be either a single `string` or an array of
784 content blocks, where each block has a specific `type`. Using a `string` for
785 `content` is shorthand for an array of one content block of type `"text"`. The
786 following input messages are equivalent:
787
788 ```json
789 { "role": "user", "content": "Hello, Claude" }
790 ```
791
792 ```json
793 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
794 ```
795
796 See
797 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
798
799 Note that if you want to include a
800 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
801 you can use the top-level `system` parameter — there is no `"system"` role for
802 input messages in the Messages API.
803
804 There is a limit of 100,000 messages in a single request.
805
806 model: The model that will complete your prompt.
807
808 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
809 details and options.
810
811 stream: Whether to incrementally stream the response using server-sent events. When
812 `true`, SDKs return a raw event stream.
813
814 In the TypeScript, Python and Ruby SDKs, the recommended way to stream is
815 `messages.stream()`. It sets `stream` for you and accumulates the events into
816 the final message. See
817 [Streaming with SDKs](https://platform.claude.com/docs/en/build-with-claude/streaming#streaming-with-sdks)
818 for an example in each language.
819
820 cache_control: Top-level cache control automatically applies a cache_control marker to the last
821 cacheable block in the request.
822
823 container: Container identifier for reuse across requests.
824
825 diagnostics: Request-level diagnostics. Supply `previous_message_id` to have the response
826 include `diagnostics.cache_miss_reason` explaining any prompt-cache divergence
827 from that prior request.
828
829 inference_geo: Specifies the geographic region for inference processing. If not specified, the
830 workspace's `default_inference_geo` is used.
831
832 metadata: An object describing metadata about the request.
833
834 output_config: Configuration options for the model's output, such as the output format.
835
836 service_tier: Determines whether to use priority capacity (if available) or standard capacity
837 for this request.
838
839 Anthropic offers different levels of service for your API requests. See
840 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
841 details.
842
843 stop_sequences: Custom text sequences that will cause the model to stop generating.
844
845 Our models will normally stop when they have naturally completed their turn,
846 which will result in a response `stop_reason` of `"end_turn"`.
847
848 If you want the model to stop generating when it encounters custom strings of
849 text, you can use the `stop_sequences` parameter. If the model encounters one of
850 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
851 and the response `stop_sequence` value will contain the matched stop sequence.
852
853 system: System prompt.
854
855 A system prompt is a way of providing context and instructions to Claude, such
856 as specifying a particular goal or role. See our
857 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
858
859 thinking: Configuration for enabling Claude's extended thinking.
860
861 When enabled, responses include `thinking` content blocks showing Claude's
862 thinking process before the final answer. Requires a minimum budget of 1,024
863 tokens and counts towards your `max_tokens` limit.
864
865 See
866 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
867 for details.
868
869 tool_choice: How the model should use the provided tools. The model can use a specific tool,
870 any available tool, decide by itself, or not use tools at all.
871
872 tools: Definitions of tools that the model may use.
873
874 If you include `tools` in your API request, the model may return `tool_use`
875 content blocks that represent the model's use of those tools. You can then run
876 those tools using the tool input generated by the model and then optionally
877 return results back to the model using `tool_result` content blocks.
878
879 There are two types of tools: **client tools** and **server tools**. The
880 behavior described below applies to client tools. For
881 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
882 see their individual documentation as each has its own behavior (e.g., the
883 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
884
885 Each tool definition includes:
886
887 - `name`: Name of the tool.
888 - `description`: Optional, but strongly-recommended description of the tool.
889 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
890 tool `input` shape that the model will produce in `tool_use` output content
891 blocks.
892
893 For example, if you defined `tools` as:
894
895 ```json
896 [
897 {
898 "name": "get_stock_price",
899 "description": "Get the current stock price for a given ticker symbol.",
900 "input_schema": {
901 "type": "object",
902 "properties": {
903 "ticker": {
904 "type": "string",
905 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
906 }
907 },
908 "required": ["ticker"]
909 }
910 }
911 ]
912 ```
913
914 And then asked the model "What's the S&P 500 at today?", the model might produce
915 `tool_use` content blocks in the response like this:
916
917 ```json
918 [
919 {
920 "type": "tool_use",
921 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
922 "name": "get_stock_price",
923 "input": { "ticker": "^GSPC" }
924 }
925 ]
926 ```
927
928 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
929 input, and return the following back to the model in a subsequent `user`
930 message:
931
932 ```json
933 [
934 {
935 "type": "tool_result",
936 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
937 "content": "259.75 USD"
938 }
939 ]
940 ```
941
942 Tools can be used for workflows that include running client-side tools and
943 functions, or more generally whenever you want the model to produce a particular
944 JSON structure of output.
945
946 See our
947 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
948 for more details.
949
950 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
951 party other than your organization. Requires the `user-profiles` beta header.
952
953 workspace_id: Optional header to select the Workspace for this request. The value is a
954 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
955
956 Only needed for credentials that can act on more than one Workspace. A
957 credential that belongs to a specific Workspace may omit it; if sent, it must
958 match that Workspace.
959
960 extra_headers: Send extra headers
961
962 extra_query: Add additional query parameters to the request
963
964 extra_body: Add additional JSON properties to the request
965
966 timeout: Override the client-level default timeout for this request, in seconds
967 """
968 ...
969
970 @required_args(["max_tokens", "messages", "model"], ["max_tokens", "messages", "model", "stream"])
971 def create(
972 self,
973 *,
974 max_tokens: int,
975 messages: Iterable[MessageParam],
976 model: ModelParam,
977 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
978 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
979 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
980 inference_geo: Optional[str] | Omit = omit,
981 metadata: MetadataParam | Omit = omit,
982 output_config: OutputConfigParam | Omit = omit,
983 service_tier: Literal["auto", "standard_only"] | Omit = omit,
984 stop_sequences: SequenceNotStr[str] | Omit = omit,
985 stream: Literal[False] | Literal[True] | Omit = omit,
986 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
987 thinking: ThinkingConfigParam | Omit = omit,
988 tool_choice: ToolChoiceParam | Omit = omit,
989 tools: Iterable[ToolUnionParam] | Omit = omit,
990 user_profile_id: str | Omit = omit,
991 workspace_id: str | Omit = omit,
992 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
993 # The extra values given here take precedence over values defined on the client or passed to this method.
994 extra_headers: Headers | None = None,
995 extra_query: Query | None = None,
996 extra_body: Body | None = None,
997 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
998 ) -> Message | Stream[RawMessageStreamEvent]:
999 if not stream and not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT:
1000 timeout = self._client._calculate_nonstreaming_timeout(
1001 max_tokens, MODEL_NONSTREAMING_TOKENS.get(model, None)
1002 )
1003
1004 if model in DEPRECATED_MODELS:
1005 warnings.warn(
1006 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.",
1007 DeprecationWarning,
1008 stacklevel=3,
1009 )
1010
1011 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
1012 warnings.warn(
1013 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",
1014 UserWarning,
1015 stacklevel=3,
1016 )
1017
1018 extra_headers = {
1019 **strip_not_given(
1020 {
1021 "anthropic-user-profile-id": user_profile_id,
1022 "anthropic-workspace-id": workspace_id,
1023 }
1024 ),
1025 **(extra_headers or {}),
1026 }
1027 return self._post(
1028 "/v1/messages",
1029 body={
1030 "max_tokens": max_tokens,
1031 "messages": messages,
1032 "model": model,
1033 "cache_control": cache_control,
1034 "container": container,
1035 "diagnostics": diagnostics,
1036 "inference_geo": inference_geo,
1037 "metadata": metadata,
1038 "output_config": output_config,
1039 "service_tier": service_tier,
1040 "stop_sequences": stop_sequences,
1041 "stream": stream,
1042 "system": system,
1043 "thinking": thinking,
1044 "tool_choice": tool_choice,
1045 "tools": tools,
1046 },
1047 options=make_request_options(
1048 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
1049 ),
1050 cast_to=Message,
1051 stream=stream or False,
1052 stream_cls=Stream[RawMessageStreamEvent],
1053 )
1054
1055 def stream(
1056 self,
1057 *,
1058 max_tokens: int,
1059 messages: Iterable[MessageParam],
1060 model: ModelParam,
1061 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
1062 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
1063 inference_geo: Optional[str] | Omit = omit,
1064 metadata: MetadataParam | Omit = omit,
1065 output_config: OutputConfigParam | Omit = omit,
1066 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
1067 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
1068 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1069 stop_sequences: SequenceNotStr[str] | Omit = omit,
1070 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
1071 thinking: ThinkingConfigParam | Omit = omit,
1072 tool_choice: ToolChoiceParam | Omit = omit,
1073 tools: Iterable[ToolUnionParam] | Omit = omit,
1074 user_profile_id: str | Omit = omit,
1075 workspace_id: str | Omit = omit,
1076 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1077 # The extra values given here take precedence over values defined on the client or passed to this method.
1078 extra_headers: Headers | None = None,
1079 extra_query: Query | None = None,
1080 extra_body: Body | None = None,
1081 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1082 ) -> MessageStreamManager[ResponseFormatT]:
1083 """Create a Message stream"""
1084 if model in DEPRECATED_MODELS:
1085 warnings.warn(
1086 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.",
1087 DeprecationWarning,
1088 stacklevel=3,
1089 )
1090
1091 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
1092 warnings.warn(
1093 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",
1094 UserWarning,
1095 stacklevel=3,
1096 )
1097
1098 extra_headers = {
1099 **strip_not_given(
1100 {
1101 "anthropic-user-profile-id": user_profile_id,
1102 "anthropic-workspace-id": workspace_id,
1103 }
1104 ),
1105 _STAINLESS_HELPER_METHOD_HEADER: _HELPER_METHOD_STREAM,
1106 _STAINLESS_STREAM_HELPER_HEADER: "messages",
1107 **(extra_headers or {}),
1108 }
1109
1110 transformed_output_format: Optional[JSONOutputFormatParam] | NotGiven = not_given
1111
1112 if is_given(output_format) and output_format is not None:
1113 if isinstance(output_format, Mapping):
1114 raise TypeError(
1115 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
1116 )
1117 adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format)
1118
1119 try:
1120 schema = adapted_type.json_schema()
1121 transformed_output_format = JSONOutputFormatParam(schema=transform_schema(schema), type="json_schema")
1122 except pydantic.errors.PydanticSchemaGenerationError as e:
1123 raise TypeError(
1124 (
1125 "Could not generate JSON schema for the given `output_format` type. "
1126 "Use a type that works with `pydantic.TypeAdapter`"
1127 )
1128 ) from e
1129
1130 # Merge output_format into output_config
1131 merged_output_config: OutputConfigParam | Omit = omit
1132 if is_given(transformed_output_format):
1133 if is_given(output_config):
1134 merged_output_config = {**output_config, "format": transformed_output_format}
1135 else:
1136 merged_output_config = {"format": transformed_output_format}
1137 elif is_given(output_config):
1138 merged_output_config = output_config
1139
1140 make_request = partial(
1141 self._post,
1142 "/v1/messages",
1143 body={
1144 "max_tokens": max_tokens,
1145 "messages": messages,
1146 "model": model,
1147 "cache_control": cache_control,
1148 "diagnostics": diagnostics,
1149 "inference_geo": inference_geo,
1150 "metadata": metadata,
1151 "output_config": merged_output_config,
1152 "container": container,
1153 "service_tier": service_tier,
1154 "stop_sequences": stop_sequences,
1155 "system": system,
1156 "tools": tools,
1157 "thinking": thinking,
1158 "tool_choice": tool_choice,
1159 "stream": True,
1160 },
1161 options=make_request_options(
1162 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
1163 ),
1164 cast_to=Message,
1165 stream=True,
1166 stream_cls=Stream[RawMessageStreamEvent],
1167 )
1168 return MessageStreamManager(
1169 make_request,
1170 output_format=cast(ResponseFormatT, output_format),
1171 )
1172
1173 def parse(
1174 self,
1175 *,
1176 max_tokens: int,
1177 messages: Iterable[MessageParam],
1178 model: ModelParam,
1179 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
1180 metadata: MetadataParam | Omit = omit,
1181 output_config: OutputConfigParam | Omit = omit,
1182 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
1183 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1184 stop_sequences: SequenceNotStr[str] | Omit = omit,
1185 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
1186 thinking: ThinkingConfigParam | Omit = omit,
1187 tool_choice: ToolChoiceParam | Omit = omit,
1188 tools: Iterable[ToolUnionParam] | Omit = omit,
1189 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1190 # The extra values given here take precedence over values defined on the client or passed to this method.
1191 extra_headers: Headers | None = None,
1192 extra_query: Query | None = None,
1193 extra_body: Body | None = None,
1194 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1195 ) -> ParsedMessage[ResponseFormatT]:
1196 if not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT:
1197 timeout = self._client._calculate_nonstreaming_timeout(
1198 max_tokens, MODEL_NONSTREAMING_TOKENS.get(model, None)
1199 )
1200
1201 if model in DEPRECATED_MODELS:
1202 warnings.warn(
1203 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.",
1204 DeprecationWarning,
1205 stacklevel=3,
1206 )
1207
1208 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
1209 warnings.warn(
1210 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",
1211 UserWarning,
1212 stacklevel=3,
1213 )
1214
1215 extra_headers = merge_headers(
1216 _helper_header("messages.parse"),
1217 extra_headers or {},
1218 )
1219
1220 transformed_output_format: Optional[JSONOutputFormatParam] | NotGiven = not_given
1221
1222 if is_given(output_format) and output_format is not None:
1223 if isinstance(output_format, Mapping):
1224 raise TypeError(
1225 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
1226 )
1227 adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format)
1228
1229 try:
1230 schema = adapted_type.json_schema()
1231 transformed_output_format = JSONOutputFormatParam(schema=transform_schema(schema), type="json_schema")
1232 except pydantic.errors.PydanticSchemaGenerationError as e:
1233 raise TypeError(
1234 (
1235 "Could not generate JSON schema for the given `output_format` type. "
1236 "Use a type that works with `pydantic.TypeAdapter`"
1237 )
1238 ) from e
1239
1240 def parser(response: Message) -> ParsedMessage[ResponseFormatT]:
1241 return parse_response(
1242 response=response,
1243 output_format=cast(
1244 ResponseFormatT,
1245 output_format if is_given(output_format) and output_format is not None else not_given,
1246 ),
1247 )
1248
1249 # Merge output_format into output_config
1250 merged_output_config: OutputConfigParam | Omit = omit
1251 if is_given(transformed_output_format):
1252 if is_given(output_config):
1253 merged_output_config = {**output_config, "format": transformed_output_format}
1254 else:
1255 merged_output_config = {"format": transformed_output_format}
1256 elif is_given(output_config):
1257 merged_output_config = output_config
1258
1259 return self._post(
1260 "/v1/messages",
1261 body={
1262 "max_tokens": max_tokens,
1263 "messages": messages,
1264 "model": model,
1265 "diagnostics": diagnostics,
1266 "metadata": metadata,
1267 "output_config": merged_output_config,
1268 "service_tier": service_tier,
1269 "stop_sequences": stop_sequences,
1270 "system": system,
1271 "thinking": thinking,
1272 "tool_choice": tool_choice,
1273 "tools": tools,
1274 },
1275 options=make_request_options(
1276 extra_headers=extra_headers,
1277 extra_query=extra_query,
1278 extra_body=extra_body,
1279 timeout=timeout,
1280 post_parser=parser,
1281 ),
1282 cast_to=cast(Type[ParsedMessage[ResponseFormatT]], Message),
1283 stream=False,
1284 )
1285
1286 def count_tokens(
1287 self,
1288 *,
1289 messages: Iterable[MessageParam],
1290 model: ModelParam,
1291 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
1292 output_config: OutputConfigParam | Omit = omit,
1293 output_format: Optional[type] | Omit = omit,
1294 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
1295 thinking: ThinkingConfigParam | Omit = omit,
1296 tool_choice: ToolChoiceParam | Omit = omit,
1297 tools: Iterable[MessageCountTokensToolParam] | Omit = omit,
1298 user_profile_id: str | Omit = omit,
1299 workspace_id: str | Omit = omit,
1300 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1301 # The extra values given here take precedence over values defined on the client or passed to this method.
1302 extra_headers: Headers | None = None,
1303 extra_query: Query | None = None,
1304 extra_body: Body | None = None,
1305 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1306 ) -> MessageTokensCount:
1307 """
1308 Count the number of tokens in a Message.
1309
1310 The Token Count API can be used to count the number of tokens in a Message,
1311 including tools, images, and documents, without creating it.
1312
1313 Learn more about token counting in our
1314 [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting)
1315
1316 Args:
1317 messages: Input messages.
1318
1319 Our models are trained to operate on alternating `user` and `assistant`
1320 conversational turns. When creating a new `Message`, you specify the prior
1321 conversational turns with the `messages` parameter, and the model then generates
1322 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
1323 in your request will be combined into a single turn.
1324
1325 Each input message must be an object with a `role` and `content`. You can
1326 specify a single `user`-role message, or you can include multiple `user` and
1327 `assistant` messages.
1328
1329 If the final message uses the `assistant` role, the response content will
1330 continue immediately from the content in that message. This can be used to
1331 constrain part of the model's response.
1332
1333 Example with a single `user` message:
1334
1335 ```json
1336 [{ "role": "user", "content": "Hello, Claude" }]
1337 ```
1338
1339 Example with multiple conversational turns:
1340
1341 ```json
1342 [
1343 { "role": "user", "content": "Hello there." },
1344 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
1345 { "role": "user", "content": "Can you explain LLMs in plain English?" }
1346 ]
1347 ```
1348
1349 Example with a partially-filled response from Claude:
1350
1351 ```json
1352 [
1353 {
1354 "role": "user",
1355 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
1356 },
1357 { "role": "assistant", "content": "The best answer is (" }
1358 ]
1359 ```
1360
1361 Each input message `content` may be either a single `string` or an array of
1362 content blocks, where each block has a specific `type`. Using a `string` for
1363 `content` is shorthand for an array of one content block of type `"text"`. The
1364 following input messages are equivalent:
1365
1366 ```json
1367 { "role": "user", "content": "Hello, Claude" }
1368 ```
1369
1370 ```json
1371 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
1372 ```
1373
1374 See
1375 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
1376
1377 Note that if you want to include a
1378 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
1379 you can use the top-level `system` parameter — there is no `"system"` role for
1380 input messages in the Messages API.
1381
1382 There is a limit of 100,000 messages in a single request.
1383
1384 model: The model that will complete your prompt.
1385
1386 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
1387 details and options.
1388
1389 cache_control: Top-level cache control automatically applies a cache_control marker to the last
1390 cacheable block in the request.
1391
1392 output_config: Configuration options for the model's output, such as the output format.
1393
1394
1395 system: System prompt.
1396
1397 A system prompt is a way of providing context and instructions to Claude, such
1398 as specifying a particular goal or role. See our
1399 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
1400
1401 thinking: Configuration for enabling Claude's extended thinking.
1402
1403 When enabled, responses include `thinking` content blocks showing Claude's
1404 thinking process before the final answer. Requires a minimum budget of 1,024
1405 tokens and counts towards your `max_tokens` limit.
1406
1407 See
1408 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
1409 for details.
1410
1411 tool_choice: How the model should use the provided tools. The model can use a specific tool,
1412 any available tool, decide by itself, or not use tools at all.
1413
1414 tools: Definitions of tools that the model may use.
1415
1416 If you include `tools` in your API request, the model may return `tool_use`
1417 content blocks that represent the model's use of those tools. You can then run
1418 those tools using the tool input generated by the model and then optionally
1419 return results back to the model using `tool_result` content blocks.
1420
1421 There are two types of tools: **client tools** and **server tools**. The
1422 behavior described below applies to client tools. For
1423 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
1424 see their individual documentation as each has its own behavior (e.g., the
1425 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
1426
1427 Each tool definition includes:
1428
1429 - `name`: Name of the tool.
1430 - `description`: Optional, but strongly-recommended description of the tool.
1431 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
1432 tool `input` shape that the model will produce in `tool_use` output content
1433 blocks.
1434
1435 For example, if you defined `tools` as:
1436
1437 ```json
1438 [
1439 {
1440 "name": "get_stock_price",
1441 "description": "Get the current stock price for a given ticker symbol.",
1442 "input_schema": {
1443 "type": "object",
1444 "properties": {
1445 "ticker": {
1446 "type": "string",
1447 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
1448 }
1449 },
1450 "required": ["ticker"]
1451 }
1452 }
1453 ]
1454 ```
1455
1456 And then asked the model "What's the S&P 500 at today?", the model might produce
1457 `tool_use` content blocks in the response like this:
1458
1459 ```json
1460 [
1461 {
1462 "type": "tool_use",
1463 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
1464 "name": "get_stock_price",
1465 "input": { "ticker": "^GSPC" }
1466 }
1467 ]
1468 ```
1469
1470 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
1471 input, and return the following back to the model in a subsequent `user`
1472 message:
1473
1474 ```json
1475 [
1476 {
1477 "type": "tool_result",
1478 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
1479 "content": "259.75 USD"
1480 }
1481 ]
1482 ```
1483
1484 Tools can be used for workflows that include running client-side tools and
1485 functions, or more generally whenever you want the model to produce a particular
1486 JSON structure of output.
1487
1488 See our
1489 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
1490 for more details.
1491
1492 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
1493 party other than your organization. Requires the `user-profiles` beta header.
1494
1495 workspace_id: Optional header to select the Workspace for this request. The value is a
1496 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
1497
1498 Only needed for credentials that can act on more than one Workspace. A
1499 credential that belongs to a specific Workspace may omit it; if sent, it must
1500 match that Workspace.
1501
1502 extra_headers: Send extra headers
1503
1504 extra_query: Add additional query parameters to the request
1505
1506 extra_body: Add additional JSON properties to the request
1507
1508 timeout: Override the client-level default timeout for this request, in seconds
1509 """
1510 extra_headers = {
1511 **strip_not_given(
1512 {
1513 "anthropic-user-profile-id": user_profile_id,
1514 "anthropic-workspace-id": workspace_id,
1515 }
1516 ),
1517 **(extra_headers or {}),
1518 }
1519
1520 # Transform output_format if provided
1521 transformed_output_format: Optional[JSONOutputFormatParam] | NotGiven = not_given
1522
1523 if is_given(output_format) and output_format is not None:
1524 if isinstance(output_format, Mapping):
1525 raise TypeError(
1526 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
1527 )
1528 adapted_type: TypeAdapter[type] = TypeAdapter(output_format)
1529
1530 try:
1531 schema = adapted_type.json_schema()
1532 transformed_output_format = JSONOutputFormatParam(schema=transform_schema(schema), type="json_schema")
1533 except pydantic.errors.PydanticSchemaGenerationError as e:
1534 raise TypeError(
1535 (
1536 "Could not generate JSON schema for the given `output_format` type. "
1537 "Use a type that works with `pydantic.TypeAdapter`"
1538 )
1539 ) from e
1540
1541 # Merge output_format into output_config
1542 merged_output_config: OutputConfigParam | Omit = omit
1543 if is_given(transformed_output_format):
1544 if is_given(output_config):
1545 merged_output_config = {**output_config, "format": transformed_output_format}
1546 else:
1547 merged_output_config = {"format": transformed_output_format}
1548 elif is_given(output_config):
1549 merged_output_config = output_config
1550
1551 return self._post(
1552 "/v1/messages/count_tokens",
1553 body={
1554 "messages": messages,
1555 "model": model,
1556 "cache_control": cache_control,
1557 "output_config": merged_output_config,
1558 "system": system,
1559 "thinking": thinking,
1560 "tool_choice": tool_choice,
1561 "tools": tools,
1562 },
1563 options=make_request_options(
1564 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
1565 ),
1566 cast_to=MessageTokensCount,
1567 )
1568
1569
1570 class AsyncMessages(AsyncAPIResource):
1571 @cached_property
1572 def batches(self) -> AsyncBatches:
1573 return AsyncBatches(self._client)
1574
1575 @cached_property
1576 def with_raw_response(self) -> AsyncMessagesWithRawResponse:
1577 """
1578 This property can be used as a prefix for any HTTP method call to return
1579 the raw response object instead of the parsed content.
1580
1581 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
1582 """
1583 return AsyncMessagesWithRawResponse(self)
1584
1585 @cached_property
1586 def with_streaming_response(self) -> AsyncMessagesWithStreamingResponse:
1587 """
1588 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
1589
1590 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
1591 """
1592 return AsyncMessagesWithStreamingResponse(self)
1593
1594 @overload
1595 async def create(
1596 self,
1597 *,
1598 max_tokens: int,
1599 messages: Iterable[MessageParam],
1600 model: ModelParam,
1601 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
1602 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
1603 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
1604 inference_geo: Optional[str] | Omit = omit,
1605 metadata: MetadataParam | Omit = omit,
1606 output_config: OutputConfigParam | Omit = omit,
1607 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1608 stop_sequences: SequenceNotStr[str] | Omit = omit,
1609 stream: Literal[False] | Omit = omit,
1610 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
1611 thinking: ThinkingConfigParam | Omit = omit,
1612 tool_choice: ToolChoiceParam | Omit = omit,
1613 tools: Iterable[ToolUnionParam] | Omit = omit,
1614 user_profile_id: str | Omit = omit,
1615 workspace_id: str | Omit = omit,
1616 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1617 # The extra values given here take precedence over values defined on the client or passed to this method.
1618 extra_headers: Headers | None = None,
1619 extra_query: Query | None = None,
1620 extra_body: Body | None = None,
1621 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1622 ) -> Message:
1623 """
1624 Send a structured list of input messages with text and/or image content, and the
1625 model will generate the next message in the conversation.
1626
1627 The Messages API can be used for either single queries or stateless multi-turn
1628 conversations.
1629
1630 Learn more about the Messages API in our
1631 [user guide](https://platform.claude.com/docs/en/get-started)
1632
1633 Args:
1634 max_tokens: The maximum number of tokens to generate before stopping.
1635
1636 Note that our models may stop _before_ reaching this maximum. This parameter
1637 only specifies the absolute maximum number of tokens to generate.
1638
1639 Set to `0` to populate the
1640 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
1641 without generating a response.
1642
1643 Different models have different maximum values for this parameter. See
1644 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
1645 details.
1646
1647 messages: Input messages.
1648
1649 Our models are trained to operate on alternating `user` and `assistant`
1650 conversational turns. When creating a new `Message`, you specify the prior
1651 conversational turns with the `messages` parameter, and the model then generates
1652 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
1653 in your request will be combined into a single turn.
1654
1655 Each input message must be an object with a `role` and `content`. You can
1656 specify a single `user`-role message, or you can include multiple `user` and
1657 `assistant` messages.
1658
1659 If the final message uses the `assistant` role, the response content will
1660 continue immediately from the content in that message. This can be used to
1661 constrain part of the model's response.
1662
1663 Example with a single `user` message:
1664
1665 ```json
1666 [{ "role": "user", "content": "Hello, Claude" }]
1667 ```
1668
1669 Example with multiple conversational turns:
1670
1671 ```json
1672 [
1673 { "role": "user", "content": "Hello there." },
1674 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
1675 { "role": "user", "content": "Can you explain LLMs in plain English?" }
1676 ]
1677 ```
1678
1679 Example with a partially-filled response from Claude:
1680
1681 ```json
1682 [
1683 {
1684 "role": "user",
1685 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
1686 },
1687 { "role": "assistant", "content": "The best answer is (" }
1688 ]
1689 ```
1690
1691 Each input message `content` may be either a single `string` or an array of
1692 content blocks, where each block has a specific `type`. Using a `string` for
1693 `content` is shorthand for an array of one content block of type `"text"`. The
1694 following input messages are equivalent:
1695
1696 ```json
1697 { "role": "user", "content": "Hello, Claude" }
1698 ```
1699
1700 ```json
1701 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
1702 ```
1703
1704 See
1705 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
1706
1707 Note that if you want to include a
1708 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
1709 you can use the top-level `system` parameter — there is no `"system"` role for
1710 input messages in the Messages API.
1711
1712 There is a limit of 100,000 messages in a single request.
1713
1714 model: The model that will complete your prompt.
1715
1716 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
1717 details and options.
1718
1719 cache_control: Top-level cache control automatically applies a cache_control marker to the last
1720 cacheable block in the request.
1721
1722 container: Container identifier for reuse across requests.
1723
1724 diagnostics: Request-level diagnostics. Supply `previous_message_id` to have the response
1725 include `diagnostics.cache_miss_reason` explaining any prompt-cache divergence
1726 from that prior request.
1727
1728 inference_geo: Specifies the geographic region for inference processing. If not specified, the
1729 workspace's `default_inference_geo` is used.
1730
1731 metadata: An object describing metadata about the request.
1732
1733 output_config: Configuration options for the model's output, such as the output format.
1734
1735 service_tier: Determines whether to use priority capacity (if available) or standard capacity
1736 for this request.
1737
1738 Anthropic offers different levels of service for your API requests. See
1739 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
1740 details.
1741
1742 stop_sequences: Custom text sequences that will cause the model to stop generating.
1743
1744 Our models will normally stop when they have naturally completed their turn,
1745 which will result in a response `stop_reason` of `"end_turn"`.
1746
1747 If you want the model to stop generating when it encounters custom strings of
1748 text, you can use the `stop_sequences` parameter. If the model encounters one of
1749 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
1750 and the response `stop_sequence` value will contain the matched stop sequence.
1751
1752 stream: Whether to incrementally stream the response using server-sent events. When
1753 `true`, SDKs return a raw event stream.
1754
1755 In the TypeScript, Python and Ruby SDKs, the recommended way to stream is
1756 `messages.stream()`. It sets `stream` for you and accumulates the events into
1757 the final message. See
1758 [Streaming with SDKs](https://platform.claude.com/docs/en/build-with-claude/streaming#streaming-with-sdks)
1759 for an example in each language.
1760
1761 system: System prompt.
1762
1763 A system prompt is a way of providing context and instructions to Claude, such
1764 as specifying a particular goal or role. See our
1765 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
1766
1767 thinking: Configuration for enabling Claude's extended thinking.
1768
1769 When enabled, responses include `thinking` content blocks showing Claude's
1770 thinking process before the final answer. Requires a minimum budget of 1,024
1771 tokens and counts towards your `max_tokens` limit.
1772
1773 See
1774 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
1775 for details.
1776
1777 tool_choice: How the model should use the provided tools. The model can use a specific tool,
1778 any available tool, decide by itself, or not use tools at all.
1779
1780 tools: Definitions of tools that the model may use.
1781
1782 If you include `tools` in your API request, the model may return `tool_use`
1783 content blocks that represent the model's use of those tools. You can then run
1784 those tools using the tool input generated by the model and then optionally
1785 return results back to the model using `tool_result` content blocks.
1786
1787 There are two types of tools: **client tools** and **server tools**. The
1788 behavior described below applies to client tools. For
1789 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
1790 see their individual documentation as each has its own behavior (e.g., the
1791 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
1792
1793 Each tool definition includes:
1794
1795 - `name`: Name of the tool.
1796 - `description`: Optional, but strongly-recommended description of the tool.
1797 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
1798 tool `input` shape that the model will produce in `tool_use` output content
1799 blocks.
1800
1801 For example, if you defined `tools` as:
1802
1803 ```json
1804 [
1805 {
1806 "name": "get_stock_price",
1807 "description": "Get the current stock price for a given ticker symbol.",
1808 "input_schema": {
1809 "type": "object",
1810 "properties": {
1811 "ticker": {
1812 "type": "string",
1813 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
1814 }
1815 },
1816 "required": ["ticker"]
1817 }
1818 }
1819 ]
1820 ```
1821
1822 And then asked the model "What's the S&P 500 at today?", the model might produce
1823 `tool_use` content blocks in the response like this:
1824
1825 ```json
1826 [
1827 {
1828 "type": "tool_use",
1829 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
1830 "name": "get_stock_price",
1831 "input": { "ticker": "^GSPC" }
1832 }
1833 ]
1834 ```
1835
1836 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
1837 input, and return the following back to the model in a subsequent `user`
1838 message:
1839
1840 ```json
1841 [
1842 {
1843 "type": "tool_result",
1844 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
1845 "content": "259.75 USD"
1846 }
1847 ]
1848 ```
1849
1850 Tools can be used for workflows that include running client-side tools and
1851 functions, or more generally whenever you want the model to produce a particular
1852 JSON structure of output.
1853
1854 See our
1855 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
1856 for more details.
1857
1858 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
1859 party other than your organization. Requires the `user-profiles` beta header.
1860
1861 workspace_id: Optional header to select the Workspace for this request. The value is a
1862 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
1863
1864 Only needed for credentials that can act on more than one Workspace. A
1865 credential that belongs to a specific Workspace may omit it; if sent, it must
1866 match that Workspace.
1867
1868 extra_headers: Send extra headers
1869
1870 extra_query: Add additional query parameters to the request
1871
1872 extra_body: Add additional JSON properties to the request
1873
1874 timeout: Override the client-level default timeout for this request, in seconds
1875 """
1876 ...
1877
1878 @overload
1879 async def create(
1880 self,
1881 *,
1882 max_tokens: int,
1883 messages: Iterable[MessageParam],
1884 model: ModelParam,
1885 stream: Literal[True],
1886 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
1887 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
1888 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
1889 inference_geo: Optional[str] | Omit = omit,
1890 metadata: MetadataParam | Omit = omit,
1891 output_config: OutputConfigParam | Omit = omit,
1892 service_tier: Literal["auto", "standard_only"] | Omit = omit,
1893 stop_sequences: SequenceNotStr[str] | Omit = omit,
1894 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
1895 thinking: ThinkingConfigParam | Omit = omit,
1896 tool_choice: ToolChoiceParam | Omit = omit,
1897 tools: Iterable[ToolUnionParam] | Omit = omit,
1898 user_profile_id: str | Omit = omit,
1899 workspace_id: str | Omit = omit,
1900 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1901 # The extra values given here take precedence over values defined on the client or passed to this method.
1902 extra_headers: Headers | None = None,
1903 extra_query: Query | None = None,
1904 extra_body: Body | None = None,
1905 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1906 ) -> AsyncStream[RawMessageStreamEvent]:
1907 """
1908 Send a structured list of input messages with text and/or image content, and the
1909 model will generate the next message in the conversation.
1910
1911 The Messages API can be used for either single queries or stateless multi-turn
1912 conversations.
1913
1914 Learn more about the Messages API in our
1915 [user guide](https://platform.claude.com/docs/en/get-started)
1916
1917 Args:
1918 max_tokens: The maximum number of tokens to generate before stopping.
1919
1920 Note that our models may stop _before_ reaching this maximum. This parameter
1921 only specifies the absolute maximum number of tokens to generate.
1922
1923 Set to `0` to populate the
1924 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
1925 without generating a response.
1926
1927 Different models have different maximum values for this parameter. See
1928 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
1929 details.
1930
1931 messages: Input messages.
1932
1933 Our models are trained to operate on alternating `user` and `assistant`
1934 conversational turns. When creating a new `Message`, you specify the prior
1935 conversational turns with the `messages` parameter, and the model then generates
1936 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
1937 in your request will be combined into a single turn.
1938
1939 Each input message must be an object with a `role` and `content`. You can
1940 specify a single `user`-role message, or you can include multiple `user` and
1941 `assistant` messages.
1942
1943 If the final message uses the `assistant` role, the response content will
1944 continue immediately from the content in that message. This can be used to
1945 constrain part of the model's response.
1946
1947 Example with a single `user` message:
1948
1949 ```json
1950 [{ "role": "user", "content": "Hello, Claude" }]
1951 ```
1952
1953 Example with multiple conversational turns:
1954
1955 ```json
1956 [
1957 { "role": "user", "content": "Hello there." },
1958 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
1959 { "role": "user", "content": "Can you explain LLMs in plain English?" }
1960 ]
1961 ```
1962
1963 Example with a partially-filled response from Claude:
1964
1965 ```json
1966 [
1967 {
1968 "role": "user",
1969 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
1970 },
1971 { "role": "assistant", "content": "The best answer is (" }
1972 ]
1973 ```
1974
1975 Each input message `content` may be either a single `string` or an array of
1976 content blocks, where each block has a specific `type`. Using a `string` for
1977 `content` is shorthand for an array of one content block of type `"text"`. The
1978 following input messages are equivalent:
1979
1980 ```json
1981 { "role": "user", "content": "Hello, Claude" }
1982 ```
1983
1984 ```json
1985 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
1986 ```
1987
1988 See
1989 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
1990
1991 Note that if you want to include a
1992 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
1993 you can use the top-level `system` parameter — there is no `"system"` role for
1994 input messages in the Messages API.
1995
1996 There is a limit of 100,000 messages in a single request.
1997
1998 model: The model that will complete your prompt.
1999
2000 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
2001 details and options.
2002
2003 stream: Whether to incrementally stream the response using server-sent events. When
2004 `true`, SDKs return a raw event stream.
2005
2006 In the TypeScript, Python and Ruby SDKs, the recommended way to stream is
2007 `messages.stream()`. It sets `stream` for you and accumulates the events into
2008 the final message. See
2009 [Streaming with SDKs](https://platform.claude.com/docs/en/build-with-claude/streaming#streaming-with-sdks)
2010 for an example in each language.
2011
2012 cache_control: Top-level cache control automatically applies a cache_control marker to the last
2013 cacheable block in the request.
2014
2015 container: Container identifier for reuse across requests.
2016
2017 diagnostics: Request-level diagnostics. Supply `previous_message_id` to have the response
2018 include `diagnostics.cache_miss_reason` explaining any prompt-cache divergence
2019 from that prior request.
2020
2021 inference_geo: Specifies the geographic region for inference processing. If not specified, the
2022 workspace's `default_inference_geo` is used.
2023
2024 metadata: An object describing metadata about the request.
2025
2026 output_config: Configuration options for the model's output, such as the output format.
2027
2028 service_tier: Determines whether to use priority capacity (if available) or standard capacity
2029 for this request.
2030
2031 Anthropic offers different levels of service for your API requests. See
2032 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
2033 details.
2034
2035 stop_sequences: Custom text sequences that will cause the model to stop generating.
2036
2037 Our models will normally stop when they have naturally completed their turn,
2038 which will result in a response `stop_reason` of `"end_turn"`.
2039
2040 If you want the model to stop generating when it encounters custom strings of
2041 text, you can use the `stop_sequences` parameter. If the model encounters one of
2042 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
2043 and the response `stop_sequence` value will contain the matched stop sequence.
2044
2045 system: System prompt.
2046
2047 A system prompt is a way of providing context and instructions to Claude, such
2048 as specifying a particular goal or role. See our
2049 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
2050
2051 thinking: Configuration for enabling Claude's extended thinking.
2052
2053 When enabled, responses include `thinking` content blocks showing Claude's
2054 thinking process before the final answer. Requires a minimum budget of 1,024
2055 tokens and counts towards your `max_tokens` limit.
2056
2057 See
2058 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
2059 for details.
2060
2061 tool_choice: How the model should use the provided tools. The model can use a specific tool,
2062 any available tool, decide by itself, or not use tools at all.
2063
2064 tools: Definitions of tools that the model may use.
2065
2066 If you include `tools` in your API request, the model may return `tool_use`
2067 content blocks that represent the model's use of those tools. You can then run
2068 those tools using the tool input generated by the model and then optionally
2069 return results back to the model using `tool_result` content blocks.
2070
2071 There are two types of tools: **client tools** and **server tools**. The
2072 behavior described below applies to client tools. For
2073 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
2074 see their individual documentation as each has its own behavior (e.g., the
2075 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
2076
2077 Each tool definition includes:
2078
2079 - `name`: Name of the tool.
2080 - `description`: Optional, but strongly-recommended description of the tool.
2081 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
2082 tool `input` shape that the model will produce in `tool_use` output content
2083 blocks.
2084
2085 For example, if you defined `tools` as:
2086
2087 ```json
2088 [
2089 {
2090 "name": "get_stock_price",
2091 "description": "Get the current stock price for a given ticker symbol.",
2092 "input_schema": {
2093 "type": "object",
2094 "properties": {
2095 "ticker": {
2096 "type": "string",
2097 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
2098 }
2099 },
2100 "required": ["ticker"]
2101 }
2102 }
2103 ]
2104 ```
2105
2106 And then asked the model "What's the S&P 500 at today?", the model might produce
2107 `tool_use` content blocks in the response like this:
2108
2109 ```json
2110 [
2111 {
2112 "type": "tool_use",
2113 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2114 "name": "get_stock_price",
2115 "input": { "ticker": "^GSPC" }
2116 }
2117 ]
2118 ```
2119
2120 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
2121 input, and return the following back to the model in a subsequent `user`
2122 message:
2123
2124 ```json
2125 [
2126 {
2127 "type": "tool_result",
2128 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2129 "content": "259.75 USD"
2130 }
2131 ]
2132 ```
2133
2134 Tools can be used for workflows that include running client-side tools and
2135 functions, or more generally whenever you want the model to produce a particular
2136 JSON structure of output.
2137
2138 See our
2139 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
2140 for more details.
2141
2142 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
2143 party other than your organization. Requires the `user-profiles` beta header.
2144
2145 workspace_id: Optional header to select the Workspace for this request. The value is a
2146 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
2147
2148 Only needed for credentials that can act on more than one Workspace. A
2149 credential that belongs to a specific Workspace may omit it; if sent, it must
2150 match that Workspace.
2151
2152 extra_headers: Send extra headers
2153
2154 extra_query: Add additional query parameters to the request
2155
2156 extra_body: Add additional JSON properties to the request
2157
2158 timeout: Override the client-level default timeout for this request, in seconds
2159 """
2160 ...
2161
2162 @overload
2163 async def create(
2164 self,
2165 *,
2166 max_tokens: int,
2167 messages: Iterable[MessageParam],
2168 model: ModelParam,
2169 stream: bool,
2170 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
2171 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
2172 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
2173 inference_geo: Optional[str] | Omit = omit,
2174 metadata: MetadataParam | Omit = omit,
2175 output_config: OutputConfigParam | Omit = omit,
2176 service_tier: Literal["auto", "standard_only"] | Omit = omit,
2177 stop_sequences: SequenceNotStr[str] | Omit = omit,
2178 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
2179 thinking: ThinkingConfigParam | Omit = omit,
2180 tool_choice: ToolChoiceParam | Omit = omit,
2181 tools: Iterable[ToolUnionParam] | Omit = omit,
2182 user_profile_id: str | Omit = omit,
2183 workspace_id: str | Omit = omit,
2184 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
2185 # The extra values given here take precedence over values defined on the client or passed to this method.
2186 extra_headers: Headers | None = None,
2187 extra_query: Query | None = None,
2188 extra_body: Body | None = None,
2189 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
2190 ) -> Message | AsyncStream[RawMessageStreamEvent]:
2191 """
2192 Send a structured list of input messages with text and/or image content, and the
2193 model will generate the next message in the conversation.
2194
2195 The Messages API can be used for either single queries or stateless multi-turn
2196 conversations.
2197
2198 Learn more about the Messages API in our
2199 [user guide](https://platform.claude.com/docs/en/get-started)
2200
2201 Args:
2202 max_tokens: The maximum number of tokens to generate before stopping.
2203
2204 Note that our models may stop _before_ reaching this maximum. This parameter
2205 only specifies the absolute maximum number of tokens to generate.
2206
2207 Set to `0` to populate the
2208 [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pre-warming-the-cache)
2209 without generating a response.
2210
2211 Different models have different maximum values for this parameter. See
2212 [models](https://platform.claude.com/docs/en/about-claude/models/overview) for
2213 details.
2214
2215 messages: Input messages.
2216
2217 Our models are trained to operate on alternating `user` and `assistant`
2218 conversational turns. When creating a new `Message`, you specify the prior
2219 conversational turns with the `messages` parameter, and the model then generates
2220 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
2221 in your request will be combined into a single turn.
2222
2223 Each input message must be an object with a `role` and `content`. You can
2224 specify a single `user`-role message, or you can include multiple `user` and
2225 `assistant` messages.
2226
2227 If the final message uses the `assistant` role, the response content will
2228 continue immediately from the content in that message. This can be used to
2229 constrain part of the model's response.
2230
2231 Example with a single `user` message:
2232
2233 ```json
2234 [{ "role": "user", "content": "Hello, Claude" }]
2235 ```
2236
2237 Example with multiple conversational turns:
2238
2239 ```json
2240 [
2241 { "role": "user", "content": "Hello there." },
2242 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
2243 { "role": "user", "content": "Can you explain LLMs in plain English?" }
2244 ]
2245 ```
2246
2247 Example with a partially-filled response from Claude:
2248
2249 ```json
2250 [
2251 {
2252 "role": "user",
2253 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
2254 },
2255 { "role": "assistant", "content": "The best answer is (" }
2256 ]
2257 ```
2258
2259 Each input message `content` may be either a single `string` or an array of
2260 content blocks, where each block has a specific `type`. Using a `string` for
2261 `content` is shorthand for an array of one content block of type `"text"`. The
2262 following input messages are equivalent:
2263
2264 ```json
2265 { "role": "user", "content": "Hello, Claude" }
2266 ```
2267
2268 ```json
2269 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
2270 ```
2271
2272 See
2273 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
2274
2275 Note that if you want to include a
2276 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
2277 you can use the top-level `system` parameter — there is no `"system"` role for
2278 input messages in the Messages API.
2279
2280 There is a limit of 100,000 messages in a single request.
2281
2282 model: The model that will complete your prompt.
2283
2284 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
2285 details and options.
2286
2287 stream: Whether to incrementally stream the response using server-sent events. When
2288 `true`, SDKs return a raw event stream.
2289
2290 In the TypeScript, Python and Ruby SDKs, the recommended way to stream is
2291 `messages.stream()`. It sets `stream` for you and accumulates the events into
2292 the final message. See
2293 [Streaming with SDKs](https://platform.claude.com/docs/en/build-with-claude/streaming#streaming-with-sdks)
2294 for an example in each language.
2295
2296 cache_control: Top-level cache control automatically applies a cache_control marker to the last
2297 cacheable block in the request.
2298
2299 container: Container identifier for reuse across requests.
2300
2301 diagnostics: Request-level diagnostics. Supply `previous_message_id` to have the response
2302 include `diagnostics.cache_miss_reason` explaining any prompt-cache divergence
2303 from that prior request.
2304
2305 inference_geo: Specifies the geographic region for inference processing. If not specified, the
2306 workspace's `default_inference_geo` is used.
2307
2308 metadata: An object describing metadata about the request.
2309
2310 output_config: Configuration options for the model's output, such as the output format.
2311
2312 service_tier: Determines whether to use priority capacity (if available) or standard capacity
2313 for this request.
2314
2315 Anthropic offers different levels of service for your API requests. See
2316 [service-tiers](https://platform.claude.com/docs/en/api/service-tiers) for
2317 details.
2318
2319 stop_sequences: Custom text sequences that will cause the model to stop generating.
2320
2321 Our models will normally stop when they have naturally completed their turn,
2322 which will result in a response `stop_reason` of `"end_turn"`.
2323
2324 If you want the model to stop generating when it encounters custom strings of
2325 text, you can use the `stop_sequences` parameter. If the model encounters one of
2326 the custom sequences, the response `stop_reason` value will be `"stop_sequence"`
2327 and the response `stop_sequence` value will contain the matched stop sequence.
2328
2329 system: System prompt.
2330
2331 A system prompt is a way of providing context and instructions to Claude, such
2332 as specifying a particular goal or role. See our
2333 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
2334
2335 thinking: Configuration for enabling Claude's extended thinking.
2336
2337 When enabled, responses include `thinking` content blocks showing Claude's
2338 thinking process before the final answer. Requires a minimum budget of 1,024
2339 tokens and counts towards your `max_tokens` limit.
2340
2341 See
2342 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
2343 for details.
2344
2345 tool_choice: How the model should use the provided tools. The model can use a specific tool,
2346 any available tool, decide by itself, or not use tools at all.
2347
2348 tools: Definitions of tools that the model may use.
2349
2350 If you include `tools` in your API request, the model may return `tool_use`
2351 content blocks that represent the model's use of those tools. You can then run
2352 those tools using the tool input generated by the model and then optionally
2353 return results back to the model using `tool_result` content blocks.
2354
2355 There are two types of tools: **client tools** and **server tools**. The
2356 behavior described below applies to client tools. For
2357 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
2358 see their individual documentation as each has its own behavior (e.g., the
2359 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
2360
2361 Each tool definition includes:
2362
2363 - `name`: Name of the tool.
2364 - `description`: Optional, but strongly-recommended description of the tool.
2365 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
2366 tool `input` shape that the model will produce in `tool_use` output content
2367 blocks.
2368
2369 For example, if you defined `tools` as:
2370
2371 ```json
2372 [
2373 {
2374 "name": "get_stock_price",
2375 "description": "Get the current stock price for a given ticker symbol.",
2376 "input_schema": {
2377 "type": "object",
2378 "properties": {
2379 "ticker": {
2380 "type": "string",
2381 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
2382 }
2383 },
2384 "required": ["ticker"]
2385 }
2386 }
2387 ]
2388 ```
2389
2390 And then asked the model "What's the S&P 500 at today?", the model might produce
2391 `tool_use` content blocks in the response like this:
2392
2393 ```json
2394 [
2395 {
2396 "type": "tool_use",
2397 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2398 "name": "get_stock_price",
2399 "input": { "ticker": "^GSPC" }
2400 }
2401 ]
2402 ```
2403
2404 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
2405 input, and return the following back to the model in a subsequent `user`
2406 message:
2407
2408 ```json
2409 [
2410 {
2411 "type": "tool_result",
2412 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2413 "content": "259.75 USD"
2414 }
2415 ]
2416 ```
2417
2418 Tools can be used for workflows that include running client-side tools and
2419 functions, or more generally whenever you want the model to produce a particular
2420 JSON structure of output.
2421
2422 See our
2423 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
2424 for more details.
2425
2426 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
2427 party other than your organization. Requires the `user-profiles` beta header.
2428
2429 workspace_id: Optional header to select the Workspace for this request. The value is a
2430 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
2431
2432 Only needed for credentials that can act on more than one Workspace. A
2433 credential that belongs to a specific Workspace may omit it; if sent, it must
2434 match that Workspace.
2435
2436 extra_headers: Send extra headers
2437
2438 extra_query: Add additional query parameters to the request
2439
2440 extra_body: Add additional JSON properties to the request
2441
2442 timeout: Override the client-level default timeout for this request, in seconds
2443 """
2444 ...
2445
2446 @required_args(["max_tokens", "messages", "model"], ["max_tokens", "messages", "model", "stream"])
2447 async def create(
2448 self,
2449 *,
2450 max_tokens: int,
2451 messages: Iterable[MessageParam],
2452 model: ModelParam,
2453 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
2454 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
2455 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
2456 inference_geo: Optional[str] | Omit = omit,
2457 metadata: MetadataParam | Omit = omit,
2458 output_config: OutputConfigParam | Omit = omit,
2459 service_tier: Literal["auto", "standard_only"] | Omit = omit,
2460 stop_sequences: SequenceNotStr[str] | Omit = omit,
2461 stream: Literal[False] | Literal[True] | Omit = omit,
2462 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
2463 thinking: ThinkingConfigParam | Omit = omit,
2464 tool_choice: ToolChoiceParam | Omit = omit,
2465 tools: Iterable[ToolUnionParam] | Omit = omit,
2466 user_profile_id: str | Omit = omit,
2467 workspace_id: str | Omit = omit,
2468 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
2469 # The extra values given here take precedence over values defined on the client or passed to this method.
2470 extra_headers: Headers | None = None,
2471 extra_query: Query | None = None,
2472 extra_body: Body | None = None,
2473 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
2474 ) -> Message | AsyncStream[RawMessageStreamEvent]:
2475 if not stream and not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT:
2476 timeout = self._client._calculate_nonstreaming_timeout(
2477 max_tokens, MODEL_NONSTREAMING_TOKENS.get(model, None)
2478 )
2479
2480 if model in DEPRECATED_MODELS:
2481 warnings.warn(
2482 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.",
2483 DeprecationWarning,
2484 stacklevel=3,
2485 )
2486
2487 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
2488 warnings.warn(
2489 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",
2490 UserWarning,
2491 stacklevel=3,
2492 )
2493
2494 extra_headers = {
2495 **strip_not_given(
2496 {
2497 "anthropic-user-profile-id": user_profile_id,
2498 "anthropic-workspace-id": workspace_id,
2499 }
2500 ),
2501 **(extra_headers or {}),
2502 }
2503 return await self._post(
2504 "/v1/messages",
2505 body={
2506 "max_tokens": max_tokens,
2507 "messages": messages,
2508 "model": model,
2509 "cache_control": cache_control,
2510 "container": container,
2511 "diagnostics": diagnostics,
2512 "inference_geo": inference_geo,
2513 "metadata": metadata,
2514 "output_config": output_config,
2515 "service_tier": service_tier,
2516 "stop_sequences": stop_sequences,
2517 "stream": stream,
2518 "system": system,
2519 "thinking": thinking,
2520 "tool_choice": tool_choice,
2521 "tools": tools,
2522 },
2523 options=make_request_options(
2524 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
2525 ),
2526 cast_to=Message,
2527 stream=stream or False,
2528 stream_cls=AsyncStream[RawMessageStreamEvent],
2529 )
2530
2531 def stream(
2532 self,
2533 *,
2534 max_tokens: int,
2535 messages: Iterable[MessageParam],
2536 model: ModelParam,
2537 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
2538 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
2539 inference_geo: Optional[str] | Omit = omit,
2540 metadata: MetadataParam | Omit = omit,
2541 output_config: OutputConfigParam | Omit = omit,
2542 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
2543 container: Optional[MessageCreateParamsContainerParam] | Omit = omit,
2544 service_tier: Literal["auto", "standard_only"] | Omit = omit,
2545 stop_sequences: SequenceNotStr[str] | Omit = omit,
2546 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
2547 thinking: ThinkingConfigParam | Omit = omit,
2548 tool_choice: ToolChoiceParam | Omit = omit,
2549 tools: Iterable[ToolUnionParam] | Omit = omit,
2550 user_profile_id: str | Omit = omit,
2551 workspace_id: str | Omit = omit,
2552 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
2553 # The extra values given here take precedence over values defined on the client or passed to this method.
2554 extra_headers: Headers | None = None,
2555 extra_query: Query | None = None,
2556 extra_body: Body | None = None,
2557 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
2558 ) -> AsyncMessageStreamManager[ResponseFormatT]:
2559 """Create a Message stream"""
2560 if model in DEPRECATED_MODELS:
2561 warnings.warn(
2562 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.",
2563 DeprecationWarning,
2564 stacklevel=3,
2565 )
2566
2567 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
2568 warnings.warn(
2569 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",
2570 UserWarning,
2571 stacklevel=3,
2572 )
2573
2574 extra_headers = {
2575 **strip_not_given(
2576 {
2577 "anthropic-user-profile-id": user_profile_id,
2578 "anthropic-workspace-id": workspace_id,
2579 }
2580 ),
2581 _STAINLESS_HELPER_METHOD_HEADER: _HELPER_METHOD_STREAM,
2582 _STAINLESS_STREAM_HELPER_HEADER: "messages",
2583 **(extra_headers or {}),
2584 }
2585
2586 transformed_output_format: Optional[JSONOutputFormatParam] | NotGiven = not_given
2587
2588 if is_given(output_format) and output_format is not None:
2589 if isinstance(output_format, Mapping):
2590 raise TypeError(
2591 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
2592 )
2593 adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format)
2594
2595 try:
2596 schema = adapted_type.json_schema()
2597 transformed_output_format = JSONOutputFormatParam(schema=transform_schema(schema), type="json_schema")
2598 except pydantic.errors.PydanticSchemaGenerationError as e:
2599 raise TypeError(
2600 (
2601 "Could not generate JSON schema for the given `output_format` type. "
2602 "Use a type that works with `pydantic.TypeAdapter`"
2603 )
2604 ) from e
2605
2606 # Merge output_format into output_config
2607 merged_output_config: OutputConfigParam | Omit = omit
2608 if is_given(transformed_output_format):
2609 if is_given(output_config):
2610 merged_output_config = {**output_config, "format": transformed_output_format}
2611 else:
2612 merged_output_config = {"format": transformed_output_format}
2613 elif is_given(output_config):
2614 merged_output_config = output_config
2615
2616 request = self._post(
2617 "/v1/messages",
2618 body={
2619 "max_tokens": max_tokens,
2620 "messages": messages,
2621 "model": model,
2622 "cache_control": cache_control,
2623 "diagnostics": diagnostics,
2624 "inference_geo": inference_geo,
2625 "metadata": metadata,
2626 "output_config": merged_output_config,
2627 "container": container,
2628 "service_tier": service_tier,
2629 "stop_sequences": stop_sequences,
2630 "system": system,
2631 "tools": tools,
2632 "thinking": thinking,
2633 "tool_choice": tool_choice,
2634 "stream": True,
2635 },
2636 options=make_request_options(
2637 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
2638 ),
2639 cast_to=Message,
2640 stream=True,
2641 stream_cls=AsyncStream[RawMessageStreamEvent],
2642 )
2643 return AsyncMessageStreamManager(
2644 request,
2645 output_format=cast(ResponseFormatT, output_format),
2646 )
2647
2648 async def parse(
2649 self,
2650 *,
2651 max_tokens: int,
2652 messages: Iterable[MessageParam],
2653 model: ModelParam,
2654 diagnostics: Optional[DiagnosticsParam] | Omit = omit,
2655 metadata: MetadataParam | Omit = omit,
2656 output_config: OutputConfigParam | Omit = omit,
2657 output_format: Optional[type[ResponseFormatT]] | Omit = omit,
2658 service_tier: Literal["auto", "standard_only"] | Omit = omit,
2659 stop_sequences: SequenceNotStr[str] | Omit = omit,
2660 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
2661 thinking: ThinkingConfigParam | Omit = omit,
2662 tool_choice: ToolChoiceParam | Omit = omit,
2663 tools: Iterable[ToolUnionParam] | Omit = omit,
2664 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
2665 # The extra values given here take precedence over values defined on the client or passed to this method.
2666 extra_headers: Headers | None = None,
2667 extra_query: Query | None = None,
2668 extra_body: Body | None = None,
2669 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
2670 ) -> ParsedMessage[ResponseFormatT]:
2671 if not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT:
2672 timeout = self._client._calculate_nonstreaming_timeout(
2673 max_tokens, MODEL_NONSTREAMING_TOKENS.get(model, None)
2674 )
2675
2676 if model in DEPRECATED_MODELS:
2677 warnings.warn(
2678 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.",
2679 DeprecationWarning,
2680 stacklevel=3,
2681 )
2682
2683 if model in MODELS_TO_WARN_WITH_THINKING_ENABLED and thinking and thinking["type"] == "enabled":
2684 warnings.warn(
2685 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",
2686 UserWarning,
2687 stacklevel=3,
2688 )
2689
2690 extra_headers = merge_headers(
2691 _helper_header("messages.parse"),
2692 extra_headers or {},
2693 )
2694
2695 transformed_output_format: Optional[JSONOutputFormatParam] | NotGiven = not_given
2696
2697 if is_given(output_format) and output_format is not None:
2698 if isinstance(output_format, Mapping):
2699 raise TypeError(
2700 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
2701 )
2702 adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format)
2703
2704 try:
2705 schema = adapted_type.json_schema()
2706 transformed_output_format = JSONOutputFormatParam(schema=transform_schema(schema), type="json_schema")
2707 except pydantic.errors.PydanticSchemaGenerationError as e:
2708 raise TypeError(
2709 (
2710 "Could not generate JSON schema for the given `output_format` type. "
2711 "Use a type that works with `pydantic.TypeAdapter`"
2712 )
2713 ) from e
2714
2715 def parser(response: Message) -> ParsedMessage[ResponseFormatT]:
2716 return parse_response(
2717 response=response,
2718 output_format=cast(
2719 ResponseFormatT,
2720 output_format if is_given(output_format) and output_format is not None else not_given,
2721 ),
2722 )
2723
2724 # Merge output_format into output_config
2725 merged_output_config: OutputConfigParam | Omit = omit
2726 if is_given(transformed_output_format):
2727 if is_given(output_config):
2728 merged_output_config = {**output_config, "format": transformed_output_format}
2729 else:
2730 merged_output_config = {"format": transformed_output_format}
2731 elif is_given(output_config):
2732 merged_output_config = output_config
2733
2734 return await self._post(
2735 "/v1/messages",
2736 body={
2737 "max_tokens": max_tokens,
2738 "messages": messages,
2739 "model": model,
2740 "diagnostics": diagnostics,
2741 "metadata": metadata,
2742 "output_config": merged_output_config,
2743 "service_tier": service_tier,
2744 "stop_sequences": stop_sequences,
2745 "system": system,
2746 "thinking": thinking,
2747 "tool_choice": tool_choice,
2748 "tools": tools,
2749 },
2750 options=make_request_options(
2751 extra_headers=extra_headers,
2752 extra_query=extra_query,
2753 extra_body=extra_body,
2754 timeout=timeout,
2755 post_parser=parser,
2756 ),
2757 cast_to=cast(Type[ParsedMessage[ResponseFormatT]], Message),
2758 stream=False,
2759 )
2760
2761 async def count_tokens(
2762 self,
2763 *,
2764 messages: Iterable[MessageParam],
2765 model: ModelParam,
2766 cache_control: Optional[CacheControlEphemeralParam] | Omit = omit,
2767 output_config: OutputConfigParam | Omit = omit,
2768 output_format: Optional[type] | Omit = omit,
2769 system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
2770 thinking: ThinkingConfigParam | Omit = omit,
2771 tool_choice: ToolChoiceParam | Omit = omit,
2772 tools: Iterable[MessageCountTokensToolParam] | Omit = omit,
2773 user_profile_id: str | Omit = omit,
2774 workspace_id: str | Omit = omit,
2775 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
2776 # The extra values given here take precedence over values defined on the client or passed to this method.
2777 extra_headers: Headers | None = None,
2778 extra_query: Query | None = None,
2779 extra_body: Body | None = None,
2780 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
2781 ) -> MessageTokensCount:
2782 """
2783 Count the number of tokens in a Message.
2784
2785 The Token Count API can be used to count the number of tokens in a Message,
2786 including tools, images, and documents, without creating it.
2787
2788 Learn more about token counting in our
2789 [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting)
2790
2791 Args:
2792 messages: Input messages.
2793
2794 Our models are trained to operate on alternating `user` and `assistant`
2795 conversational turns. When creating a new `Message`, you specify the prior
2796 conversational turns with the `messages` parameter, and the model then generates
2797 the next `Message` in the conversation. Consecutive `user` or `assistant` turns
2798 in your request will be combined into a single turn.
2799
2800 Each input message must be an object with a `role` and `content`. You can
2801 specify a single `user`-role message, or you can include multiple `user` and
2802 `assistant` messages.
2803
2804 If the final message uses the `assistant` role, the response content will
2805 continue immediately from the content in that message. This can be used to
2806 constrain part of the model's response.
2807
2808 Example with a single `user` message:
2809
2810 ```json
2811 [{ "role": "user", "content": "Hello, Claude" }]
2812 ```
2813
2814 Example with multiple conversational turns:
2815
2816 ```json
2817 [
2818 { "role": "user", "content": "Hello there." },
2819 { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
2820 { "role": "user", "content": "Can you explain LLMs in plain English?" }
2821 ]
2822 ```
2823
2824 Example with a partially-filled response from Claude:
2825
2826 ```json
2827 [
2828 {
2829 "role": "user",
2830 "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"
2831 },
2832 { "role": "assistant", "content": "The best answer is (" }
2833 ]
2834 ```
2835
2836 Each input message `content` may be either a single `string` or an array of
2837 content blocks, where each block has a specific `type`. Using a `string` for
2838 `content` is shorthand for an array of one content block of type `"text"`. The
2839 following input messages are equivalent:
2840
2841 ```json
2842 { "role": "user", "content": "Hello, Claude" }
2843 ```
2844
2845 ```json
2846 { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] }
2847 ```
2848
2849 See
2850 [input examples](https://platform.claude.com/docs/en/build-with-claude/working-with-messages).
2851
2852 Note that if you want to include a
2853 [system prompt](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role),
2854 you can use the top-level `system` parameter — there is no `"system"` role for
2855 input messages in the Messages API.
2856
2857 There is a limit of 100,000 messages in a single request.
2858
2859 model: The model that will complete your prompt.
2860
2861 See [models](https://docs.anthropic.com/en/docs/models-overview) for additional
2862 details and options.
2863
2864 cache_control: Top-level cache control automatically applies a cache_control marker to the last
2865 cacheable block in the request.
2866
2867 output_config: Configuration options for the model's output, such as the output format.
2868
2869
2870 system: System prompt.
2871
2872 A system prompt is a way of providing context and instructions to Claude, such
2873 as specifying a particular goal or role. See our
2874 [guide to system prompts](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#give-claude-a-role).
2875
2876 thinking: Configuration for enabling Claude's extended thinking.
2877
2878 When enabled, responses include `thinking` content blocks showing Claude's
2879 thinking process before the final answer. Requires a minimum budget of 1,024
2880 tokens and counts towards your `max_tokens` limit.
2881
2882 See
2883 [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)
2884 for details.
2885
2886 tool_choice: How the model should use the provided tools. The model can use a specific tool,
2887 any available tool, decide by itself, or not use tools at all.
2888
2889 tools: Definitions of tools that the model may use.
2890
2891 If you include `tools` in your API request, the model may return `tool_use`
2892 content blocks that represent the model's use of those tools. You can then run
2893 those tools using the tool input generated by the model and then optionally
2894 return results back to the model using `tool_result` content blocks.
2895
2896 There are two types of tools: **client tools** and **server tools**. The
2897 behavior described below applies to client tools. For
2898 [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools),
2899 see their individual documentation as each has its own behavior (e.g., the
2900 [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)).
2901
2902 Each tool definition includes:
2903
2904 - `name`: Name of the tool.
2905 - `description`: Optional, but strongly-recommended description of the tool.
2906 - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the
2907 tool `input` shape that the model will produce in `tool_use` output content
2908 blocks.
2909
2910 For example, if you defined `tools` as:
2911
2912 ```json
2913 [
2914 {
2915 "name": "get_stock_price",
2916 "description": "Get the current stock price for a given ticker symbol.",
2917 "input_schema": {
2918 "type": "object",
2919 "properties": {
2920 "ticker": {
2921 "type": "string",
2922 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
2923 }
2924 },
2925 "required": ["ticker"]
2926 }
2927 }
2928 ]
2929 ```
2930
2931 And then asked the model "What's the S&P 500 at today?", the model might produce
2932 `tool_use` content blocks in the response like this:
2933
2934 ```json
2935 [
2936 {
2937 "type": "tool_use",
2938 "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2939 "name": "get_stock_price",
2940 "input": { "ticker": "^GSPC" }
2941 }
2942 ]
2943 ```
2944
2945 You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an
2946 input, and return the following back to the model in a subsequent `user`
2947 message:
2948
2949 ```json
2950 [
2951 {
2952 "type": "tool_result",
2953 "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
2954 "content": "259.75 USD"
2955 }
2956 ]
2957 ```
2958
2959 Tools can be used for workflows that include running client-side tools and
2960 functions, or more generally whenever you want the model to produce a particular
2961 JSON structure of output.
2962
2963 See our
2964 [guide](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
2965 for more details.
2966
2967 user_profile_id: The user profile ID to attribute this request to. Use when acting on behalf of a
2968 party other than your organization. Requires the `user-profiles` beta header.
2969
2970 workspace_id: Optional header to select the Workspace for this request. The value is a
2971 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
2972
2973 Only needed for credentials that can act on more than one Workspace. A
2974 credential that belongs to a specific Workspace may omit it; if sent, it must
2975 match that Workspace.
2976
2977 extra_headers: Send extra headers
2978
2979 extra_query: Add additional query parameters to the request
2980
2981 extra_body: Add additional JSON properties to the request
2982
2983 timeout: Override the client-level default timeout for this request, in seconds
2984 """
2985 extra_headers = {
2986 **strip_not_given(
2987 {
2988 "anthropic-user-profile-id": user_profile_id,
2989 "anthropic-workspace-id": workspace_id,
2990 }
2991 ),
2992 **(extra_headers or {}),
2993 }
2994
2995 # Transform output_format if provided
2996 transformed_output_format: Optional[JSONOutputFormatParam] | NotGiven = not_given
2997
2998 if is_given(output_format) and output_format is not None:
2999 if isinstance(output_format, Mapping):
3000 raise TypeError(
3001 "`output_format` must be a type; pass a schema dict as `output_config={'format': ...}` instead"
3002 )
3003 adapted_type: TypeAdapter[type] = TypeAdapter(output_format)
3004
3005 try:
3006 schema = adapted_type.json_schema()
3007 transformed_output_format = JSONOutputFormatParam(schema=transform_schema(schema), type="json_schema")
3008 except pydantic.errors.PydanticSchemaGenerationError as e:
3009 raise TypeError(
3010 (
3011 "Could not generate JSON schema for the given `output_format` type. "
3012 "Use a type that works with `pydantic.TypeAdapter`"
3013 )
3014 ) from e
3015
3016 # Merge output_format into output_config
3017 merged_output_config: OutputConfigParam | Omit = omit
3018 if is_given(transformed_output_format):
3019 if is_given(output_config):
3020 merged_output_config = {**output_config, "format": transformed_output_format}
3021 else:
3022 merged_output_config = {"format": transformed_output_format}
3023 elif is_given(output_config):
3024 merged_output_config = output_config
3025
3026 return await self._post(
3027 "/v1/messages/count_tokens",
3028 body={
3029 "messages": messages,
3030 "model": model,
3031 "cache_control": cache_control,
3032 "output_config": merged_output_config,
3033 "system": system,
3034 "thinking": thinking,
3035 "tool_choice": tool_choice,
3036 "tools": tools,
3037 },
3038 options=make_request_options(
3039 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
3040 ),
3041 cast_to=MessageTokensCount,
3042 )
3043
3044
3045 class MessagesWithRawResponse:
3046 def __init__(self, messages: Messages) -> None:
3047 self._messages = messages
3048
3049 self.create = to_raw_response_wrapper(
3050 messages.create,
3051 )
3052 self.count_tokens = to_raw_response_wrapper(
3053 messages.count_tokens,
3054 )
3055
3056 @cached_property
3057 def batches(self) -> BatchesWithRawResponse:
3058 return BatchesWithRawResponse(self._messages.batches)
3059
3060
3061 class AsyncMessagesWithRawResponse:
3062 def __init__(self, messages: AsyncMessages) -> None:
3063 self._messages = messages
3064
3065 self.create = async_to_raw_response_wrapper(
3066 messages.create,
3067 )
3068 self.count_tokens = async_to_raw_response_wrapper(
3069 messages.count_tokens,
3070 )
3071
3072 @cached_property
3073 def batches(self) -> AsyncBatchesWithRawResponse:
3074 return AsyncBatchesWithRawResponse(self._messages.batches)
3075
3076
3077 class MessagesWithStreamingResponse:
3078 def __init__(self, messages: Messages) -> None:
3079 self._messages = messages
3080
3081 self.create = to_streamed_response_wrapper(
3082 messages.create,
3083 )
3084 self.count_tokens = to_streamed_response_wrapper(
3085 messages.count_tokens,
3086 )
3087
3088 @cached_property
3089 def batches(self) -> BatchesWithStreamingResponse:
3090 return BatchesWithStreamingResponse(self._messages.batches)
3091
3092
3093 class AsyncMessagesWithStreamingResponse:
3094 def __init__(self, messages: AsyncMessages) -> None:
3095 self._messages = messages
3096
3097 self.create = async_to_streamed_response_wrapper(
3098 messages.create,
3099 )
3100 self.count_tokens = async_to_streamed_response_wrapper(
3101 messages.count_tokens,
3102 )
3103
3104 @cached_property
3105 def batches(self) -> AsyncBatchesWithStreamingResponse:
3106 return AsyncBatchesWithStreamingResponse(self._messages.batches)