跳转至内容

类型(Types)

消息、补全、响应与分页的共享 pydantic 模型,以及消息规范化辅助函数。 大部分名称可从 dashscope.types 直接导入。最后一节说明所有资源 共享的原始响应包装器与解析/错误模式契约。

消息与内容片段

Message

Bases: BaseModel

One chat message; content is a string, parts list, or None (assistant tool-call messages).

role instance-attribute

role: str

content class-attribute instance-attribute

content: Union[str, List[ContentPart], None] = None

name class-attribute instance-attribute

name: Optional[str] = None

tool_calls class-attribute instance-attribute

tool_calls: Optional[List[ToolCall]] = None

tool_call_id class-attribute instance-attribute

tool_call_id: Optional[str] = None

reasoning_content class-attribute instance-attribute

reasoning_content: Optional[str] = None

reasoning_signature class-attribute instance-attribute

reasoning_signature: Optional[str] = None

TextPart

Bases: BaseModel

type class-attribute instance-attribute

type: Literal['text'] = 'text'

text instance-attribute

text: str

cache_control class-attribute instance-attribute

cache_control: Optional[Dict[str, Any]] = None

ImagePart

Bases: BaseModel

type class-attribute instance-attribute

type: Literal['image'] = 'image'

url instance-attribute

url: str

detail class-attribute instance-attribute

detail: Optional[str] = None

min_pixels class-attribute instance-attribute

min_pixels: Optional[int] = None

max_pixels class-attribute instance-attribute

max_pixels: Optional[int] = None

cache_control class-attribute instance-attribute

cache_control: Optional[Dict[str, Any]] = None

AudioPart

Bases: BaseModel

type class-attribute instance-attribute

type: Literal['audio'] = 'audio'

url class-attribute instance-attribute

url: Optional[str] = None

data class-attribute instance-attribute

data: Optional[str] = None

format class-attribute instance-attribute

format: Optional[str] = None

cache_control class-attribute instance-attribute

cache_control: Optional[Dict[str, Any]] = None

VideoPart

Bases: BaseModel

type class-attribute instance-attribute

type: Literal['video'] = 'video'

url class-attribute instance-attribute

url: Optional[str] = None

frames class-attribute instance-attribute

frames: Optional[List[str]] = None

fps class-attribute instance-attribute

fps: Optional[float] = None

min_pixels class-attribute instance-attribute

min_pixels: Optional[int] = None

max_pixels class-attribute instance-attribute

max_pixels: Optional[int] = None

total_pixels class-attribute instance-attribute

total_pixels: Optional[int] = None

cache_control class-attribute instance-attribute

cache_control: Optional[Dict[str, Any]] = None

ToolCall

Bases: BaseModel

id class-attribute instance-attribute

id: Optional[str] = None

type class-attribute instance-attribute

type: str = 'function'

function class-attribute instance-attribute

function: ToolCallFunction = ToolCallFunction()

index class-attribute instance-attribute

index: Optional[int] = None

ToolCallFunction

Bases: BaseModel

name class-attribute instance-attribute

name: Optional[str] = None

arguments class-attribute instance-attribute

arguments: str = ''

补全模型

ChatCompletion

Bases: ResponseBase

model class-attribute instance-attribute

model: Optional[str] = None

choices class-attribute instance-attribute

choices: List[Choice] = []

usage class-attribute instance-attribute

usage: Optional[Usage] = None

search_info class-attribute instance-attribute

search_info: Optional[SearchInfo] = None

output_text property

output_text: str

ChatCompletionChunk

Bases: ResponseBase

model class-attribute instance-attribute

model: Optional[str] = None

choices class-attribute instance-attribute

choices: List[StreamChoice] = []

usage class-attribute instance-attribute

usage: Optional[Usage] = None

search_info class-attribute instance-attribute

search_info: Optional[SearchInfo] = None

delta property

delta: Optional[Delta]

ChatCompletionMessage

Bases: BaseModel

role class-attribute instance-attribute

role: str = 'assistant'

content class-attribute instance-attribute

content: Optional[str] = None

content_parts class-attribute instance-attribute

content_parts: Optional[List[Dict[str, Any]]] = None

