Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Anthropics Anthropic sdk python Messages Parse

From Leeroopedia
Knowledge Sources
Domains Structured_Output, LLM, Data_Extraction
Last Updated 2026-02-15 00:00 GMT

Overview

The Messages Parse implementation provides the parse() method on both the synchronous Messages and asynchronous AsyncMessages resource classes. This method combines API request execution with automatic schema derivation and response validation, returning a fully typed ParsedMessage[ResponseFormatT] instead of a raw Message.

API Surface

Messages.parse (Synchronous)

from anthropic import Anthropic
client = Anthropic()
result = client.messages.parse(...)

Source: src/anthropic/resources/messages/messages.py:L1118-1234

def parse(
    self,
    *,
    max_tokens: int,
    messages: Iterable[MessageParam],
    model: ModelParam,
    metadata: MetadataParam | Omit = omit,
    output_config: OutputConfigParam | Omit = omit,
    output_format: Optional[type[ResponseFormatT]] | Omit = omit,
    service_tier: Literal["auto", "standard_only"] | Omit = omit,
    stop_sequences: SequenceNotStr[str] | Omit = omit,
    stream: Literal[False] | Literal[True] | Omit = omit,
    system: Union[str, Iterable[TextBlockParam]] | Omit = omit,
    temperature: float | Omit = omit,
    thinking: ThinkingConfigParam | Omit = omit,
    tool_choice: ToolChoiceParam | Omit = omit,
    tools: Iterable[ToolUnionParam] | Omit = omit,
    top_k: int | Omit = omit,
    top_p: float | Omit = omit,
    extra_headers: Headers | None = None,
    extra_query: Query | None = None,
    extra_body: Body | None = None,
    timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> ParsedMessage[ResponseFormatT]:

AsyncMessages.parse (Asynchronous)

Source: src/anthropic/resources/messages/messages.py:L2535-2651

async def parse(
    self,
    *,
    max_tokens: int,
    messages: Iterable[MessageParam],
    model: ModelParam,
    output_format: Optional[type[ResponseFormatT]] | Omit = omit,
    # ... same parameters as synchronous version ...
) -> ParsedMessage[ResponseFormatT]:

The async variant has an identical signature and returns the same ParsedMessage[ResponseFormatT] type. The only difference is that the HTTP POST and body transformation use await.

Detailed Behavior

Step 1: Timeout Calculation

If streaming is not enabled, no explicit timeout is given, and the client uses the default timeout, the method calculates an appropriate non-streaming timeout based on the max_tokens parameter and model-specific token rate estimates:

if not stream and not is_given(timeout) and self._client.timeout == DEFAULT_TIMEOUT:
    timeout = self._client._calculate_nonstreaming_timeout(
        max_tokens, MODEL_NONSTREAMING_TOKENS.get(model, None)
    )

Step 2: Telemetry Header Injection

A helper identification header is added to every parse() request:

extra_headers = {
    "X-Stainless-Helper": "messages.parse",
    **(extra_headers or {}),
}

Step 3: Schema Derivation and Transformation

When output_format is provided (a Pydantic BaseModel subclass), the method generates and transforms the JSON Schema:

if is_given(output_format) and output_format is not None:
    adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format)

    try:
        schema = adapted_type.json_schema()
        transformed_output_format = JSONOutputFormatParam(
            schema=transform_schema(schema), type="json_schema"
        )
    except pydantic.errors.PydanticSchemaGenerationError as e:
        raise TypeError(
            "Could not generate JSON schema for the given `output_format` type. "
            "Use a type that works with `pydantic.TypeAdapter`"
        ) from e

If schema generation fails, a TypeError is raised immediately before any API call is made.

Step 4: Output Config Merging

The transformed schema is merged into the output_config parameter. If the developer also provided an output_config, the format is merged in; otherwise, a new config is created:

merged_output_config: OutputConfigParam | Omit = omit
if is_given(transformed_output_format):
    if is_given(output_config):
        merged_output_config = {**output_config, "format": transformed_output_format}
    else:
        merged_output_config = {"format": transformed_output_format}
elif is_given(output_config):
    merged_output_config = output_config

Step 5: Post-Parser Callback Registration

A parser closure is defined that will transform the raw Message response into a ParsedMessage[ResponseFormatT]:

def parser(response: Message) -> ParsedMessage[ResponseFormatT]:
    return parse_response(
        response=response,
        output_format=cast(
            ResponseFormatT,
            output_format if is_given(output_format) and output_format is not None else NOT_GIVEN,
        ),
    )

This callback is registered via make_request_options(post_parser=parser), which causes the SDK's HTTP layer to invoke it after deserializing the response body into a Message object.

Step 6: API Request

The method calls self._post("/v1/messages", ...) with the transformed body, options (including the post-parser), and a cast to the expected return type:

return self._post(
    "/v1/messages",
    body=maybe_transform({...}, message_create_params.MessageCreateParamsNonStreaming),
    options=make_request_options(
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        timeout=timeout,
        post_parser=parser,
    ),
    cast_to=cast(Type[ParsedMessage[ResponseFormatT]], Message),
    stream=False,
)

Usage Example

import anthropic
from pydantic import BaseModel

class MovieReview(BaseModel):
    title: str
    rating: float
    summary: str
    pros: list[str]
    cons: list[str]

client = anthropic.Anthropic()

message = client.messages.parse(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Review the movie Inception"}],
    output_format=MovieReview,
)

review = message.parsed_output  # MovieReview instance
print(f"{review.title}: {review.rating}/10")
print(f"Pros: {', '.join(review.pros)}")

Dependencies

  • httpx: HTTP client used for API communication.
  • pydantic (BaseModel, TypeAdapter): For schema generation and JSON validation.
  • anthropic.lib._parse._transform (transform_schema): For schema normalization.
  • anthropic.lib._parse._response (parse_response): For post-parse transformation of the Message into ParsedMessage.
  • anthropic.types (JSONOutputFormatParam, ParsedMessage): Type definitions.

Key Source Files

  • src/anthropic/resources/messages/messages.py -- Messages.parse() at L1118-1234, AsyncMessages.parse() at L2535-2651.
  • src/anthropic/lib/_parse/_transform.py -- transform_schema() used for schema normalization.
  • src/anthropic/lib/_parse/_response.py -- parse_response() at L49-72 used as the post-parser callback.

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment