Types¶
Shared pydantic models for messages, completions, responses and pagination,
plus message-normalization helpers. Most names are importable directly from
dashscope.types. The last section documents the raw-response wrapper and
the parsing / error-mode contract shared by all resources.
Messages & content parts¶
Message
¶
Bases: BaseModel
One chat message; content is a string, parts list, or None
(assistant tool-call messages).
TextPart
¶
ImagePart
¶
Bases: BaseModel
AudioPart
¶
Bases: BaseModel
VideoPart
¶
Bases: BaseModel
ToolCall
¶
Bases: BaseModel
ToolCallFunction
¶
Completion models¶
ChatCompletion
¶
Bases: ResponseBase
ChatCompletionChunk
¶
Bases: ResponseBase
ChatCompletionMessage
¶
Bases: BaseModel
content_parts
class-attribute
instance-attribute
¶
content_parts: Optional[List[Dict[str, Any]]] = None
Choice
¶
StreamChoice
¶
Delta
¶
Bases: BaseModel
content_parts
class-attribute
instance-attribute
¶
content_parts: Optional[List[Dict[str, Any]]] = None
SearchInfo
¶
Bases: BaseModel
Web-search citations, present when search is enabled.
SearchResult
¶
Bases: BaseModel
One web-search citation (output.search_info.search_results[]).
Common & pagination¶
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.
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.
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.
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.
total_count
class-attribute
instance-attribute
¶
total_count: int = Field(
0, validation_alias=AliasChoices("total_count", "total")
)
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
Helpers¶
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 | |
extract_text
¶
extract_text(message: Message) -> str
Source code in dashscope/types/messages.py
224 225 226 227 228 229 230 | |
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 | |
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 | |
Raw responses & parsing¶
Passing raw=True to a resource call returns an APIResponse before any
error check or parsing: read status_code, headers, elapsed and
request_id, decode the body with json(), or build a typed model with
parse(Model). The four switches below are independent of each other:
| Switch | Scope | Effect |
|---|---|---|
| Lenient parse (default) | every typed response | Drifted fields are repaired to their defaults / zero values and logged at debug level; unknown keys are kept. A server-side schema change does not break the call. |
strict_validation=True |
Client(...) / dashscope.settings / config file |
Opts out of the repair: a drifted body raises APIResponseValidationError (carrying response and the raw body) instead of degrading. Fires even in non-raising mode. |
raise_on_error=False |
Client(...) |
HTTP / business failures come back as the typed envelope (is_error, code, message) instead of raising. Does not suppress strict-validation errors or local ValueError. |
raw=True |
per call | Returns APIResponse before the error check and parsing; parse(Model) then applies the client's strictness. A raw response carries no pagination callback, and parse() does not replay a resource's custom reshaping. |
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 | |
headers
property
¶
headers: Dict[str, str]
A plain dict copy of the headers (same shape as with_headers).
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 | |
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 | |
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 | |
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 | |