Skip to content

Build and run agents you can see, understand and trust.

feat(model): fix dashscope structured output and add examples (#1651)

qbc9e532dba3456
diff --git a/scripts/model_examples/README.md b/scripts/model_examples/README.md
index 74861d347..704d1d844 100644
--- a/scripts/model_examples/README.md
+++ b/scripts/model_examples/README.md
@@ -13,7 +13,7 @@ scripts/model_examples/
├── _utils.py # Shared helpers (stream_and_collect)
├── test.jpeg # Sample image for multimodal tests
│
-├── openai_chat_call.py # OpenAI Chat Completions – basic + tool call
+├── openai_chat_call.py # OpenAI Chat Completions – basic + tool call + structured output
├── openai_chat_multiagent.py # OpenAI Chat Completions – multi-agent conversation
├── openai_chat_multimodal.py # OpenAI Chat Completions – image/text multimodal
├── openai_chat_multiagent_multimodal.py
@@ -63,9 +63,9 @@ scripts/model_examples/
| Suffix | File Pattern | What it covers |
|---|---|---|
-| `call` | `*_call.py` | Basic text call + two-round tool calling |
+| `call` | `*_call.py` | Basic text call + two-round tool calling + structured output |
| `multiagent` | `*_multiagent.py` | Multi-agent scenario using `MultiAgentFormatter` |
-| `multimodal` | `*_multimodal.py` | Image + text multimodal input |
+| `multimodal` | `*_multimodal.py` | Image + text multimodal input (some providers also test audio/video) |
| `multiagent_multimodal` | `*_multiagent_multimodal.py` | Multi-agent + multimodal combined |
---
@@ -212,7 +212,10 @@ Each script typically defines two or more async functions:
- `example_simple_call()` – basic text call with streaming
- `example_tool_call()` – two-round conversation with tool/function calling
-- `example_image_url()` – image + text input (in `_multimodal.py` variants)
+- `example_structured_output()` – force a Pydantic-validated JSON output (in `_call.py` variants, uses a thinking-enabled model)
+- `example_image_url()` / `example_image_local_path()` / `example_image_base64()` – image + text input (in `_multimodal.py` variants)
+- `example_audio()` – audio input (e.g. `openai_chat_multimodal.py`, `dashscope_multimodal.py`)
+- `example_video()` – video input (e.g. `dashscope_multimodal.py`)
---
diff --git a/scripts/model_examples/anthropic_call.py b/scripts/model_examples/anthropic_call.py
index 20da699d1..f398f07a5 100644
--- a/scripts/model_examples/anthropic_call.py
+++ b/scripts/model_examples/anthropic_call.py
@@ -4,6 +4,8 @@ import asyncio
import json
import os
+from pydantic import BaseModel, Field
+
from _utils import stream_and_collect
from agentscope.message import (
Msg,
@@ -130,6 +132,60 @@ async def example_tool_call() -> None:
await stream_and_collect(await model(msgs))
+# ---------------------------------------------------------------------------
+# Example 3: Structured output
+# ---------------------------------------------------------------------------
+
+
+class MathSolution(BaseModel):
+ """Structured solution to a math problem."""
+
+ problem: str = Field(description="The original problem statement")
+ answer: float = Field(description="The final numeric answer")
+ steps: list[str] = Field(
+ description="Step-by-step reasoning leading to the answer",
+ )
+
+
+async def example_structured_output() -> None:
+ """Call the Anthropic model and force a structured (JSON) output."""
+ model = AnthropicChatModel(
+ credential=AnthropicCredential(
+ api_key=os.environ["ANTHROPIC_API_KEY"],
+ ),
+ model="claude-opus-4-5",
+ stream=True,
+ context_size=1_000_000,
+ parameters=AnthropicChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=4096,
+ ),
+ )
+
+ msgs = [
+ Msg(
+ name="user",
+ content=[
+ TextBlock(
+ text=(
+ "Solve this: A train travels at 60 km/h for "
+ "2.5 hours. How far does it travel in km?"
+ ),
+ ),
+ ],
+ role="user",
+ ),
+ ]
+
+ print("=== Structured Output ===")
+ response = await model.generate_structured_output(
+ msgs,
+ structured_model=MathSolution,
+ )
+ print(response.content)
+
+
if __name__ == "__main__":
asyncio.run(example_simple_call())
asyncio.run(example_tool_call())
+ asyncio.run(example_structured_output())
diff --git a/scripts/model_examples/dashscope_call.py b/scripts/model_examples/dashscope_call.py
index 9c496a915..5e869393f 100644
--- a/scripts/model_examples/dashscope_call.py
+++ b/scripts/model_examples/dashscope_call.py
@@ -4,6 +4,8 @@ import asyncio
import json
import os
+from pydantic import BaseModel, Field
+
from _utils import stream_and_collect
from agentscope.message import (
Msg,
@@ -127,6 +129,57 @@ async def example_tool_call() -> None:
await stream_and_collect(await model(msgs))
+# ---------------------------------------------------------------------------
+# Example 3: Structured output
+# ---------------------------------------------------------------------------
+
+
+class MathSolution(BaseModel):
+ """Structured solution to a math problem."""
+
+ problem: str = Field(description="The original problem statement")
+ answer: float = Field(description="The final numeric answer")
+ steps: list[str] = Field(
+ description="Step-by-step reasoning leading to the answer",
+ )
+
+
+async def example_structured_output() -> None:
+ """Call the DashScope model and force a structured (JSON) output."""
+ model = DashScopeChatModel(
+ credential=DashScopeCredential(
+ api_key=os.environ["DASHSCOPE_API_KEY"],
+ ),
+ model="qwen3.5-plus",
+ stream=True,
+ context_size=1_000_000,
+ parameters=DashScopeChatModel.Parameters(thinking_enable=True),
+ )
+
+ msgs = [
+ Msg(
+ name="user",
+ content=[
+ TextBlock(
+ text=(
+ "Solve this: A train travels at 60 km/h for "
+ "2.5 hours. How far does it travel in km?"
+ ),
+ ),
+ ],
+ role="user",
+ ),
+ ]
+
+ print("=== Structured Output ===")
+ response = await model.generate_structured_output(
+ msgs,
+ structured_model=MathSolution,
+ )
+ print(response.content)
+
+
if __name__ == "__main__":
asyncio.run(example_simple_call())
asyncio.run(example_tool_call())
+ asyncio.run(example_structured_output())
diff --git a/scripts/model_examples/deepseek_call.py b/scripts/model_examples/deepseek_call.py
index 0d5910f3c..4854e515d 100644
--- a/scripts/model_examples/deepseek_call.py
+++ b/scripts/model_examples/deepseek_call.py
@@ -9,6 +9,8 @@ import asyncio
import json
import os
+from pydantic import BaseModel, Field
+
from _utils import stream_and_collect
from agentscope.message import (
Msg,
@@ -131,6 +133,59 @@ async def example_tool_call() -> None:
await stream_and_collect(await model(msgs))
+# ---------------------------------------------------------------------------
+# Example 3: Structured output
+# ---------------------------------------------------------------------------
+
+
+class MathSolution(BaseModel):
+ """Structured solution to a math problem."""
+
+ problem: str = Field(description="The original problem statement")
+ answer: float = Field(description="The final numeric answer")
+ steps: list[str] = Field(
+ description="Step-by-step reasoning leading to the answer",
+ )
+
+
+async def example_structured_output() -> None:
+ """Call the DeepSeek reasoning model and force a structured output.
+
+ Uses deepseek-reasoner — the reasoning model with chain-of-thought.
+ """
+ model = DeepSeekChatModel(
+ credential=DeepSeekCredential(
+ api_key=os.environ["DEEPSEEK_API_KEY"],
+ ),
+ model="deepseek-reasoner",
+ stream=True,
+ context_size=65_536,
+ )
+
+ msgs = [
+ Msg(
+ name="user",
+ content=[
+ TextBlock(
+ text=(
+ "Solve this: A train travels at 60 km/h for "
+ "2.5 hours. How far does it travel in km?"
+ ),
+ ),
+ ],
+ role="user",
+ ),
+ ]
+
+ print("=== Structured Output ===")
+ response = await model.generate_structured_output(
+ msgs,
+ structured_model=MathSolution,
+ )
+ print(response.content)
+
+
if __name__ == "__main__":
asyncio.run(example_simple_call())
asyncio.run(example_tool_call())
+ asyncio.run(example_structured_output())
diff --git a/scripts/model_examples/gemini_call.py b/scripts/model_examples/gemini_call.py
index c08a2ad8e..c99f5388f 100644
--- a/scripts/model_examples/gemini_call.py
+++ b/scripts/model_examples/gemini_call.py
@@ -4,6 +4,8 @@ import asyncio
import json
import os
+from pydantic import BaseModel, Field
+
from _utils import stream_and_collect
from agentscope.message import (
Msg,
@@ -130,6 +132,60 @@ async def example_tool_call() -> None:
await stream_and_collect(await model(msgs))
+# ---------------------------------------------------------------------------
+# Example 3: Structured output
+# ---------------------------------------------------------------------------
+
+
+class MathSolution(BaseModel):
+ """Structured solution to a math problem."""
+
+ problem: str = Field(description="The original problem statement")
+ answer: float = Field(description="The final numeric answer")
+ steps: list[str] = Field(
+ description="Step-by-step reasoning leading to the answer",
+ )
+
+
+async def example_structured_output() -> None:
+ """Call the Gemini model and force a structured (JSON) output."""
+ model = GeminiChatModel(
+ credential=GeminiCredential(
+ api_key=os.environ["GEMINI_API_KEY"],
+ ),
+ model="gemini-2.5-flash",
+ stream=True,
+ context_size=1_048_576,
+ parameters=GeminiChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=8192,
+ ),
+ )
+
+ msgs = [
+ Msg(
+ name="user",
+ content=[
+ TextBlock(
+ text=(
+ "Solve this: A train travels at 60 km/h for "
+ "2.5 hours. How far does it travel in km?"
+ ),
+ ),
+ ],
+ role="user",
+ ),
+ ]
+
+ print("=== Structured Output ===")
+ response = await model.generate_structured_output(
+ msgs,
+ structured_model=MathSolution,
+ )
+ print(response.content)
+
+
if __name__ == "__main__":
asyncio.run(example_simple_call())
asyncio.run(example_tool_call())
+ asyncio.run(example_structured_output())
diff --git a/scripts/model_examples/moonshot_call.py b/scripts/model_examples/moonshot_call.py
index 625bd59f7..74e6d01ba 100644
--- a/scripts/model_examples/moonshot_call.py
+++ b/scripts/model_examples/moonshot_call.py
@@ -4,6 +4,8 @@ import asyncio
import json
import os
+from pydantic import BaseModel, Field
+
from _utils import stream_and_collect
from agentscope.message import (
Msg,
@@ -122,6 +124,57 @@ async def example_tool_call() -> None:
await stream_and_collect(await model(msgs))
+# ---------------------------------------------------------------------------
+# Example 3: Structured output
+# ---------------------------------------------------------------------------
+
+
+class MathSolution(BaseModel):
+ """Structured solution to a math problem."""
+
+ problem: str = Field(description="The original problem statement")
+ answer: float = Field(description="The final numeric answer")
+ steps: list[str] = Field(
+ description="Step-by-step reasoning leading to the answer",
+ )
+
+
+async def example_structured_output() -> None:
+ """Call the Moonshot model and force a structured (JSON) output."""
+ model = MoonshotChatModel(
+ credential=MoonshotCredential(
+ api_key=os.environ["MOONSHOT_API_KEY"],
+ ),
+ model="kimi-k2.6",
+ stream=True,
+ context_size=262_144,
+ parameters=MoonshotChatModel.Parameters(thinking_enable=True),
+ )
+
+ msgs = [
+ Msg(
+ name="user",
+ content=[
+ TextBlock(
+ text=(
+ "Solve this: A train travels at 60 km/h for "
+ "2.5 hours. How far does it travel in km?"
+ ),
+ ),
+ ],
+ role="user",
+ ),
+ ]
+
+ print("=== Structured Output ===")
+ response = await model.generate_structured_output(
+ msgs,
+ structured_model=MathSolution,
+ )
+ print(response.content)
+
+
if __name__ == "__main__":
asyncio.run(example_simple_call())
asyncio.run(example_tool_call())
+ asyncio.run(example_structured_output())
diff --git a/scripts/model_examples/ollama_call.py b/scripts/model_examples/ollama_call.py
index 50b795cc4..d633f08e9 100644
--- a/scripts/model_examples/ollama_call.py
+++ b/scripts/model_examples/ollama_call.py
@@ -10,6 +10,8 @@ Pull the model first if you haven't already:
import asyncio
import json
+from pydantic import BaseModel, Field
+
from _utils import stream_and_collect
from agentscope.message import (
Msg,
@@ -130,6 +132,57 @@ async def example_tool_call() -> None:
await stream_and_collect(await model(msgs))
+# ---------------------------------------------------------------------------
+# Example 3: Structured output
+# ---------------------------------------------------------------------------
+
+
+class MathSolution(BaseModel):
+ """Structured solution to a math problem."""
+
+ problem: str = Field(description="The original problem statement")
+ answer: float = Field(description="The final numeric answer")
+ steps: list[str] = Field(
+ description="Step-by-step reasoning leading to the answer",
+ )
+
+
+async def example_structured_output() -> None:
+ """Call the Ollama model and force a structured (JSON) output."""
+ model = OllamaChatModel(
+ credential=OllamaCredential(
+ host="http://localhost:11434",
+ ),
+ model="qwen3:14b",
+ stream=True,
+ context_size=40_960,
+ parameters=OllamaChatModel.Parameters(thinking_enable=True),
+ )
+
+ msgs = [
+ Msg(
+ name="user",
+ content=[
+ TextBlock(
+ text=(
+ "Solve this: A train travels at 60 km/h for "
+ "2.5 hours. How far does it travel in km?"
+ ),
+ ),
+ ],
+ role="user",
+ ),
+ ]
+
+ print("=== Structured Output ===")
+ response = await model.generate_structured_output(
+ msgs,
+ structured_model=MathSolution,
+ )
+ print(response.content)
+
+
if __name__ == "__main__":
asyncio.run(example_simple_call())
asyncio.run(example_tool_call())
+ asyncio.run(example_structured_output())
diff --git a/scripts/model_examples/openai_chat_call.py b/scripts/model_examples/openai_chat_call.py
index 4bf9a3cdb..132ab59a6 100644
--- a/scripts/model_examples/openai_chat_call.py
+++ b/scripts/model_examples/openai_chat_call.py
@@ -4,6 +4,8 @@ import asyncio
import json
import os
+from pydantic import BaseModel, Field
+
from _utils import stream_and_collect
from agentscope.message import (
Msg,
@@ -128,6 +130,59 @@ async def example_tool_call() -> None:
await stream_and_collect(await model(msgs))
+# ---------------------------------------------------------------------------
+# Example 3: Structured output
+# ---------------------------------------------------------------------------
+
+
+class MathSolution(BaseModel):
+ """Structured solution to a math problem."""
+
+ problem: str = Field(description="The original problem statement")
+ answer: float = Field(description="The final numeric answer")
+ steps: list[str] = Field(
+ description="Step-by-step reasoning leading to the answer",
+ )
+
+
+async def example_structured_output() -> None:
+ """Call the OpenAI Chat model and force a structured (JSON) output."""
+ model = OpenAIChatModel(
+ credential=OpenAICredential(
+ api_key=os.environ["OPENAI_API_KEY"],
+ ),
+ model="o4-mini",
+ stream=True,
+ context_size=200_000,
+ parameters=OpenAIChatModel.Parameters(
+ reasoning_effort="low",
+ ),
+ )
+
+ msgs = [
+ Msg(
+ name="user",
+ content=[
+ TextBlock(
+ text=(
+ "Solve this: A train travels at 60 km/h for "
+ "2.5 hours. How far does it travel in km?"
+ ),
+ ),
+ ],
+ role="user",
+ ),
+ ]
+
+ print("=== Structured Output ===")
+ response = await model.generate_structured_output(
+ msgs,
+ structured_model=MathSolution,
+ )
+ print(response.content)
+
+
if __name__ == "__main__":
asyncio.run(example_simple_call())
asyncio.run(example_tool_call())
+ asyncio.run(example_structured_output())
diff --git a/scripts/model_examples/openai_response_call.py b/scripts/model_examples/openai_response_call.py
index 6aa7ddf28..62c9195f8 100644
--- a/scripts/model_examples/openai_response_call.py
+++ b/scripts/model_examples/openai_response_call.py
@@ -9,6 +9,8 @@ import asyncio
import json
import os
+from pydantic import BaseModel, Field
+
from _utils import stream_and_collect
from agentscope.message import (
Msg,
@@ -36,7 +38,7 @@ async def example_simple_call() -> None:
model="o1",
stream=True,
context_size=200_000,
- parameters=OpenAIResponseModel.Parameters(reasoning_effort="high"),
+ parameters=OpenAIResponseModel.Parameters(reasoning_effort="low"),
)
msgs = [
@@ -80,7 +82,7 @@ async def example_tool_call() -> None:
model="o1",
stream=True,
context_size=200_000,
- parameters=OpenAIResponseModel.Parameters(reasoning_effort="high"),
+ parameters=OpenAIResponseModel.Parameters(reasoning_effort="low"),
)
msgs = [
@@ -132,6 +134,57 @@ async def example_tool_call() -> None:
await stream_and_collect(await model(msgs))
+# ---------------------------------------------------------------------------
+# Example 3: Structured output
+# ---------------------------------------------------------------------------
+
+
+class MathSolution(BaseModel):
+ """Structured solution to a math problem."""
+
+ problem: str = Field(description="The original problem statement")
+ answer: float = Field(description="The final numeric answer")
+ steps: list[str] = Field(
+ description="Step-by-step reasoning leading to the answer",
+ )
+
+
+async def example_structured_output() -> None:
+ """Call the OpenAI Response model and force a structured (JSON) output."""
+ model = OpenAIResponseModel(
+ credential=OpenAICredential(
+ api_key=os.environ["OPENAI_API_KEY"],
+ ),
+ model="o1",
+ stream=True,
+ context_size=200_000,
+ parameters=OpenAIResponseModel.Parameters(reasoning_effort="low"),
+ )
+
+ msgs = [
+ Msg(
+ name="user",
+ content=[
+ TextBlock(
+ text=(
+ "Solve this: A train travels at 60 km/h for "
+ "2.5 hours. How far does it travel in km?"
+ ),
+ ),
+ ],
+ role="user",
+ ),
+ ]
+
+ print("=== Structured Output ===")
+ response = await model.generate_structured_output(
+ msgs,
+ structured_model=MathSolution,
+ )
+ print(response.content)
+
+
if __name__ == "__main__":
asyncio.run(example_simple_call())
asyncio.run(example_tool_call())
+ asyncio.run(example_structured_output())
diff --git a/scripts/model_examples/xai_call.py b/scripts/model_examples/xai_call.py
index f6b7b5f4b..97e88d249 100644
--- a/scripts/model_examples/xai_call.py
+++ b/scripts/model_examples/xai_call.py
@@ -9,6 +9,8 @@ import asyncio
import json
import os
+from pydantic import BaseModel, Field
+
from _utils import stream_and_collect
from agentscope.message import (
Msg,
@@ -36,7 +38,7 @@ async def example_simple_call() -> None:
model="grok-3-mini",
stream=True,
context_size=131_072,
- parameters=XAIChatModel.Parameters(reasoning_effort="high"),
+ parameters=XAIChatModel.Parameters(reasoning_effort="low"),
)
msgs = [
@@ -131,6 +133,57 @@ async def example_tool_call() -> None:
await stream_and_collect(await model(msgs))
+# ---------------------------------------------------------------------------
+# Example 3: Structured output
+# ---------------------------------------------------------------------------
+
+
+class MathSolution(BaseModel):
+ """Structured solution to a math problem."""
+
+ problem: str = Field(description="The original problem statement")
+ answer: float = Field(description="The final numeric answer")
+ steps: list[str] = Field(
+ description="Step-by-step reasoning leading to the answer",
+ )
+
+
+async def example_structured_output() -> None:
+ """Call the xAI reasoning model and force a structured (JSON) output."""
+ model = XAIChatModel(
+ credential=XAICredential(
+ api_key=os.environ["XAI_API_KEY"],
+ ),
+ model="grok-3-mini",
+ stream=True,
+ context_size=131_072,
+ parameters=XAIChatModel.Parameters(reasoning_effort="low"),
+ )
+
+ msgs = [
+ Msg(
+ name="user",
+ content=[
+ TextBlock(
+ text=(
+ "Solve this: A train travels at 60 km/h for "
+ "2.5 hours. How far does it travel in km?"
+ ),
+ ),
+ ],
+ role="user",
+ ),
+ ]
+
+ print("=== Structured Output ===")
+ response = await model.generate_structured_output(
+ msgs,
+ structured_model=MathSolution,
+ )
+ print(response.content)
+
+
if __name__ == "__main__":
asyncio.run(example_simple_call())
asyncio.run(example_tool_call())
+ asyncio.run(example_structured_output())
diff --git a/src/agentscope/model/_base.py b/src/agentscope/model/_base.py
index de4218a4f..8a8bd59f8 100644
--- a/src/agentscope/model/_base.py
+++ b/src/agentscope/model/_base.py
@@ -413,6 +413,7 @@ class ChatModelBase:
model_name: str,
messages: list[Msg],
structured_model: Type[BaseModel] | dict,
+ tool_choice: ToolChoice | None = None,
**kwargs: Any,
) -> StructuredResponse:
"""This function constructs a 'generate_structured_output' tool to
@@ -423,11 +424,28 @@ class ChatModelBase:
API supports structured output, you can override this method to
provide a more accurate implementation.
- Note this method use the "required" tool choice to force LLM to call
- the 'generate_structured_output' method, and adds instructions into
- the input messages. However, LLM APIs that doesn't support
- "required" tool choice may still fail (e.g. generate text output and
- ignore the tool call, or fail in validation).
+ Note by default this method forces LLM to call the
+ 'generate_structured_output' tool via tool_choice, and adds
+ instructions into the input messages. Subclasses whose underlying
+ API rejects forced tool_choice in certain modes (e.g. DashScope in
+ thinking mode) can pass ``tool_choice=ToolChoice(mode="auto")`` and
+ rely solely on the injected system-reminder prompt. LLM APIs that
+ don't support "required" tool choice may still fail (e.g. generate
+ text output and ignore the tool call, or fail in validation).
+
+ Args:
+ model_name (`str`):
+ The model name to use for this call.
+ messages (`list[Msg]`):
+ The context for the LLM to generate the structured output.
+ structured_model (`Type[BaseModel] | dict`):
+ A Pydantic model class or a JSON schema dict describing the
+ required output structure.
+ tool_choice (`ToolChoice | None`, defaults to `None`):
+ The tool_choice forwarded to ``_call_api``. When ``None``,
+ defaults to forcing the ``generate_structured_output`` tool.
+ **kwargs (`Any`):
+ Additional keyword arguments forwarded to ``_call_api``.
"""
if isinstance(structured_model, dict):
@@ -436,6 +454,8 @@ class ChatModelBase:
input_schema = structured_model.model_json_schema()
func_name = "generate_structured_output"
+ if tool_choice is None:
+ tool_choice = ToolChoice(mode=func_name)
instruction = (
"<system-reminder>Now you **MUST** call the tool named "
f"'{func_name}' to generate the structured output required "
@@ -469,9 +489,7 @@ class ChatModelBase:
},
},
],
- tool_choice=ToolChoice(
- mode=func_name,
- ),
+ tool_choice=tool_choice,
**kwargs,
)
diff --git a/src/agentscope/model/_dashscope/_model.py b/src/agentscope/model/_dashscope/_model.py
index 4737fbeaa..f3d7fe0e9 100644
--- a/src/agentscope/model/_dashscope/_model.py
+++ b/src/agentscope/model/_dashscope/_model.py
@@ -3,12 +3,12 @@
import warnings
from collections import OrderedDict
from datetime import datetime
-from typing import Any, AsyncGenerator, List, Literal, TYPE_CHECKING
+from typing import Any, AsyncGenerator, List, Literal, Type, TYPE_CHECKING
from pydantic import BaseModel, Field
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
-from .._model_response import ChatResponse
+from .._model_response import ChatResponse, StructuredResponse
from .._model_usage import ChatUsage
from ...credential import DashScopeCredential
from ...formatter import FormatterBase, DashScopeChatFormatter
@@ -517,3 +517,50 @@ class DashScopeChatModel(ChatModelBase):
return fmt_tools, "auto"
return fmt_tools, mode
+
+ async def _call_api_with_structured_output(
+ self,
+ model_name: str,
+ messages: list[Msg],
+ structured_model: Type[BaseModel] | dict,
+ tool_choice: ToolChoice | None = None,
+ **kwargs: Any,
+ ) -> StructuredResponse:
+ """DashScope-specific override for structured output.
+
+ DashScope rejects ``tool_choice="required"`` or an object-form
+ ``tool_choice`` when thinking mode is enabled. In that case we
+ default ``tool_choice`` to ``"auto"`` and rely on the base class's
+ injected system-reminder prompt to guide the model. When thinking
+ is disabled, this falls through to the base implementation.
+
+ Args:
+ model_name (`str`):
+ The model name to use for this call.
+ messages (`list[Msg]`):
+ The context for the LLM to generate the structured output.
+ structured_model (`Type[BaseModel] | dict`):
+ A Pydantic model class or a JSON schema dict describing the
+ required output structure.
+ tool_choice (`ToolChoice | None`, defaults to `None`):
+ The tool_choice forwarded to ``_call_api``. When ``None``
+ and thinking mode is enabled, it is downgraded to
+ ``ToolChoice(mode="auto")``; otherwise the base default
+ (force the structured-output tool) is used.
+ **kwargs (`Any`):
+ Additional keyword arguments forwarded to ``_call_api``.
+
+ Returns:
+ `StructuredResponse`:
+ The structured response whose ``content`` is the validated
+ output dict matching ``structured_model``.
+ """
+ if tool_choice is None and self.parameters.thinking_enable:
+ tool_choice = ToolChoice(mode="auto")
+ return await super()._call_api_with_structured_output(
+ model_name=model_name,
+ messages=messages,
+ structured_model=structured_model,
+ tool_choice=tool_choice,
+ **kwargs,
+ )