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