reasoning_content class-attribute instance-attribute

reasoning_content: Optional[str] = None

reasoning_signature class-attribute instance-attribute

reasoning_signature: Optional[str] = None

tool_calls class-attribute instance-attribute

tool_calls: Optional[List[ToolCall]] = None

Choice

Bases: BaseModel

index class-attribute instance-attribute

index: int = 0

finish_reason class-attribute instance-attribute

finish_reason: Optional[str] = None

message instance-attribute

message: ChatCompletionMessage

StreamChoice

Bases: BaseModel

index class-attribute instance-attribute

index: int = 0

finish_reason class-attribute instance-attribute

finish_reason: Optional[str] = None

delta instance-attribute

delta: Delta

Delta

Bases: BaseModel

role class-attribute instance-attribute

role: Optional[str] = None

content class-attribute instance-attribute

content: Optional[str] = None

content_parts class-attribute instance-attribute

content_parts: Optional[List[Dict[str, Any]]] = None

reasoning_content class-attribute instance-attribute

reasoning_content: Optional[str] = None

reasoning_signature class-attribute instance-attribute

reasoning_signature: Optional[str] = None

tool_calls class-attribute instance-attribute

tool_calls: Optional[List[ToolCall]] = None

SearchInfo

Bases: BaseModel

Web-search citations, present when search is enabled.

search_results class-attribute instance-attribute

search_results: List[SearchResult] = []

SearchResult

Bases: BaseModel

One web-search citation (output.search_info.search_results[]).

title class-attribute instance-attribute

title: Optional[str] = None

url class-attribute instance-attribute

url: Optional[str] = None

site_name class-attribute instance-attribute

site_name: Optional[str] = None

index class-attribute instance-attribute

index: Optional[int] = None

通用与分页

ResponseBase

Bases: BaseModel

Envelope every top-level response carries.

DashScope can report a failure with HTTP 200, so code / message / is_error are part of every response rather than a chat-only concern; they stay empty when the call succeeded. With raise_on_error=False the SDK fills them instead of raising.

request_id class-attribute instance-attribute

request_id: Optional[str] = None

status_code class-attribute instance-attribute

status_code: Optional[int] = None

code class-attribute instance-attribute

code: Optional[str] = None

message class-attribute instance-attribute

message: Optional[str] = None

is_error class-attribute instance-attribute

is_error: bool = False

headers class-attribute instance-attribute

headers: Dict[str, str] = Field(default_factory=dict)

diagnosis property

diagnosis

Structured local fix guidance for a non-raising error envelope.

The raise_on_error=False counterpart of DashScopeError.diagnosis: when the SDK filled code/message instead of raising, this matches the same offline rule table and returns the guidance (or None for a success, or when no rule matched). Imported lazily so successful responses pay nothing and never load the devkit package.

Usage

Bases: BaseModel

Token usage, shared by every resource that reports it.

Service-specific counters (image_count for text-to-image, models for applications) arrive as extra fields and stay readable as attributes. Protocol adapters must preserve that property: they translate the three canonical counters and pass the rest of the wire bag through, so per-provider billing detail (cached or reasoning token counts) is never dropped on the way to the caller.

input_tokens class-attribute instance-attribute

input_tokens: int = 0

output_tokens class-attribute instance-attribute

output_tokens: int = 0

total_tokens class-attribute instance-attribute

total_tokens: int = 0

JobStatus

Bases: ResponseBase

Result of a state transition that reports nothing but the new state.

Shared by fine_tunes.cancel / fine_tunes.delete / deployments.delete, whose responses are identical on the wire.

status class-attribute instance-attribute

status: Optional[str] = None

BasePage

Bases: ResponseBase, Generic[T]

One page of an offset-paginated list, with traversal helpers.

Subclasses declare their item list under a resource-specific field and override :attr:items to return it. page_no / page_size / total_count are inherited from here.

page_no class-attribute instance-attribute

page_no: int = 1

page_size class-attribute instance-attribute

page_size: int = 10

total_count class-attribute instance-attribute

total_count: int = Field(
    0, validation_alias=AliasChoices("total_count", "total")
)

items property

items: List[T]

The items on this page; overridden by each concrete list model.

