跳转至内容

协议适配器(Protocols)

dashscope.protocols 在不同传输协议之间转换对话请求与响应, 同一个 client.chat.completions 调用可以使用 DashScope 原生协议、 OpenAI 兼容协议或 Anthropic 兼容协议。通过 Client(protocol="openai") (或 protocol 配置项 / DASHSCOPE_PROTOCOL 环境变量)选择; 合法值为 native、openai、anthropic。

优先级

显式 Client(protocol=...) 参数优先于 protocol 配置项, 后者优先于 DASHSCOPE_PROTOCOL 环境变量。

基础契约

ChatProtocol

ChatProtocol(*, strict: bool = False)

Bases: ABC

Translates canonical chat calls to one wire protocol.

Source code in dashscope/protocols/base.py
59
60
def __init__(self, *, strict: bool = False) -> None:
    self._strict = strict

name class-attribute

name: str

MULTIMODAL_PATH class-attribute

MULTIMODAL_PATH: Optional[str] = None

strict property

strict: bool

Reject (True) or pass through (False) unknown parameters.

Inert on the native adapter: every known parameter maps into its parameters bag, so nothing is ever "unknown".

build_chat_request abstractmethod

build_chat_request(
    *,
    model: str,
    messages: List[Dict[str, Any]],
    stream: bool = False,
    tools: Optional[List[Dict[str, Any]]] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
    stop: Union[str, List[str], None] = None,
    seed: Optional[int] = None,
    repetition_penalty: Optional[float] = None,
    presence_penalty: Optional[float] = None,
    enable_thinking: Optional[bool] = None,
    response_format: Optional[Dict[str, Any]] = None,
    top_k: Optional[int] = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    n: Optional[int] = None,
    logprobs: Optional[bool] = None,
    top_logprobs: Optional[int] = None,
    thinking_budget: Optional[int] = None,
    enable_search: Optional[bool] = None,
    search_options: Optional[Dict[str, Any]] = None,
    parallel_tool_calls: Optional[bool] = None,
    extra_parameters: Optional[Dict[str, Any]] = None,
    path: Optional[str] = None
) -> ChatRequest

Build the wire request (path, headers, body) for one call.

path overrides the adapter's default endpoint; callers pass MULTIMODAL_PATH when the messages carry media parts.

Source code in dashscope/protocols/base.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@abstractmethod
def build_chat_request(
    self,
    *,
    model: str,
    messages: List[Dict[str, Any]],
    stream: bool = False,
    tools: Optional[List[Dict[str, Any]]] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
    stop: Union[str, List[str], None] = None,
    seed: Optional[int] = None,
    repetition_penalty: Optional[float] = None,
    presence_penalty: Optional[float] = None,
    enable_thinking: Optional[bool] = None,
    response_format: Optional[Dict[str, Any]] = None,
    top_k: Optional[int] = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    n: Optional[int] = None,
    logprobs: Optional[bool] = None,
    top_logprobs: Optional[int] = None,
    thinking_budget: Optional[int] = None,
    enable_search: Optional[bool] = None,
    search_options: Optional[Dict[str, Any]] = None,
    parallel_tool_calls: Optional[bool] = None,
    extra_parameters: Optional[Dict[str, Any]] = None,
    path: Optional[str] = None,
) -> ChatRequest:
    """Build the wire request (path, headers, body) for one call.

    ``path`` overrides the adapter's default endpoint; callers pass
    ``MULTIMODAL_PATH`` when the messages carry media parts.
    """

parse_completion abstractmethod