bind_pagination

bind_pagination(
    callback: Optional[Callable[[int, int], Any]],
    requested_page_no: Optional[int] = None,
    requested_page_size: Optional[int] = None,
) -> "BasePage[T]"

Attach the page-fetch callback the traversal methods use.

Resources call this right after parsing so next_page() / iter_pages() can request the following page. Returns self for chaining. callback is stored in a PrivateAttr, so binding it never changes model_dump().

requested_page_no / requested_page_size are the offsets the resource actually sent, and traversal advances from them rather than from the parsed :attr:page_no / :attr:page_size. A gateway that omits page_no leaves every page reading the field's default of 1, so advancing from the echo would request page 2 forever; one that omits page_size would silently change the window and skip or repeat items. The resource is the only party that reliably knows what it asked for.

Source code in dashscope/types/pagination.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def bind_pagination(
    self,
    callback: Optional[Callable[[int, int], Any]],
    requested_page_no: Optional[int] = None,
    requested_page_size: Optional[int] = None,
) -> "BasePage[T]":
    """Attach the page-fetch callback the traversal methods use.

    Resources call this right after parsing so ``next_page()`` /
    ``iter_pages()`` can request the following page. Returns ``self``
    for chaining. ``callback`` is stored in a ``PrivateAttr``, so
    binding it never changes ``model_dump()``.

    ``requested_page_no`` / ``requested_page_size`` are the offsets the
    resource actually sent, and traversal advances from them rather than
    from the parsed :attr:`page_no` / :attr:`page_size`. A gateway that
    omits ``page_no`` leaves every page reading the field's default of 1,
    so advancing from the echo would request page 2 forever; one that
    omits ``page_size`` would silently change the window and skip or
    repeat items. The resource is the only party that reliably knows what
    it asked for.
    """
    self._fetch_next = callback
    self._requested_no = requested_page_no
    self._requested_size = requested_page_size
    return self

has_next_page

has_next_page() -> bool

Whether total_count implies a page after this one.

Offset arithmetic only: it trusts the server's total_count and does not consult _fetch_next, so it stays meaningful on a page built without a callback (e.g. parsed straight from a body).

Source code in dashscope/types/pagination.py
158
159
160
161
162
163
164
165
def has_next_page(self) -> bool:
    """Whether ``total_count`` implies a page after this one.

    Offset arithmetic only: it trusts the server's ``total_count`` and
    does not consult ``_fetch_next``, so it stays meaningful on a page
    built without a callback (e.g. parsed straight from a body).
    """
    return self._cursor_no * self._cursor_size < self.total_count

next_page

next_page() -> Optional['BasePage[T]']

Fetch the following page, or None at the end of the list.

Returns None when there is no next page or when no fetch callback was injected (a standalone page cannot advance itself). Raises TypeError on a page fetched through AsyncClient -- use :meth:next_page_async there.

Source code in dashscope/types/pagination.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def next_page(self) -> Optional["BasePage[T]"]:
    """Fetch the following page, or ``None`` at the end of the list.

    Returns ``None`` when there is no next page or when no fetch callback
    was injected (a standalone page cannot advance itself). Raises
    ``TypeError`` on a page fetched through ``AsyncClient`` -- use
    :meth:`next_page_async` there.
    """
    if not self.has_next_page() or self._fetch_next is None:
        return None
    _reject_async_callback(self._fetch_next)
    return _reject_awaitable_page(
        self._fetch_next(self._cursor_no + 1, self._cursor_size),
    )

next_page_async async

next_page_async() -> Optional['BasePage[T]']

Async :meth:next_page; awaits the callback when it is a coroutine.

Source code in dashscope/types/pagination.py
182
183
184
185
186
187
188
189
async def next_page_async(self) -> Optional["BasePage[T]"]:
    """Async :meth:`next_page`; awaits the callback when it is a coroutine."""
    if not self.has_next_page() or self._fetch_next is None:
        return None
    result = self._fetch_next(self._cursor_no + 1, self._cursor_size)
    if inspect.isawaitable(result):
        result = await result
    return result

iter_pages

iter_pages() -> Iterator['BasePage[T]']

Yield this page and every following one, advancing via :meth:next_page.

Raises TypeError on a page fetched through AsyncClient; use :meth:iter_pages_async there. When the resource bound the coroutine function directly the refusal happens before anything is yielded; when it bound a closure around one, the first page is yielded and the advance that follows raises.

Source code in dashscope/types/pagination.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def iter_pages(self) -> Iterator["BasePage[T]"]:
    """Yield this page and every following one, advancing via :meth:`next_page`.

    Raises ``TypeError`` on a page fetched through ``AsyncClient``; use
    :meth:`iter_pages_async` there. When the resource bound the coroutine
    function directly the refusal happens before anything is yielded;
    when it bound a closure around one, the first page is yielded and the
    advance that follows raises.
    """
    if self._fetch_next is not None:
        _reject_async_callback(self._fetch_next)
    page: Optional["BasePage[T]"] = self
    while page is not None:
        yield page
        page = page.next_page()

iter_pages_async async

iter_pages_async() -> AsyncIterator['BasePage[T]']

Async :meth:iter_pages, advancing via :meth:next_page_async.

Source code in dashscope/types/pagination.py
220
221
222
223
224
225
async def iter_pages_async(self) -> AsyncIterator["BasePage[T]"]:
    """Async :meth:`iter_pages`, advancing via :meth:`next_page_async`."""
    page: Optional["BasePage[T]"] = self
    while page is not None:
        yield page
        page = await page.next_page_async()

辅助函数

normalize_messages

normalize_messages(
    messages: Union[MessageInput, List[MessageInput]],
) -> List[Message]
Source code in dashscope/types/messages.py
214
215
216
217
218
219
220
221
def normalize_messages(
    messages: Union[MessageInput, List[MessageInput]],
) -> List[Message]:
    if isinstance(messages, (str, dict, Message)):
        messages = [messages]
    if not messages:
        raise ValueError("messages must not be empty")
    return [_normalize_message(m) for m in messages]

extract_text

extract_text(message: Message) -> str
Source code in dashscope/types/messages.py
224
225
226
227
228
229
230
def extract_text(message: Message) -> str:
    content = message.content
    if content is None:
        return ""
    if isinstance(content, str):
        return content
    return "".join(p.text for p in content if isinstance(p, TextPart))

parse_completion