parse_completion(
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> ChatCompletion

Translate a non-streaming response body.

strict_validation raises on a body that does not fit the typed model instead of degrading it; it is unrelated to :attr:strict, which governs request construction. response is only carried onto that raised error, so the caller can inspect the status and headers of the body that failed; websocket payloads have none and leave it None.

Source code in dashscope/protocols/base.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
@abstractmethod
def parse_completion(
    self,
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> ChatCompletion:
    """Translate a non-streaming response body.

    ``strict_validation`` raises on a body that does not fit the
    typed model instead of degrading it; it is unrelated to
    :attr:`strict`, which governs *request* construction.
    ``response`` is only carried onto that raised error, so the
    caller can inspect the status and headers of the body that
    failed; websocket payloads have none and leave it ``None``.
    """

parse_chunk abstractmethod

parse_chunk(
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> Optional[ChatCompletionChunk]

Translate one streaming event body; None skips the event (keepalives and control frames carry no user-facing content).

Source code in dashscope/protocols/base.py
124
125
126
127
128
129
130
131
132
133
@abstractmethod
def parse_chunk(
    self,
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> Optional[ChatCompletionChunk]:
    """Translate one streaming event body; ``None`` skips the event
    (keepalives and control frames carry no user-facing content)."""

make_chunk_parser

make_chunk_parser(
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> Callable[
    [Dict[str, Any]], Optional[ChatCompletionChunk]
]

Return the chunk parser for one new stream.

Stateless adapters reuse parse_chunk; stateful adapters (e.g. anthropic tool-use accumulation) return a fresh parser per stream so concurrent streams never share state.

The returned callable takes only the payload, so the validation mode and the response a strict failure should carry are bound here rather than passed per event.

Source code in dashscope/protocols/base.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def make_chunk_parser(
    self,
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> Callable[[Dict[str, Any]], Optional[ChatCompletionChunk]]:
    """Return the chunk parser for one new stream.

    Stateless adapters reuse ``parse_chunk``; stateful adapters
    (e.g. anthropic tool-use accumulation) return a fresh parser
    per stream so concurrent streams never share state.

    The returned callable takes only the payload, so the validation
    mode and the response a strict failure should carry are bound
    here rather than passed per event.
    """
    if not strict_validation and response is None:
        return self.parse_chunk
    return functools.partial(
        self.parse_chunk,
        strict_validation=strict_validation,
        response=response,
    )

ChatRequest dataclass

ChatRequest(
    path: str,
    body: Dict[str, Any],
    headers: Dict[str, str] = dict(),
)

Wire-level description of one chat request.

path instance-attribute

path: str

body instance-attribute

body: Dict[str, Any]

headers class-attribute instance-attribute

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

适配器

NativeProtocol

NativeProtocol(*, strict: bool = False)

Bases: ChatProtocol

DashScope native protocol: /services/... + input/parameters body.

Source code in dashscope/protocols/base.py
59
60
def __init__(self, *, strict: bool = False) -> None:
    self._strict = strict

name class-attribute instance-attribute

name = 'native'

PATH class-attribute instance-attribute

PATH = '/services/aigc/text-generation/generation'

MULTIMODAL_PATH class-attribute instance-attribute

MULTIMODAL_PATH = (
    "/services/aigc/multimodal-generation/generation"
)

SSE_HEADERS class-attribute instance-attribute

SSE_HEADERS = {'X-DashScope-SSE': 'enable'}

build_chat_request

build_chat_request(
    *,
    model: str,
    messages: List[Dict[str, Any]],
    stream: bool = False,
    tools: Optional[List[Dict[str, Any]]] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
    stop: Union[str, List[str], None] = None,
    seed: Optional[int] = None,
    repetition_penalty: Optional[float] = None,
    presence_penalty: Optional[float] = None,
    enable_thinking: Optional[bool] = None,
    response_format: Optional[Dict[str, Any]] = None,
    top_k: Optional[int] = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    n: Optional[int] = None,
    logprobs: Optional[bool] = None,
    top_logprobs: Optional[int] = None,
    thinking_budget: Optional[int] = None,
    enable_search: Optional[bool] = None,
    search_options: Optional[Dict[str, Any]] = None,
    parallel_tool_calls: Optional[bool] = None,
    extra_parameters: Optional[Dict[str, Any]] = None,
    path: Optional[str] = None
) -> ChatRequest
Source code in dashscope/protocols/native.py
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def build_chat_request(
    self,
    *,
    model: str,
    messages: List[Dict[str, Any]],
    stream: bool = False,
    tools: Optional[List[Dict[str, Any]]] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
    stop: Union[str, List[str], None] = None,
    seed: Optional[int] = None,
    repetition_penalty: Optional[float] = None,
    presence_penalty: Optional[float] = None,
    enable_thinking: Optional[bool] = None,
    response_format: Optional[Dict[str, Any]] = None,
    top_k: Optional[int] = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    n: Optional[int] = None,
    logprobs: Optional[bool] = None,
    top_logprobs: Optional[int] = None,
    thinking_budget: Optional[int] = None,
    enable_search: Optional[bool] = None,
    search_options: Optional[Dict[str, Any]] = None,
    parallel_tool_calls: Optional[bool] = None,
    extra_parameters: Optional[Dict[str, Any]] = None,
    path: Optional[str] = None,
) -> ChatRequest:
    parameters: Dict[str, Any] = {"result_format": "message"}
    if stream:
        parameters["incremental_output"] = True
    for key, value in (
        ("temperature", temperature),
        ("top_p", top_p),
        ("max_tokens", max_tokens),
        ("stop", stop),
        ("seed", seed),
        ("repetition_penalty", repetition_penalty),
        ("presence_penalty", presence_penalty),
        ("enable_thinking", enable_thinking),
        ("response_format", response_format),
        ("top_k", top_k),
        ("tool_choice", tool_choice),
        ("n", n),
        ("logprobs", logprobs),
        ("top_logprobs", top_logprobs),
        ("thinking_budget", thinking_budget),
        ("enable_search", enable_search),
        ("search_options", search_options),
        ("parallel_tool_calls", parallel_tool_calls),
        ("tools", tools),
    ):
        if value is not None:
            parameters[key] = value
    if extra_parameters:
        parameters.update(extra_parameters)
    body = {
        "model": model,
        "input": {"messages": _translate_messages(messages)},
        "parameters": parameters,
    }
    headers = dict(self.SSE_HEADERS) if stream else {}
    return ChatRequest(path=path or self.PATH, body=body, headers=headers)

parse_completion

parse_completion(
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> ChatCompletion
Source code in dashscope/protocols/native.py
169
170
171
172
173
174
175
176
177
178
179
180
def parse_completion(
    self,
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> ChatCompletion:
    return parse_completion(
        payload,
        strict_validation=strict_validation,
        response=response,
    )

parse_chunk

parse_chunk(
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> ChatCompletionChunk
Source code in dashscope/protocols/native.py
182
183
184
185
186
187
188
189
190
191
192
193
def parse_chunk(
    self,
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> ChatCompletionChunk:
    return parse_chunk(
        payload,
        strict_validation=strict_validation,
        response=response,
    )

OpenAIProtocol

OpenAIProtocol(*, strict: bool = False)

Bases: ChatProtocol

Adapter for POST /chat/completions (OpenAI-compatible).

Source code in dashscope/protocols/base.py
59
60
def __init__(self, *, strict: bool = False) -> None:
    self._strict = strict

name class-attribute instance-attribute

name = 'openai'

PATH class-attribute instance-attribute

PATH = '/chat/completions'

build_chat_request

build_chat_request(
    *,
    model: str,
    messages: List[Dict[str, Any]],
    stream: bool = False,
    tools: Optional[List[Dict[str, Any]]] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
    stop: Union[str, List[str], None] = None,
    seed: Optional[int] = None,
    repetition_penalty: Optional[float] = None,
    presence_penalty: Optional[float] = None,
    enable_thinking: Optional[bool] = None,
    response_format: Optional[Dict[str, Any]] = None,
    top_k: Optional[int] = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    n: Optional[int] = None,
    logprobs: Optional[bool] = None,
    top_logprobs: Optional[int] = None,
    thinking_budget: Optional[int] = None,
    enable_search: Optional[bool] = None,
    search_options: Optional[Dict[str, Any]] = None,
    parallel_tool_calls: Optional[bool] = None,
    extra_parameters: Optional[Dict[str, Any]] = None,
    path: Optional[str] = None
) -> ChatRequest
Source code in dashscope/protocols/openai.py
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
210
211
212
213
214
215
216
217
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def build_chat_request(
    self,
    *,
    model: str,
    messages: List[Dict[str, Any]],
    stream: bool = False,
    tools: Optional[List[Dict[str, Any]]] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
    stop: Union[str, List[str], None] = None,
    seed: Optional[int] = None,
    repetition_penalty: Optional[float] = None,
    presence_penalty: Optional[float] = None,
    enable_thinking: Optional[bool] = None,
    response_format: Optional[Dict[str, Any]] = None,
    top_k: Optional[int] = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    n: Optional[int] = None,
    logprobs: Optional[bool] = None,
    top_logprobs: Optional[int] = None,
    thinking_budget: Optional[int] = None,
    enable_search: Optional[bool] = None,
    search_options: Optional[Dict[str, Any]] = None,
    parallel_tool_calls: Optional[bool] = None,
    extra_parameters: Optional[Dict[str, Any]] = None,
    path: Optional[str] = None,
) -> ChatRequest:
    body: Dict[str, Any] = {
        "model": model,
        "messages": [_translate_message(m) for m in messages],
    }
    if stream:
        body["stream"] = True
        # OpenAI-compatible servers omit usage from streams unless
        # asked; extra_parameters can still override this.
        body["stream_options"] = {"include_usage": True}
    for key, value in (
        ("temperature", temperature),
        ("top_p", top_p),
        ("max_tokens", max_tokens),
        ("stop", stop),
        ("seed", seed),
        ("presence_penalty", presence_penalty),
        ("response_format", response_format),
        ("tools", tools),
        ("tool_choice", tool_choice),
        ("n", n),
        ("logprobs", logprobs),
        ("top_logprobs", top_logprobs),
        ("parallel_tool_calls", parallel_tool_calls),
        # DashScope extensions Bailian compatible-mode understands;
        # named SDK params, so strict must not reject them. The search
        # runs server-side, but the compatible wire returns no search
        # sources, so search_info stays None on this protocol (the
        # native protocol is where it is parsed).
        ("top_k", top_k),
        ("thinking_budget", thinking_budget),
        ("enable_search", enable_search),
        ("search_options", search_options),
    ):
        if value is not None:
            body[key] = value
    unknown: Dict[str, Any] = {}
    if repetition_penalty is not None:
        unknown["repetition_penalty"] = repetition_penalty
    if enable_thinking is not None:
        unknown["enable_thinking"] = enable_thinking
    if extra_parameters:
        unknown.update(extra_parameters)
    if unknown:
        if self._strict:
            raise DashScopeError(
                "unknown OpenAI parameters in strict mode: "
                f"{sorted(unknown)}; drop them or use strict=False",
            )
        body.update(unknown)
    return ChatRequest(path=path or self.PATH, body=body)

parse_completion

parse_completion(
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> ChatCompletion
Source code in dashscope/protocols/openai.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def parse_completion(
    self,
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> ChatCompletion:
    choices = []
    for raw in payload.get("choices") or []:
        if isinstance(raw, dict):
            raw = dict(raw)
            message = raw.get("message")
            if isinstance(message, dict):
                raw["message"] = _normalize_message_content(message)
        choices.append(raw)
    return parse_model(
        ChatCompletion,
        {
            "request_id": payload.get("request_id") or payload.get("id"),
            "model": payload.get("model"),
            "choices": choices,
            "usage": _canonical_usage(payload.get("usage")),
        },
        strict=strict_validation,
        response=response,
    )

parse_chunk

parse_chunk(
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> ChatCompletionChunk
Source code in dashscope/protocols/openai.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def parse_chunk(
    self,
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> ChatCompletionChunk:
    choices = []
    for raw in payload.get("choices") or []:
        # A non-mapping element has no ``delta`` to default, and
        # ``dict()`` on it would escape as a bare ValueError.
        # Keeping the slot preserves positional alignment for
        # parse_model to repair in place.
        if isinstance(raw, dict):
            raw = dict(raw)
            raw.setdefault("delta", {})
            if isinstance(raw["delta"], dict):
                raw["delta"] = _normalize_message_content(raw["delta"])
        choices.append(raw)
    return parse_model(
        ChatCompletionChunk,
        {
            "request_id": payload.get("request_id") or payload.get("id"),
            "model": payload.get("model"),
            "choices": choices,
            "usage": _canonical_usage(payload.get("usage")),
        },
        strict=strict_validation,
        response=response,
    )

AnthropicProtocol

AnthropicProtocol(*, strict: bool = False)

Bases: ChatProtocol

Adapter for POST /v1/messages (Anthropic Messages API).

Source code in dashscope/protocols/anthropic.py
647
648
649
def __init__(self, *, strict: bool = False) -> None:
    super().__init__(strict=strict)
    self._default_parser = _StreamParser()

name class-attribute instance-attribute

name = 'anthropic'

PATH class-attribute instance-attribute

PATH = '/v1/messages'

API_VERSION class-attribute instance-attribute

API_VERSION = '2023-06-01'

make_chunk_parser

make_chunk_parser(
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> Callable[
    [Dict[str, Any]], Optional[ChatCompletionChunk]
]

Return a fresh parser so concurrent streams stay isolated.

Source code in dashscope/protocols/anthropic.py
651
652
653
654
655
656
657
658
659
660
661
def make_chunk_parser(
    self,
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> Callable[[Dict[str, Any]], Optional[ChatCompletionChunk]]:
    """Return a fresh parser so concurrent streams stay isolated."""
    return _StreamParser(
        strict_validation=strict_validation,
        response=response,
    ).parse

build_chat_request

build_chat_request(
    *,
    model: str,
    messages: List[Dict[str, Any]],
    stream: bool = False,
    tools: Optional[List[Dict[str, Any]]] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
    stop: Union[str, List[str], None] = None,
    seed: Optional[int] = None,
    repetition_penalty: Optional[float] = None,
    presence_penalty: Optional[float] = None,
    enable_thinking: Optional[bool] = None,
    response_format: Optional[Dict[str, Any]] = None,
    top_k: Optional[int] = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    n: Optional[int] = None,
    logprobs: Optional[bool] = None,
    top_logprobs: Optional[int] = None,
    thinking_budget: Optional[int] = None,
    enable_search: Optional[bool] = None,
    search_options: Optional[Dict[str, Any]] = None,
    parallel_tool_calls: Optional[bool] = None,
    extra_parameters: Optional[Dict[str, Any]] = None,
    path: Optional[str] = None
) -> ChatRequest
Source code in dashscope/protocols/anthropic.py
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def build_chat_request(
    self,
    *,
    model: str,
    messages: List[Dict[str, Any]],
    stream: bool = False,
    tools: Optional[List[Dict[str, Any]]] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
    stop: Union[str, List[str], None] = None,
    seed: Optional[int] = None,
    repetition_penalty: Optional[float] = None,
    presence_penalty: Optional[float] = None,
    enable_thinking: Optional[bool] = None,
    response_format: Optional[Dict[str, Any]] = None,
    top_k: Optional[int] = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    n: Optional[int] = None,
    logprobs: Optional[bool] = None,
    top_logprobs: Optional[int] = None,
    thinking_budget: Optional[int] = None,
    enable_search: Optional[bool] = None,
    search_options: Optional[Dict[str, Any]] = None,
    parallel_tool_calls: Optional[bool] = None,
    extra_parameters: Optional[Dict[str, Any]] = None,
    path: Optional[str] = None,
) -> ChatRequest:
    _reject_unsupported(
        (
            ("seed", seed),
            ("repetition_penalty", repetition_penalty),
            ("presence_penalty", presence_penalty),
            ("enable_thinking", enable_thinking),
            ("response_format", response_format),
            ("n", n),
            ("logprobs", logprobs),
            ("top_logprobs", top_logprobs),
            ("thinking_budget", thinking_budget),
            ("enable_search", enable_search),
            ("search_options", search_options),
            ("parallel_tool_calls", parallel_tool_calls),
        ),
    )
    wire_messages, system_blocks = _split_messages(messages)
    body: Dict[str, Any] = {
        "model": model,
        "messages": wire_messages,
        "max_tokens": max_tokens or DEFAULT_MAX_TOKENS,
    }
    if system_blocks:
        if any("cache_control" in b for b in system_blocks):
            # A cache_control marker needs the block-list form of the
            # Anthropic ``system`` field; without one keep the joined
            # string so the wire stays byte-identical.
            body["system"] = system_blocks
        else:
            body["system"] = "\n\n".join(b["text"] for b in system_blocks)
    if stream:
        body["stream"] = True
    if temperature is not None:
        body["temperature"] = temperature
    if top_p is not None:
        body["top_p"] = top_p
    if top_k is not None:
        body["top_k"] = top_k
    if stop is not None:
        body["stop_sequences"] = [stop] if isinstance(stop, str) else stop
    if tools:
        body["tools"] = _translate_tools(tools)
    # Emitted even without tools so the value is never silently
    # dropped; a tool_choice without tools gets a clear server-side
    # 400 instead.
    if tool_choice is not None:
        body["tool_choice"] = _translate_tool_choice(tool_choice)
    # The hatch below is applied verbatim (body.update), so a
    # canonical or OpenAI-shaped tool_choice smuggled through
    # extra_parameters must go through the same translator first;
    # otherwise a bare "required" reaches the wire and the gateway
    # silently ignores it. Native shapes pass through the translator
    # unchanged, so this converges both entry points and keeps the
    # hatch-wins precedence. Copy first: never mutate the caller's
    # dict.
    if (
        extra_parameters
        and extra_parameters.get("tool_choice") is not None
    ):
        extra_parameters = dict(extra_parameters)
        extra_parameters["tool_choice"] = _translate_tool_choice(
            extra_parameters["tool_choice"],
        )
    # Reject unsupported canonical names even when passed via
    # extra_parameters, so they can never slip through silently.
    _reject_unsupported(
        tuple(
            (key, value)
            for key, value in (extra_parameters or {}).items()
            if key in _UNSUPPORTED_CANONICAL
        ),
    )
    _apply_extra_parameters(body, self._strict, extra_parameters)
    return ChatRequest(
        path=path or self.PATH,
        body=body,
        headers={"anthropic-version": self.API_VERSION},
    )

parse_completion

parse_completion(
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> ChatCompletion
Source code in dashscope/protocols/anthropic.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
def parse_completion(
    self,
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> ChatCompletion:
    text_parts: List[str] = []
    thinking_parts: List[str] = []
    thinking_blocks: List[Dict[str, Any]] = []
    tool_calls: List[Dict[str, Any]] = []
    for block in payload.get("content") or []:
        if not isinstance(block, dict):
            # ``block.get`` on a drifted element (a bare string)
            # would escape as an AttributeError before parse_model
            # ever saw the body; there is nothing to translate.
            continue
        if block.get("type") == "text":
            text_parts.append(block.get("text", ""))
        elif block.get("type") == "thinking":
            # Parity with the streaming thinking_delta path. The
            # signature is kept so the turn can be echoed back
            # to the API; redacted_thinking carries no readable
            # text and stays dropped (verbatim replay of it is
            # unsupported by the flat canonical model).
            thinking_parts.append(block.get("thinking", ""))
            thinking_blocks.append(dict(block))
        elif block.get("type") == "redacted_thinking":
            thinking_blocks.append(dict(block))
        elif block.get("type") == "tool_use":
            tool_calls.append(
                {
                    "id": block.get("id"),
                    "type": "function",
                    "function": {
                        "name": block.get("name"),
                        "arguments": json.dumps(
                            block.get("input") or {},
                            ensure_ascii=False,
                        ),
                    },
                },
            )
    message: Dict[str, Any] = {
        "role": payload.get("role") or "assistant",
        "content": "".join(text_parts) or None,
    }
    reasoning_content = "".join(thinking_parts)
    if reasoning_content:
        message["reasoning_content"] = reasoning_content
    if thinking_blocks:
        message["reasoning_blocks"] = thinking_blocks
    signed = [
        block
        for block in thinking_blocks
        if block.get("type") == "thinking" and block.get("signature")
    ]
    if len(signed) == 1:
        message["reasoning_signature"] = signed[0]["signature"]
    if tool_calls:
        message["tool_calls"] = tool_calls
    stop_reason = payload.get("stop_reason")
    usage = payload.get("usage") or {}
    return parse_model(
        ChatCompletion,
        {
            "request_id": payload.get("id"),
            "model": payload.get("model"),
            "choices": [
                {
                    "index": 0,
                    "finish_reason": _STOP_REASON_MAP.get(
                        stop_reason,
                        stop_reason,
                    ),
                    "message": message,
                },
            ],
            "usage": _canonical_usage(usage) if usage else None,
        },
        strict=strict_validation,
        response=response,
    )

parse_chunk

parse_chunk(
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[Response] = None
) -> Optional[ChatCompletionChunk]
Source code in dashscope/protocols/anthropic.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
def parse_chunk(
    self,
    payload: Dict[str, Any],
    *,
    strict_validation: bool = False,
    response: Optional[httpx.Response] = None,
) -> Optional[ChatCompletionChunk]:
    # Sequential convenience path for direct calls; resources take
    # a per-stream parser from make_chunk_parser() instead.
    return self._default_parser.parse(
        payload,
        strict_validation=strict_validation,
        response=response,
    )

注册表

get_protocol

get_protocol(
    name: str,
    protocol_options: Optional[Dict[str, Any]] = None,
) -> ChatProtocol

Resolve a protocol adapter by name, passing adapter options.

Source code in dashscope/protocols/__init__.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def get_protocol(
    name: str,
    protocol_options: Optional[Dict[str, Any]] = None,
) -> ChatProtocol:
    """Resolve a protocol adapter by name, passing adapter options."""
    protocol_cls = _REGISTRY.get(name)
    if protocol_cls is None:
        raise ValueError(
            f"unknown protocol {name!r}, expected one of {VALID_PROTOCOLS}",
        )
    try:
        return protocol_cls(  # type: ignore[abstract]
            **dict(protocol_options or {}),
        )
    except TypeError as exc:
        raise ValueError(
            f"invalid protocol_options for protocol {name!r}: {exc}",
        ) from exc