parse_completion(
    body: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> ChatCompletion
Source code in dashscope/types/completions.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def parse_completion(
    body: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> ChatCompletion:
    output = _output(body)
    return parse_model(
        ChatCompletion,
        {
            "request_id": body.get("request_id"),
            "model": body.get("model"),
            "choices": _canonical_choices(output),
            "usage": body.get("usage"),
            "search_info": output.get("search_info"),
        },
        strict=strict_validation,
        response=response,
    )

parse_chunk

parse_chunk(
    body: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> ChatCompletionChunk
Source code in dashscope/types/completions.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def parse_chunk(
    body: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> ChatCompletionChunk:
    output = _output(body)
    choices = []
    for raw in _canonical_choices(output):
        if isinstance(raw, dict):
            raw = dict(raw)
            if "message" in raw:
                raw["delta"] = raw.pop("message")
        choices.append(raw)
    return parse_model(
        ChatCompletionChunk,
        {
            "request_id": body.get("request_id"),
            "model": body.get("model"),
            "choices": choices,
            "usage": body.get("usage"),
            "search_info": output.get("search_info"),
        },
        strict=strict_validation,
        response=response,
    )

原始响应与解析

资源调用传 raw=True 会在任何错误检查与解析之前返回 APIResponse: 可读取 status_code、headers、elapsed、request_id,用 json() 解码响应体,或用 parse(Model) 构建类型化模型。下面四个开关 相互独立:

开关 作用域 效果
降级解析(默认) 每个类型化响应 漂移字段被修复为默认值/零值并记录 debug 日志;未知键保留。服务端字段变化不会让调用失败。
strict_validation=True Client(...) / dashscope.settings / 配置文件 关闭降级:漂移响应抛出 APIResponseValidationError(携带 response 与原始 body)。即使在不抛异常模式下也会触发。
raise_on_error=False Client(...) HTTP/业务失败以类型化信封返回(is_error、code、message),不再抛出。不会吞掉严格校验异常或本地 ValueError。
raw=True 单次调用 在错误检查与解析之前返回 APIResponse;随后 parse(Model) 按客户端的严格度解析。raw 响应不带分页回调,parse() 也不会重放资源自定义的响应整形。

APIResponse

APIResponse(response: Response, *, client: Any = None)

A parsed-on-demand view over one HTTP response.

Source code in dashscope/transport/_response.py
62
63
64
65
66
67
68
69
70
71
def __init__(
    self,
    response: httpx.Response,
    *,
    client: Any = None,
) -> None:
    self._response = response
    self._client = client
    self._parsed_by_type: Dict[Any, Any] = {}
    self._body: Any = _MISSING

http_response property

http_response: Response

The underlying raw httpx.Response.

headers property

headers: Dict[str, str]

A plain dict copy of the headers (same shape as with_headers).

status_code property

status_code: int

elapsed property

elapsed: Any

The request elapsed time (a timedelta), or None if unset.

httpx only records elapsed once the response has been read or closed; the SDK's non-streaming request() always reads it, so in practice this is set. None is returned instead of raising for a response wrapped before its body was consumed (e.g. a mock).

request_id property

request_id: Optional[str]

Server request id: the x-request-id header, else the body's.

The header wins because it is present even when the body is not decodable; the body (top-level or nested under output) is the fallback for gateways that only report it there.

json

json(*, require_object: bool = True) -> Any

The decoded JSON body, through the v2 error contract.

Delegates to :func:dashscope.errors.response_json, so an undecodable or non-object body raises the catalog internal_error rather than leaking JSONDecodeError. The object-body result is memoized; require_object=False bypasses the cache because it accepts shapes the cache does not.

Source code in dashscope/transport/_response.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def json(self, *, require_object: bool = True) -> Any:
    """The decoded JSON body, through the v2 error contract.

    Delegates to :func:`dashscope.errors.response_json`, so an
    undecodable or non-object body raises the catalog
    ``internal_error`` rather than leaking ``JSONDecodeError``. The
    object-body result is memoized; ``require_object=False`` bypasses
    the cache because it accepts shapes the cache does not.
    """
    if not require_object:
        return response_json(self._response, require_object=False)
    if self._body is _MISSING:
        self._body = response_json(self._response)
    return self._body

raise_for_status

raise_for_status() -> None

Apply the dual-layer error check (HTTP status, then business code).

Honors the client's raise_on_error: in non-raising mode a failure is left for the caller to read off the parsed model's envelope, exactly as check_response does.

Source code in dashscope/transport/_response.py
153
154
155
156
157
158
159
160
def raise_for_status(self) -> None:
    """Apply the dual-layer error check (HTTP status, then business code).

    Honors the client's ``raise_on_error``: in non-raising mode a
    failure is left for the caller to read off the parsed model's
    envelope, exactly as ``check_response`` does.
    """
    check_response(self._response, raise_on_error=self._raise_on_error)

parse

parse(cast_to: Optional[Type[T]] = None) -> Any

Parse the body, optionally into cast_to, memoized per type.

cast_to=None returns the decoded JSON body. Otherwise the body is unwrapped from its output / data envelope, built into cast_to via :func:~dashscope.types._parse.parse_model (degrading rather than raising unless the client is strict), and has the response headers attached. The result is cached by type, so repeat calls return the same object while different types cache independently.

cast_to must subclass :class:~dashscope.types.common.ResponseBase -- the headers land in its headers field, and unwrapping targets the envelope fields it declares. Anything else raises TypeError rather than failing later inside with_headers.

This is the generic direct-mapping path. Resources whose body needs reshaping beyond the envelope -- one item picked out of a list, a legacy singular field folded into a plural one, a page delivered as a bare array -- keep their own parser and read :meth:json instead. parse does not replay that reshaping, so on such an endpoint resource.method(raw=True).parse(Model) can return less than resource.method() did for the very same body. Read the resource's own docstring before relying on the raw path's parse.

Source code in dashscope/transport/_response.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def parse(self, cast_to: Optional[Type[T]] = None) -> Any:
    """Parse the body, optionally into ``cast_to``, memoized per type.

    ``cast_to=None`` returns the decoded JSON body. Otherwise the body is
    unwrapped from its ``output`` / ``data`` envelope, built into
    ``cast_to`` via :func:`~dashscope.types._parse.parse_model` (degrading
    rather than raising unless the client is strict), and has the response
    headers attached. The result is cached by type, so repeat calls return
    the *same* object while different types cache independently.

    ``cast_to`` must subclass
    :class:`~dashscope.types.common.ResponseBase` -- the headers land in
    its ``headers`` field, and unwrapping targets the envelope fields it
    declares. Anything else raises ``TypeError`` rather than failing later
    inside ``with_headers``.

    This is the generic direct-mapping path. Resources whose body needs
    reshaping beyond the envelope -- one item picked out of a list, a
    legacy singular field folded into a plural one, a page delivered as
    a bare array -- keep their own parser and read :meth:`json` instead.
    ``parse`` does not replay that reshaping, so on such an endpoint
    ``resource.method(raw=True).parse(Model)`` can return less than
    ``resource.method()`` did for the very same body. Read the
    resource's own docstring before relying on the raw path's parse.
    """
    if cast_to is None:
        return self.json()
    is_model = isinstance(cast_to, type) and issubclass(
        cast_to,
        ResponseBase,
    )
    if not is_model:
        raise TypeError(
            f"cast_to={cast_to!r} must be a ResponseBase subclass: the "
            "response headers are attached through its `headers` field",
        )
    cached = self._parsed_by_type.get(cast_to)
    if cached is not None:
        return cached
    model = parse_model(
        cast_to,
        _unwrap(self.json()),
        strict=self._strict,
        response=self._response,
    )
    model = with_headers(model, self._response)
    self._parsed_by_type[cast_to] = model
    return model

parse_model

parse_model(
    cls: Type[_ModelT],
    data: Mapping[str, Any],
    *,
    strict: bool = False,
    response: Optional[Response] = None
) -> _ModelT

Build cls from a server body, degrading rather than raising.

strict raises :class:~dashscope.errors.APIResponseValidationError carrying response and the raw body instead of degrading. It fires even when a resource is in non-raising (raise_on_error=False) mode: a schema assertion the caller opted into is not a service error to be reported through the response envelope.

Source code in dashscope/types/_parse.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def parse_model(
    cls: Type[_ModelT],
    data: Mapping[str, Any],
    *,
    strict: bool = False,
    response: Optional[httpx.Response] = None,
) -> _ModelT:
    """Build ``cls`` from a server body, degrading rather than raising.

    ``strict`` raises :class:`~dashscope.errors.APIResponseValidationError`
    carrying ``response`` and the raw ``body`` instead of degrading. It
    fires even when a resource is in non-raising (``raise_on_error=False``)
    mode: a schema assertion the caller opted into is not a service
    error to be reported through the response envelope.
    """
    if not isinstance(data, Mapping):
        # There are no fields to repair, and salvage would die on
        # ``dict(data)`` with a bare TypeError or ValueError -- exactly
        # the escape this module exists to prevent.
        if strict:
            raise APIResponseValidationError(response=response, body=data)
        logger.debug(
            "response drift: %s got %s where a mapping was expected; "
            "degraded parse applied",
            cls.__name__,
            type(data).__name__,
        )
        return _zero_model(cls)
    try:
        return cls.model_validate(data)
    except ValidationError as exc:
        error_count = len(exc.errors())
        if strict:
            logger.debug(
                "response drift: %s failed strict validation (%d error(s))",
                cls.__name__,
                error_count,
            )
            raise APIResponseValidationError(
                response=response,
                body=dict(data),
                cause=exc,
            ) from exc
        salvaged = _salvage(cls, data, exc)
    logger.debug(
        "response drift: %s failed validation (%d error(s)); "
        "degraded parse applied",
        cls.__name__,
        error_count,
    )
    try:
        return cls.model_validate(salvaged)
    except ValidationError:
        # Individually valid fields that still fail together mean a
        # cross-field invariant; only constructing can keep the body.
        return _construct_degraded(cls, salvaged)