Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(model): add Volcengine Ark chat model support (#2532)
DiegoCluv731febc501747
diff --git a/README.md b/README.mdindex 70bcec8a7..d60bcd5c4 100644--- a/README.md+++ b/README.md@@ -127,7 +127,7 @@ The SDK layer — compose an agent from a rich set of building blocks:|---|---|| [**ReAct**](https://docs.agentscope.io/latest/en/building-blocks/agent/overview) | Reasoning-acting loop with structured output, realtime interruption & resume, and batched (sequential / concurrent) tool acting || [**Toolkit**](https://docs.agentscope.io/latest/en/building-blocks/tool/overview) | Agentic tool management over Python tools, MCP servers, and skills; ships with built-in coding tools (shell, file edit, search) and task/plan tools |-| [**Model**](https://docs.agentscope.io/latest/en/building-blocks/model/overview) | LLM, embedding, and TTS across major providers (OpenAI, Anthropic, Gemini, DashScope, DeepSeek, Moonshot, xAI, Ollama) |+| [**Model**](https://docs.agentscope.io/latest/en/building-blocks/model/overview) | LLM, embedding, and TTS across major providers (OpenAI, Anthropic, Gemini, DashScope, DeepSeek, Moonshot, Volcengine, xAI, Ollama) || [**Context**](https://docs.agentscope.io/latest/en/building-blocks/context/overview) | Automatic compaction, tool-result offload, and context injection (system prompt, RAG, memory) via built-in middleware || [**Event System**](https://docs.agentscope.io/latest/en/building-blocks/message-and-event) | Unified event bus streaming reasoning, tool calls, and multimodal content (text, image, audio) to the frontend || [**Permission & HITL**](https://docs.agentscope.io/latest/en/building-blocks/permission-system/overview) | Fine-grained control over tools and resources, confirmation, bypass mode |diff --git a/README_zh.md b/README_zh.mdindex 675f1ad03..510638c05 100644--- a/README_zh.md+++ b/README_zh.md@@ -127,7 +127,7 @@ SDK 层 —— 用一整套丰富的构建模块组合出你的智能体:|---|---|| [**ReAct**](https://docs.agentscope.io/latest/zh/building-blocks/agent/overview) | 推理-行动循环,支持结构化输出、实时中断与恢复、以及批量(顺序 / 并发)工具执行 || [**工具集**](https://docs.agentscope.io/latest/zh/building-blocks/tool/overview) | 智能体自主工具管理(囊括 Python 工具、MCP 与 Skill);内置编码工具(Shell、文件编辑、搜索)与任务/规划工具开箱即用 |-| [**模型**](https://docs.agentscope.io/latest/zh/building-blocks/model/overview) | LLM、Embedding、TTS,覆盖主流厂商(OpenAI、Anthropic、Gemini、DashScope、DeepSeek、Moonshot、xAI、Ollama) |+| [**模型**](https://docs.agentscope.io/latest/zh/building-blocks/model/overview) | LLM、Embedding、TTS,覆盖主流厂商(OpenAI、Anthropic、Gemini、DashScope、DeepSeek、Moonshot、Volcengine、xAI、Ollama) || [**上下文**](https://docs.agentscope.io/latest/zh/building-blocks/context/overview) | 自动压缩、工具结果卸载、以及上下文注入(系统提示、RAG、记忆),均由内置中间件实现 || [**事件系统**](https://docs.agentscope.io/latest/zh/building-blocks/message-and-event) | 统一事件总线,将推理、工具调用与多模态内容(文本、图像、音频)流式推送到前端 || [**权限与 HITL**](https://docs.agentscope.io/latest/zh/building-blocks/permission-system/overview) | 对工具和资源的细粒度控制、确认、bypass 模式 |diff --git a/scripts/model_examples/README.md b/scripts/model_examples/README.mdindex 704d1d844..fe9bfcb07 100644--- a/scripts/model_examples/README.md+++ b/scripts/model_examples/README.md@@ -46,6 +46,9 @@ scripts/model_examples/├── moonshot_multimodal.py├── moonshot_multiagent_multimodal.py│+├── volcengine_call.py # Volcengine Ark / Doubao+├── volcengine_multiagent.py+│├── xai_call.py # xAI Grok├── xai_multiagent.py├── xai_multimodal.py@@ -81,6 +84,7 @@ scripts/model_examples/| `deepseek` | `DEEPSEEK_API_KEY` | Supports only `call` / `multiagent` (no multimodal) || `gemini` | `GEMINI_API_KEY` | Gemini models, supports `thinking_budget` || `moonshot` | `MOONSHOT_API_KEY` | Moonshot AI kimi-k2.6, etc. |+| `volcengine` | `VOLCENGINE_API_KEY` | Volcengine Ark / Doubao models || `xai` | `XAI_API_KEY` | Grok models, supports `reasoning_effort` || `ollama` | *(none – auto-detect)* | Local server, default `http://localhost:11434` |@@ -99,6 +103,7 @@ export DASHSCOPE_API_KEY="sk-..."export DEEPSEEK_API_KEY="sk-..."export GEMINI_API_KEY="AIza..."export MOONSHOT_API_KEY="sk-..."+export VOLCENGINE_API_KEY="..."export XAI_API_KEY="xai-..."```@@ -228,4 +233,3 @@ Ollama runs locally and requires no API key, but you must:3. If the service runs on a non-default address, set: `export OLLAMA_HOST=http://your-host:11434``run_tests.py` pings the Ollama host before running any test. If the server is unreachable, all Ollama tests are automatically skipped.-diff --git a/scripts/model_examples/run_tests.py b/scripts/model_examples/run_tests.pyindex 3a1643e53..8ad973e00 100644--- a/scripts/model_examples/run_tests.py+++ b/scripts/model_examples/run_tests.py@@ -168,6 +168,13 @@ ALL_PROVIDERS: list[Provider] = [],description="Moonshot AI (Kimi) models",),+ Provider(+ name="volcengine",+ env_var="VOLCENGINE_API_KEY",+ file_prefix="volcengine",+ supported_tests=["call", "multiagent"],+ description="Volcengine Ark / Doubao models",+ ),Provider(name="xai",env_var="XAI_API_KEY",diff --git a/scripts/model_examples/volcengine_call.py b/scripts/model_examples/volcengine_call.pynew file mode 100644index 000000000..3aeaafcf6--- /dev/null+++ b/scripts/model_examples/volcengine_call.py@@ -0,0 +1,153 @@+# -*- coding: utf-8 -*-+"""Examples of Volcengine Ark model calls."""+import asyncio+import json+import os++from pydantic import BaseModel, Field++from _utils import stream_and_collect+from agentscope.credential import VolcengineCredential+from agentscope.message import (+ Msg,+ TextBlock,+ ToolCallBlock,+ ToolResultBlock,+ ToolResultState,+)+from agentscope.model import VolcengineChatModel+from agentscope.tool import FunctionTool, Toolkit, ToolChoice+++MODEL_NAME = "doubao-seed-2-1-pro-260628"+++async def example_simple_call() -> None:+ """Call a Doubao model with a simple text message."""+ model = VolcengineChatModel(+ credential=VolcengineCredential(+ api_key=os.environ["VOLCENGINE_API_KEY"],+ ),+ model=MODEL_NAME,+ stream=True,+ parameters=VolcengineChatModel.Parameters(thinking_enable=True),+ )+ msgs = [+ Msg(+ name="user",+ content=[TextBlock(text="What is 1 + 1? Answer briefly.")],+ role="user",+ ),+ ]++ print("=== Simple Call ===")+ await stream_and_collect(await model(msgs))+++def get_weather(city: str) -> str:+ """Get the current weather for a city.++ Args:+ city: The city name to query the weather for.++ Returns:+ A description of the current weather.+ """+ return f"The weather in {city} is sunny and 25°C."+++async def example_tool_call() -> None:+ """Call a Doubao model with tool calling enabled."""+ toolkit = Toolkit(tools=[FunctionTool(get_weather)])+ tools = await toolkit.get_tool_schemas()+ model = VolcengineChatModel(+ credential=VolcengineCredential(+ api_key=os.environ["VOLCENGINE_API_KEY"],+ ),+ model=MODEL_NAME,+ stream=True,+ parameters=VolcengineChatModel.Parameters(thinking_enable=True),+ )+ msgs = [+ Msg(+ name="user",+ content=[TextBlock(text="What is the weather in Beijing?")],+ role="user",+ ),+ ]++ print("=== Tool Call - Round 1 ===")+ response = await stream_and_collect(+ await model(msgs, tools=tools, tool_choice=ToolChoice(mode="auto")),+ )+ print(response)++ tool_calls = [b for b in response.content if isinstance(b, ToolCallBlock)]+ if tool_calls:+ tool_results = []+ for tool_call in tool_calls:+ result = get_weather(**json.loads(tool_call.input))+ tool_results.append(+ ToolResultBlock(+ id=tool_call.id,+ name=tool_call.name,+ output=result,+ state=ToolResultState.SUCCESS,+ ),+ )+ msgs += [+ Msg(name="assistant", content=response.content, role="assistant"),+ Msg(name="tool", content=tool_results, role="assistant"),+ ]++ print("=== Tool Call - Round 2 (Final) ===")+ await stream_and_collect(await model(msgs))+++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 a Doubao model and request structured output."""+ model = VolcengineChatModel(+ credential=VolcengineCredential(+ api_key=os.environ["VOLCENGINE_API_KEY"],+ ),+ model=MODEL_NAME,+ stream=True,+ parameters=VolcengineChatModel.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/volcengine_multiagent.py b/scripts/model_examples/volcengine_multiagent.pynew file mode 100644index 000000000..a1c96e58d--- /dev/null+++ b/scripts/model_examples/volcengine_multiagent.py@@ -0,0 +1,52 @@+# -*- coding: utf-8 -*-+"""Example of Volcengine Ark calls with its multi-agent formatter."""+import asyncio+import os++from _utils import stream_and_collect+from agentscope.credential import VolcengineCredential+from agentscope.formatter import VolcengineMultiAgentFormatter+from agentscope.message import Msg, TextBlock+from agentscope.model import VolcengineChatModel+++async def example_multiagent() -> None:+ """Ask a Doubao model to summarize a multi-agent conversation."""+ model = VolcengineChatModel(+ credential=VolcengineCredential(+ api_key=os.environ["VOLCENGINE_API_KEY"],+ ),+ model="doubao-seed-2-1-pro-260628",+ stream=True,+ parameters=VolcengineChatModel.Parameters(thinking_enable=True),+ formatter=VolcengineMultiAgentFormatter(),+ )+ msgs = [+ Msg(+ name="system",+ content="You are a helpful moderator.",+ role="system",+ ),+ Msg(+ name="alice",+ content=[TextBlock(text="The weather is sunny today.")],+ role="user",+ ),+ Msg(+ name="bob",+ content=[TextBlock(text="It is a good day for a walk.")],+ role="assistant",+ ),+ Msg(+ name="moderator",+ content="Summarize the conversation in one sentence.",+ role="user",+ ),+ ]++ print("=== Multi-Agent Formatter Call ===")+ await stream_and_collect(await model(msgs))+++if __name__ == "__main__":+ asyncio.run(example_multiagent())diff --git a/src/agentscope/credential/__init__.py b/src/agentscope/credential/__init__.pyindex 7368f3b93..71d1df981 100644--- a/src/agentscope/credential/__init__.py+++ b/src/agentscope/credential/__init__.py@@ -10,6 +10,7 @@ from ._moonshot import MoonshotCredentialfrom ._ollama import OllamaCredentialfrom ._openai import OpenAICredentialfrom ._xai import XAICredential+from ._volcengine import VolcengineCredentialfrom ._factory import CredentialFactory@@ -23,5 +24,6 @@ __all__ = ["OllamaCredential","OpenAICredential","XAICredential",+ "VolcengineCredential","CredentialFactory",]diff --git a/src/agentscope/credential/_factory.py b/src/agentscope/credential/_factory.pyindex 7af1ab30b..3f758650d 100644--- a/src/agentscope/credential/_factory.py+++ b/src/agentscope/credential/_factory.py@@ -12,6 +12,7 @@ from ._moonshot import MoonshotCredentialfrom ._ollama import OllamaCredentialfrom ._openai import OpenAICredentialfrom ._xai import XAICredential+from ._volcengine import VolcengineCredentialfrom ._base import CredentialBase@@ -42,6 +43,7 @@ class CredentialFactory:OllamaCredential,OpenAICredential,XAICredential,+ VolcengineCredential,]_adapter: TypeAdapter[CredentialBase] | None = Nonediff --git a/src/agentscope/credential/_volcengine.py b/src/agentscope/credential/_volcengine.pynew file mode 100644index 000000000..81b1c7edb--- /dev/null+++ b/src/agentscope/credential/_volcengine.py@@ -0,0 +1,42 @@+# -*- coding: utf-8 -*-+"""The Volcengine credential."""++from typing import Literal, Type, TYPE_CHECKING++from pydantic import ConfigDict, Field, SecretStr++from ._base import CredentialBase++if TYPE_CHECKING:+ from ..model import ChatModelBase++_VOLCENGINE_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3"+++class VolcengineCredential(CredentialBase):+ """The Volcengine credential model."""++ model_config = ConfigDict(+ title="Volcengine Ark API",+ )++ type: Literal["volcengine_credential"] = "volcengine_credential"+ """The credential type."""++ api_key: SecretStr = Field(+ description="The Volcengine Ark API key.",+ )+ """The API key."""++ base_url: str = Field(+ default=_VOLCENGINE_BASE_URL,+ description="The base URL for the Volcengine Ark API.",+ )+ """The base URL for the Volcengine API."""++ @classmethod+ def get_chat_model_class(cls) -> Type["ChatModelBase"]:+ """Return the VolcengineChatModel class."""+ from ..model import VolcengineChatModel++ return VolcengineChatModeldiff --git a/src/agentscope/formatter/__init__.py b/src/agentscope/formatter/__init__.pyindex 0594040e8..7320a2fa3 100644--- a/src/agentscope/formatter/__init__.py+++ b/src/agentscope/formatter/__init__.py@@ -38,6 +38,10 @@ from ._xai_formatter import (XAIChatFormatter,XAIMultiAgentFormatter,)+from ._volcengine_formatter import (+ VolcengineChatFormatter,+ VolcengineMultiAgentFormatter,+)__all__ = ["FormatterBase",@@ -59,4 +63,6 @@ __all__ = ["MoonshotMultiAgentFormatter","XAIChatFormatter","XAIMultiAgentFormatter",+ "VolcengineChatFormatter",+ "VolcengineMultiAgentFormatter",]diff --git a/src/agentscope/formatter/_volcengine_formatter.py b/src/agentscope/formatter/_volcengine_formatter.pynew file mode 100644index 000000000..c5a3f1b3b--- /dev/null+++ b/src/agentscope/formatter/_volcengine_formatter.py@@ -0,0 +1,406 @@+# -*- coding: utf-8 -*-+"""The Volcengine Ark formatter module."""++from fnmatch import fnmatch+from typing import Any++from pydantic import Field++from ._openai_formatter import _OpenAIFormatterBase+from .._logging import logger+from ..message import (+ Msg,+ TextBlock,+ DataBlock,+ ThinkingBlock,+ HintBlock,+ ToolCallBlock,+ ToolResultBlock,+ URLSource,+ Base64Source,+)+++class _VolcengineFormatterBase(_OpenAIFormatterBase):+ """Base formatter with shared Ark multimodal conversion logic."""++ def _format_volcengine_data_block(+ self,+ block: DataBlock,+ ) -> dict[str, Any] | None:+ """Format supported image and video data for the Ark Chat API.++ Args:+ block (`DataBlock`):+ The data block to format.++ Returns:+ `dict[str, Any] | None`:+ The formatted content block, or ``None`` when unsupported.+ """+ if not any(+ fnmatch(block.source.media_type, pattern)+ for pattern in self.supported_input_media_types+ ):+ logger.warning(+ "Unsupported media type %s for Volcengine Ark API. "+ "Supported types: %s. This block will be skipped.",+ block.source.media_type,+ ", ".join(self.supported_input_media_types),+ )+ return None++ main_type = block.source.media_type.split("/")[0]+ if main_type == "image":+ return self._format_image_source(block.source)+ if main_type == "video":+ return self._format_video_source(block.source)++ logger.warning(+ "Unsupported main media type %s for Volcengine Ark API. "+ "This block will be skipped.",+ main_type,+ )+ return None++ def _format_video_source(+ self,+ source: URLSource | Base64Source,+ ) -> dict[str, Any]:+ """Convert a video source to Ark's ``video_url`` format. Ark takes+ the same URL / base64 data URI as images, so reuse that conversion.++ Args:+ source (`URLSource | Base64Source`):+ A remote, local, or base64-encoded video source.++ Returns:+ `dict[str, Any]`:+ A video content block accepted by the Ark Chat API.+ """+ return {+ "type": "video_url",+ "video_url": self._format_image_source(source)["image_url"],+ }+++class VolcengineChatFormatter(_VolcengineFormatterBase):+ """The Volcengine Ark formatter for a chatbot conversation.++ The ``role`` field identifies the user and assistant participants.+ """++ input_types: list[str] = Field(+ default_factory=lambda: ["text/plain", "image/*", "video/*"],+ description=(+ "The supported input types. Defaults to "+ '``["text/plain", "image/*", "video/*"]``.'+ ),+ )++ # pylint: disable=too-many-branches+ async def format(+ self,+ msgs: list[Msg],+ ) -> list[dict[str, Any]]:+ """Format message objects into Volcengine Ark API format.++ Args:+ msgs (`list[Msg]`):+ The list of message objects to format.++ Returns:+ `list[dict[str, Any]]`:+ The formatted messages as a list of dictionaries.+ """+ self.assert_list_of_msgs(msgs)++ messages: list[dict] = []+ for msg in msgs:+ content_blocks: list = []+ reasoning_content_blocks: list = []+ tool_calls = []++ for block in msg.get_content_blocks():+ if isinstance(block, TextBlock):+ content_blocks.append({"type": "text", "text": block.text})++ elif isinstance(block, DataBlock):+ formatted = self._format_volcengine_data_block(block)+ if formatted is not None:+ content_blocks.append(formatted)++ elif isinstance(block, ThinkingBlock):+ reasoning_content_blocks.append(block.thinking)++ elif isinstance(block, HintBlock):+ if (+ content_blocks+ or tool_calls+ or reasoning_content_blocks+ ):+ msg_flush_hint: dict[str, Any] = {+ "role": msg.role,+ "content": content_blocks or None,+ }+ if (+ msg.role == "assistant"+ and reasoning_content_blocks+ ):+ msg_flush_hint["reasoning_content"] = "\n".join(+ reasoning_content_blocks,+ )+ if tool_calls:+ msg_flush_hint["tool_calls"] = tool_calls+ messages.append(msg_flush_hint)+ content_blocks = []+ reasoning_content_blocks = []+ tool_calls = []++ if isinstance(block.hint, str):+ messages.append(+ {+ "role": "user",+ "content": [+ {"type": "text", "text": block.hint},+ ],+ },+ )+ else:+ hint_parts: list[dict[str, Any]] = []+ for sub in block.hint:+ if isinstance(sub, TextBlock):+ hint_parts.append(+ {"type": "text", "text": sub.text},+ )+ elif isinstance(sub, DataBlock):+ formatted_sub = (+ self._format_volcengine_data_block(sub)+ )+ if formatted_sub is not None:+ hint_parts.append(formatted_sub)+ if hint_parts:+ messages.append(+ {"role": "user", "content": hint_parts},+ )++ elif isinstance(block, ToolCallBlock):+ tool_calls.append(+ {+ "id": block.id,+ "type": "function",+ "function": {+ "name": block.name,+ "arguments": block.input,+ },+ },+ )++ elif isinstance(block, ToolResultBlock):+ if (+ content_blocks+ or tool_calls+ or reasoning_content_blocks+ ):+ msg_flush: dict[str, Any] = {+ "role": msg.role,+ "content": content_blocks or None,+ }+ if (+ msg.role == "assistant"+ and reasoning_content_blocks+ ):+ msg_flush["reasoning_content"] = "\n".join(+ reasoning_content_blocks,+ )+ if tool_calls:+ msg_flush["tool_calls"] = tool_calls+ messages.append(msg_flush)+ content_blocks = []+ reasoning_content_blocks = []+ tool_calls = []++ (+ textual_output,+ multimodal_data,+ ) = self.convert_tool_result_to_string(block.output)+ messages.append(+ {+ "role": "tool",+ "tool_call_id": block.id,+ "content": textual_output,+ "name": block.name,+ },+ )++ if multimodal_data:+ promoted_content: list[dict[str, Any]] = []+ for item in multimodal_data:+ if isinstance(item, TextBlock):+ promoted_content.append(+ {"type": "text", "text": item.text},+ )+ elif isinstance(item, DataBlock):+ formatted_item = (+ self._format_volcengine_data_block(item)+ )+ if formatted_item is not None:+ promoted_content.append(formatted_item)+ if promoted_content:+ messages.append(+ {+ "role": "user",+ "name": "system-reminder",+ "content": promoted_content,+ },+ )++ else:+ logger.warning(+ "Unsupported block type %s in the message, skipped.",+ type(block),+ )++ msg_volcengine: dict[str, Any] = {+ "role": msg.role,+ "content": content_blocks or None,+ }++ # Preserve reasoning in multi-turn requests. Ark documents this+ # field as optional, so omit it for non-thinking history.+ if msg.role == "assistant" and reasoning_content_blocks:+ msg_volcengine["reasoning_content"] = "\n".join(+ reasoning_content_blocks,+ )++ if tool_calls:+ msg_volcengine["tool_calls"] = tool_calls++ if (+ msg_volcengine["content"]+ or msg_volcengine.get("tool_calls")+ or reasoning_content_blocks+ ):+ messages.append(msg_volcengine)++ return messages+++class VolcengineMultiAgentFormatter(_VolcengineFormatterBase):+ """+ Volcengine formatter for multi-agent conversations, where more than+ a user and an agent are involved.+ """++ conversation_history_prompt: str = Field(+ default=(+ "# Conversation History\n"+ "The content between <history></history> tags contains "+ "your conversation history\n"+ ),+ description="The prompt to use for the conversation history section.",+ )++ input_types: list[str] = Field(+ default_factory=lambda: ["text/plain", "image/*", "video/*"],+ description=(+ "The supported input types. Defaults to "+ '``["text/plain", "image/*", "video/*"]``.'+ ),+ )++ async def format(self, msgs: list[Msg]) -> list[dict[str, Any]]:+ """Format input messages into the structure required by the Volcengine+ API for multi-agent conversations."""+ self.assert_list_of_msgs(msgs)++ formatted_msgs = []+ start_index = 0+ if len(msgs) > 0 and msgs[0].role == "system":+ formatted_msgs.append(+ await self._format_system_message(msgs[0]),+ )+ start_index = 1++ is_first_agent_message = True+ async for typ, group in self._group_messages(msgs[start_index:]):+ match typ:+ case "tool_sequence":+ formatted_msgs.extend(+ await self._format_tool_sequence(group),+ )+ case "agent_message":+ formatted_msgs.extend(+ await self._format_agent_message(+ group,+ is_first_agent_message,+ ),+ )+ is_first_agent_message = False++ return formatted_msgs++ async def _format_tool_sequence(+ self,+ msgs: list[Msg],+ ) -> list[dict[str, Any]]:+ """Given a sequence of tool call/result messages, format them into+ the required format for the Volcengine API."""+ return await VolcengineChatFormatter(+ input_types=self.input_types,+ ).format(msgs)++ async def _format_agent_message(+ self,+ msgs: list[Msg],+ is_first: bool = True,+ ) -> list[dict[str, Any]]:+ """Given a sequence of messages without tool calls/results, format+ them into the required format for the Volcengine API."""++ if is_first:+ conversation_history_prompt = self.conversation_history_prompt+ else:+ conversation_history_prompt = ""++ accumulated_text: list[str] = []+ media_blocks: list[dict[str, Any]] = []++ for msg in msgs:+ for block in msg.get_content_blocks():+ if isinstance(block, TextBlock):+ accumulated_text.append(f"{msg.name}: {block.text}")+ elif isinstance(block, DataBlock):+ formatted = self._format_volcengine_data_block(block)+ if formatted is not None:+ media_blocks.append(formatted)++ if not accumulated_text and not media_blocks:+ return []++ content_blocks: list[dict[str, Any]] = []+ if accumulated_text:+ content_blocks.append(+ {+ "type": "text",+ "text": (+ conversation_history_prompt+ + "<history>\n"+ + "\n".join(accumulated_text)+ + "\n</history>"+ ),+ },+ )+ content_blocks.extend(media_blocks)++ return [{"role": "user", "content": content_blocks}]++ @staticmethod+ async def _format_system_message(+ msg: Msg,+ ) -> dict[str, Any]:+ """Format system message for Volcengine API."""+ return {+ "role": "system",+ "content": msg.get_text_content(),+ }diff --git a/src/agentscope/middleware/_tracing/_attributes.py b/src/agentscope/middleware/_tracing/_attributes.pyindex ed3d336be..26992cfcb 100644--- a/src/agentscope/middleware/_tracing/_attributes.py+++ b/src/agentscope/middleware/_tracing/_attributes.py@@ -189,6 +189,9 @@ class ProviderNameValues:MOONSHOT = "moonshot""""The moonshot provider name."""+ VOLCENGINE = "volcengine"+ """The Volcengine provider name."""+AZURE_AI_OPENAI = (GenAIAttributes.GenAiProviderNameValues.AZURE_AI_OPENAI.value)diff --git a/src/agentscope/middleware/_tracing/_extractor.py b/src/agentscope/middleware/_tracing/_extractor.pyindex a8810fbbf..a46b5b8e2 100644--- a/src/agentscope/middleware/_tracing/_extractor.py+++ b/src/agentscope/middleware/_tracing/_extractor.py@@ -31,6 +31,7 @@ _CLASS_NAME_MAP = {"deepseek": ProviderNameValues.DEEPSEEK,"xai": ProviderNameValues.XAI,"moonshot": ProviderNameValues.MOONSHOT,+ "volcengine": ProviderNameValues.VOLCENGINE,}# Map base URL fragments to provider names for OpenAI-compatible APIs@@ -39,6 +40,7 @@ _BASE_URL_PROVIDER_MAP = [("dashscope", ProviderNameValues.DASHSCOPE),("deepseek", ProviderNameValues.DEEPSEEK),("moonshot", ProviderNameValues.MOONSHOT),+ ("volces.com", ProviderNameValues.VOLCENGINE),("generativelanguage.googleapis.com", ProviderNameValues.GCP_GEMINI),("openai.azure.com", ProviderNameValues.AZURE_AI_OPENAI),("amazonaws.com", ProviderNameValues.AWS_BEDROCK),diff --git a/src/agentscope/model/__init__.py b/src/agentscope/model/__init__.pyindex e7bf1b83f..c474a7367 100644--- a/src/agentscope/model/__init__.py+++ b/src/agentscope/model/__init__.py@@ -14,6 +14,7 @@ from ._openai_chat import OpenAIChatModelfrom ._xai import XAIChatModelfrom ._moonshot import MoonshotChatModelfrom ._openai_response import OpenAIResponseModel+from ._volcengine import VolcengineChatModel__all__ = ["ChatUsage",@@ -31,4 +32,5 @@ __all__ = ["XAIChatModel","MoonshotChatModel","OpenAIResponseModel",+ "VolcengineChatModel",]diff --git a/src/agentscope/model/_volcengine/__init__.py b/src/agentscope/model/_volcengine/__init__.pynew file mode 100644index 000000000..6caab2be7--- /dev/null+++ b/src/agentscope/model/_volcengine/__init__.py@@ -0,0 +1,9 @@+# -*- coding: utf-8 -*-+"""The Volcengine Ark LLM API modules."""++from ._model import VolcengineCredential, VolcengineChatModel++__all__ = [+ "VolcengineCredential",+ "VolcengineChatModel",+]diff --git a/src/agentscope/model/_volcengine/_model.py b/src/agentscope/model/_volcengine/_model.pynew file mode 100644index 000000000..b2eb4a6d9--- /dev/null+++ b/src/agentscope/model/_volcengine/_model.py@@ -0,0 +1,449 @@+# -*- coding: utf-8 -*-+"""The Volcengine Ark chat model implementation."""++from collections import OrderedDict+from datetime import datetime+from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List, Type++from pydantic import BaseModel, Field++from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES+from .._model_response import ChatResponse+from .._model_usage import ChatUsage+from ..._utils._common import _generate_id+from ...credential import VolcengineCredential+from ...formatter import FormatterBase, VolcengineChatFormatter+from ...message import Msg, ThinkingBlock, ToolCallBlock, TextBlock+from ...tool import ToolChoice++if TYPE_CHECKING:+ from openai.types.chat import ChatCompletion+ from openai import AsyncStream+else:+ ChatCompletion = Any+ AsyncStream = Any+++class VolcengineChatModel(ChatModelBase):+ """The Volcengine Ark chat model."""++ class Parameters(BaseModel):+ """The parameters for the Volcengine Ark chat model."""++ max_tokens: int | None = Field(+ default=None,+ title="Max Tokens",+ description="The maximum number of tokens for the LLM output.",+ gt=0,+ )++ thinking_enable: bool | None = Field(+ default=None,+ title="Thinking",+ description=(+ "Whether to enable or disable thinking mode. When unset, "+ "Ark uses its default auto mode."+ ),+ )++ reasoning_effort: (+ Literal["minimal", "low", "medium", "high"] | None+ ) = Field(+ default=None,+ title="Reasoning Effort",+ description=(+ "Controls the depth of reasoning in thinking mode. "+ "Supported values are minimal, low, medium, and high. "+ "The minimal level disables reasoning."+ ),+ )++ temperature: float | None = Field(+ default=None,+ title="Temperature",+ description="The temperature for the LLM output.",+ ge=0,+ le=2,+ )++ top_p: float | None = Field(+ default=None,+ title="Top P",+ description="The top P value for the LLM output.",+ gt=0,+ le=1,+ )++ type: Literal["volcengine_chat"] = "volcengine_chat"+ """The type of the chat model."""++ def __init__(+ self,+ credential: VolcengineCredential,+ model: str,+ parameters: "VolcengineChatModel.Parameters | None" = None,+ stream: bool = True,+ max_retries: int = 3,+ retry_delay: float = 1.0,+ context_size: int = 256000,+ formatter: FormatterBase | None = None,+ client_kwargs: dict[str, Any] | None = None,+ ) -> None:+ """Initialize the Volcengine Ark chat model.++ Args:+ credential (`VolcengineCredential`):+ The Volcengine Ark credential used to authenticate API calls.+ model (`str`):+ The versioned Ark model ID, e.g.+ ``doubao-seed-2-1-pro-260628``.+ parameters (`VolcengineChatModel.Parameters | None`, defaults to \+ `None`):+ The Volcengine Ark API parameters. When ``None``, the default+ parameters will be used.+ stream (`bool`, defaults to `True`):+ Whether to enable streaming output.+ max_retries (`int`, defaults to `3`):+ The maximum number of retries for the Volcengine Ark API.+ retry_delay (`float`, defaults to `1.0`):+ Seconds to sleep between retry attempts.+ context_size (`int`, defaults to `256000`):+ The model context size used for context compression.+ formatter (`FormatterBase | None`, defaults to `None`):+ The formatter that converts ``Msg`` objects to the format+ required by the Volcengine Ark API. When ``None``, a+ ``VolcengineChatFormatter`` instance will be used.+ client_kwargs (`dict[str, Any] | None`, defaults to `None`):+ Extra keyword arguments forwarded to ``openai.AsyncClient``+ (e.g. ``timeout``, ``default_headers``, ``http_client``).+ """+ super().__init__(+ credential=credential,+ model=model,+ parameters=parameters or self.Parameters(),+ stream=stream,+ max_retries=max_retries,+ retry_delay=retry_delay,+ context_size=context_size,+ )+ self.formatter = formatter or VolcengineChatFormatter()+ self.client_kwargs = client_kwargs or {}++ import openai++ self.client: openai.AsyncClient = openai.AsyncClient(+ api_key=self.credential.api_key.get_secret_value(),+ base_url=self.credential.base_url,+ **self.client_kwargs,+ )++ @classmethod+ def _get_retryable_exceptions(cls) -> tuple[Type[Exception], ...]:+ import openai++ return (+ openai.APIConnectionError,+ openai.APITimeoutError,+ openai.RateLimitError,+ openai.InternalServerError,+ )++ @classmethod+ def _get_structured_output_fallback_exceptions(+ cls,+ ) -> tuple[Type[Exception], ...]:+ import openai++ return (openai.BadRequestError,)++ async def _call_api(+ self,+ model_name: str,+ messages: list[Msg],+ tools: list[dict] | None = None,+ tool_choice: ToolChoice | None = None,+ **generate_kwargs: Any,+ ) -> ChatResponse | AsyncGenerator[ChatResponse, None]:+ """Call the Volcengine Ark chat completions API.++ Args:+ model_name (`str`):+ The model name to use for this call.+ messages (`list`):+ A list of message dicts with ``role`` and ``content`` keys.+ tools (`list[dict]`, default `None`):+ The tools JSON schemas.+ tool_choice (`ToolChoice | None`, optional):+ Controls which (if any) tool is called by the model.+ **generate_kwargs (`Any`):+ Extra keyword arguments forwarded to the API.++ Returns:+ `ChatResponse | AsyncGenerator[ChatResponse, None]`:+ A ``ChatResponse`` when streaming is disabled, or an async+ generator of ``ChatResponse`` objects when streaming is+ enabled.+ """+ formatted_messages = await self.formatter.format(messages)++ kwargs: dict[str, Any] = {+ "model": model_name,+ "messages": formatted_messages,+ "stream": self.stream,+ }++ if self.parameters.max_tokens is not None:+ kwargs["max_tokens"] = self.parameters.max_tokens++ if self.parameters.temperature is not None:+ kwargs["temperature"] = self.parameters.temperature++ if self.parameters.top_p is not None:+ kwargs["top_p"] = self.parameters.top_p++ if self.parameters.reasoning_effort is not None:+ kwargs["reasoning_effort"] = self.parameters.reasoning_effort++ kwargs.update(generate_kwargs)++ if self.parameters.thinking_enable is not None:+ thinking_type = (+ "enabled" if self.parameters.thinking_enable else "disabled"+ )+ kwargs.setdefault("extra_body", {})+ kwargs["extra_body"].setdefault("thinking", {})+ kwargs["extra_body"]["thinking"].setdefault(+ "type",+ thinking_type,+ )++ fmt_tools, fmt_tool_choice = self._format_tools(tools, tool_choice)++ if fmt_tools:+ kwargs["tools"] = fmt_tools++ if fmt_tool_choice is not None:+ kwargs["tool_choice"] = fmt_tool_choice++ if self.stream:+ kwargs["stream_options"] = {"include_usage": True}++ start_datetime = datetime.now()+ response = await self.client.chat.completions.create(**kwargs)++ if self.stream:+ return self._parse_stream_response(start_datetime, response)++ return self._parse_completion_response(start_datetime, response)++ async def _parse_stream_response(+ self,+ start_datetime: datetime,+ response: AsyncStream,+ ) -> AsyncGenerator[ChatResponse, None]:+ """Parse the Volcengine streaming response.++ Args:+ start_datetime (`datetime`):+ The start datetime of the response generation.+ response (`AsyncStream`):+ The OpenAI-compatible async stream object.++ Yields:+ `ChatResponse`:+ Incremental ``ChatResponse`` objects with ``is_last=False``+ followed by a final one with ``is_last=True``.+ """+ usage = None+ response_id: str = _generate_id()+ text_id: str = _generate_id()+ thinking_id: str = _generate_id()+ # The mapping from index to tool call id+ tool_call_mapping: dict = OrderedDict()++ async with response as stream:+ async for chunk in stream:+ delta_res = ChatResponse(+ content=[],+ is_last=False,+ id=response_id,+ )++ # Update the response ID if exists+ response_id = getattr(chunk, "id", None) or response_id+ delta_res.id = response_id++ if chunk.usage:+ u = chunk.usage+ details = getattr(u, "prompt_tokens_details", None)+ usage = ChatUsage(+ input_tokens=u.prompt_tokens,+ output_tokens=u.completion_tokens,+ time=(datetime.now() - start_datetime).total_seconds(),+ cache_input_tokens=(+ getattr(details, "cached_tokens", 0)+ if details+ else 0+ ),+ )++ if not chunk.choices:+ # Volcengine emits a trailing usage-only chunk with no+ # choices; forward it as an empty-content delta so the+ # base class ``__call__`` can absorb ``usage`` into+ # ``acc_res``. The empty delta itself is filtered out+ # of the surfaced stream by ``_stream``.+ if usage is not None:+ delta_res.usage = usage+ yield delta_res+ continue++ choice = chunk.choices[0]+ delta = choice.delta++ # Thinking block+ if getattr(delta, "reasoning_content", None):+ delta_res.append_thinking(+ block_id=thinking_id,+ thinking=delta.reasoning_content,+ )++ # Text+ if getattr(delta, "content", None):+ delta_res.append_text(+ block_id=text_id,+ text=delta.content,+ )++ # Tool call+ for tool_call in getattr(delta, "tool_calls", None) or []:+ index = tool_call.index+ fn = getattr(tool_call, "function", None)+ delta_name = getattr(fn, "name", None) if fn else None+ delta_args = getattr(fn, "arguments", None) if fn else None++ # Record the id and name in case following deltas+ # don't provide them+ if index not in tool_call_mapping:+ tool_call_mapping[index] = (+ tool_call.id,+ delta_name or "unknown",+ )++ stored_id, stored_name = tool_call_mapping[index]++ delta_res.append_tool_call(+ block_id=tool_call.id or stored_id,+ name=delta_name or stored_name,+ input=delta_args or "",+ )++ if delta_res.content or usage:+ delta_res.usage = usage+ yield delta_res++ def _parse_completion_response(+ self,+ start_datetime: datetime,+ response: ChatCompletion,+ ) -> ChatResponse:+ """Parse the Volcengine non-streaming response.++ Args:+ start_datetime (`datetime`):+ The start datetime of the response generation.+ response (`ChatCompletion`):+ The OpenAI-compatible chat completion object.++ Returns:+ `ChatResponse`:+ A single ``ChatResponse`` with ``is_last=True``.+ """+ content_blocks: List[TextBlock | ToolCallBlock | ThinkingBlock] = []++ if response.choices:+ choice = response.choices[0]+ reasoning = getattr(choice.message, "reasoning_content", None)+ if isinstance(reasoning, str) and reasoning:+ content_blocks.append(ThinkingBlock(thinking=reasoning))++ if choice.message.content:+ content_blocks.append(TextBlock(text=choice.message.content))++ for tool_call in choice.message.tool_calls or []:+ content_blocks.append(+ ToolCallBlock(+ id=tool_call.id,+ name=tool_call.function.name,+ input=tool_call.function.arguments,+ ),+ )++ usage = None+ if response.usage:+ u = response.usage+ details = getattr(u, "prompt_tokens_details", None)+ usage = ChatUsage(+ input_tokens=u.prompt_tokens,+ output_tokens=u.completion_tokens,+ time=(datetime.now() - start_datetime).total_seconds(),+ cache_input_tokens=(+ getattr(details, "cached_tokens", 0) if details else 0+ ),+ )++ resp_kwargs: dict[str, Any] = {+ "content": content_blocks,+ "is_last": True,+ "usage": usage,+ }+ response_id = getattr(response, "id", None)+ if response_id:+ resp_kwargs["id"] = response_id++ return ChatResponse(**resp_kwargs)++ def _format_tools(+ self,+ tools: list[dict] | None,+ tool_choice: ToolChoice | None,+ ) -> tuple[list[dict] | None, str | dict | None]:+ """Validate, filter, and format tools and tool choice for the+ Volcengine Ark API.++ When ``tool_choice.tools`` is specified the schemas list is filtered+ to only those tools. When ``tool_choice.mode`` is a specific tool name+ (str) the model is forced to call exactly that tool without needing to+ filter the list, preserving prompt-cache efficiency.++ Args:+ tools (`list[dict] | None`, optional):+ The raw tool schemas.+ tool_choice (`ToolChoice | None`, optional):+ The tool choice configuration.++ Returns:+ `tuple[list[dict] | None, str | dict | None]`:+ A tuple of (formatted_tools, formatted_tool_choice).+ """+ if tool_choice and tools:+ self._validate_tool_choice(tool_choice, tools)+ if tool_choice.tools:+ allowed = set(tool_choice.tools)+ tools = [t for t in tools if t["function"]["name"] in allowed]++ if not tool_choice:+ return tools, None++ mode = tool_choice.mode++ if mode not in _TOOL_CHOICE_LITERAL_MODES:+ return tools, {"type": "function", "function": {"name": mode}}++ return tools, mode++ def _get_disable_thinking_kwargs(self) -> dict:+ """Volcengine Ark uses ``thinking.type=disabled`` in extra_body."""+ return {+ "extra_body": {"thinking": {"type": "disabled"}},+ }diff --git a/src/agentscope/model/_volcengine/_models/doubao-seed-2-1-pro-260628.yaml b/src/agentscope/model/_volcengine/_models/doubao-seed-2-1-pro-260628.yamlnew file mode 100644index 000000000..2e5032b85--- /dev/null+++ b/src/agentscope/model/_volcengine/_models/doubao-seed-2-1-pro-260628.yaml@@ -0,0 +1,19 @@+name: doubao-seed-2-1-pro-260628+label: Doubao Seed 2.1 Pro+status: active++input_types:+ - text/plain+ - application/x-thinking+ - image/*+ - video/*++output_types:+ - text/plain+ - application/x-thinking++# Source: https://www.volcengine.com/docs/82379/1799865+# The official model list specifies a 256k context window and a 256k+# maximum answer length for doubao-seed-2-1-pro-260628.+context_size: 256000+output_size: 256000diff --git a/tests/formatter_volcengine_test.py b/tests/formatter_volcengine_test.pynew file mode 100644index 000000000..6b1492b34--- /dev/null+++ b/tests/formatter_volcengine_test.py@@ -0,0 +1,696 @@+# -*- coding: utf-8 -*-+"""Comprehensive formatter unit tests for VolcengineChatFormatter and+VolcengineMultiAgentFormatter, with exact ground-truth comparisons.+"""++from unittest import IsolatedAsyncioTestCase++from agentscope.formatter import (+ VolcengineChatFormatter,+ VolcengineMultiAgentFormatter,+)+from agentscope.message import (+ UserMsg,+ AssistantMsg,+ SystemMsg,+ TextBlock,+ DataBlock,+ Base64Source,+ URLSource,+ ToolCallBlock,+ ToolResultBlock,+ ToolResultState,+ ThinkingBlock,+ HintBlock,+)+++class TestVolcengineFormatter(IsolatedAsyncioTestCase):+ """Comprehensive tests for Volcengine Chat and MultiAgent formatters."""++ async def asyncSetUp(self) -> None:+ """Set up shared fixtures and ground-truth dicts."""+ _hist_prompt = (+ VolcengineMultiAgentFormatter().conversation_history_prompt+ )++ self.msgs_system = [+ SystemMsg(+ name="system",+ content="You're a helpful assistant.",+ ),+ ]+ self.msgs_conversation = [+ UserMsg(+ name="user",+ content="What is the capital of France?",+ ),+ AssistantMsg(+ name="assistant",+ content="The capital of France is Paris.",+ ),+ UserMsg(+ name="user",+ content="What is the capital of Germany?",+ ),+ AssistantMsg(+ name="assistant",+ content="The capital of Germany is Berlin.",+ ),+ UserMsg(+ name="user",+ content="What is the capital of Japan?",+ ),+ ]+ self.msgs_tools = [+ AssistantMsg(+ name="assistant",+ content=[+ ToolCallBlock(+ id="call_1",+ name="get_capital",+ input='{"country": "Japan"}',+ ),+ ToolResultBlock(+ id="call_1",+ name="get_capital",+ output=[+ TextBlock(text="The capital of Japan is Tokyo."),+ ],+ state=ToolResultState.SUCCESS,+ ),+ TextBlock(text="The capital of Japan is Tokyo."),+ ],+ ),+ ]++ # --- Chat formatter ground truth ---+ # Text content is a list of blocks, as in the OpenAI formatter.+ # Ark only needs `reasoning_content` when preserving a ThinkingBlock.+ self.gt_chat = [+ {+ "role": "system",+ "content": [+ {"type": "text", "text": "You're a helpful assistant."},+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What is the capital of France?"},+ ],+ },+ {+ "role": "assistant",+ "content": [+ {+ "type": "text",+ "text": "The capital of France is Paris.",+ },+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "What is the capital of Germany?",+ },+ ],+ },+ {+ "role": "assistant",+ "content": [+ {+ "type": "text",+ "text": "The capital of Germany is Berlin.",+ },+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What is the capital of Japan?"},+ ],+ },+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {+ "name": "get_capital",+ "arguments": '{"country": "Japan"}',+ },+ },+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_1",+ "content": "The capital of Japan is Tokyo.",+ "name": "get_capital",+ },+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "The capital of Japan is Tokyo."},+ ],+ },+ ]++ # --- MultiAgent formatter ground truth ---+ # System content is a plain string.+ # History is a single text block with <history> tags.+ # The trailing assistant message (is_first=False) is wrapped in a+ # minimal <history> block without the full prompt prefix.+ self._gt_trailing_asst = {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "The capital of Japan is Tokyo."},+ ],+ }+ self._gt_tool_call = {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {+ "name": "get_capital",+ "arguments": '{"country": "Japan"}',+ },+ },+ ],+ }+ self._gt_tool_result = {+ "role": "tool",+ "tool_call_id": "call_1",+ "content": "The capital of Japan is Tokyo.",+ "name": "get_capital",+ }++ self.gt_multiagent = [+ {"role": "system", "content": "You're a helpful assistant."},+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": (+ _hist_prompt + "<history>\n"+ "user: What is the capital of France?\n"+ "assistant: The capital of France is Paris.\n"+ "user: What is the capital of Germany?\n"+ "assistant: The capital of Germany is Berlin.\n"+ "user: What is the capital of Japan?\n"+ "</history>"+ ),+ },+ ],+ },+ self._gt_tool_call,+ self._gt_tool_result,+ self._gt_trailing_asst,+ ]++ # ------------------------------------------------------------------+ # VolcengineChatFormatter tests+ # ------------------------------------------------------------------++ async def test_chat_formatter(self) -> None:+ """Chat formatter produces exact output for various subsets."""+ fmt = VolcengineChatFormatter()++ # Full history+ res = await fmt.format(+ [*self.msgs_system, *self.msgs_conversation, *self.msgs_tools],+ )+ self.assertListEqual(self.gt_chat, res)++ # Without system+ res = await fmt.format([*self.msgs_conversation, *self.msgs_tools])+ self.assertListEqual(self.gt_chat[1:], res)++ # Without conversation+ n_tools_gt = len(self.gt_chat) - 1 - len(self.msgs_conversation)+ res = await fmt.format([*self.msgs_system, *self.msgs_tools])+ self.assertListEqual(+ [self.gt_chat[0]] + self.gt_chat[-n_tools_gt:],+ res,+ )++ # Without tools+ res = await fmt.format([*self.msgs_system, *self.msgs_conversation])+ self.assertListEqual(self.gt_chat[:-n_tools_gt], res)++ # Empty+ self.assertListEqual([], await fmt.format([]))++ async def test_chat_formatter_omits_empty_reasoning_content(+ self,+ ) -> None:+ """A non-thinking assistant message omits reasoning_content."""+ fmt = VolcengineChatFormatter()+ msgs = [AssistantMsg(name="assistant", content="Answer")]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "assistant",+ "content": [{"type": "text", "text": "Answer"}],+ },+ ],+ res,+ )++ async def test_chat_formatter_thinking_block(self) -> None:+ """ThinkingBlock is placed into reasoning_content."""+ fmt = VolcengineChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ ThinkingBlock(thinking="Let me think..."),+ TextBlock(text="Answer"),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "assistant",+ "content": [{"type": "text", "text": "Answer"}],+ "reasoning_content": "Let me think...",+ },+ ],+ res,+ )++ # ------------------------------------------------------------------+ # VolcengineMultiAgentFormatter tests+ # ------------------------------------------------------------------++ async def test_multiagent_formatter(self) -> None:+ """MultiAgent formatter produces exact output for various subsets."""+ fmt = VolcengineMultiAgentFormatter()++ # Full+ res = await fmt.format(+ [*self.msgs_system, *self.msgs_conversation, *self.msgs_tools],+ )+ self.assertListEqual(self.gt_multiagent, res)++ # Without system+ res = await fmt.format([*self.msgs_conversation, *self.msgs_tools])+ self.assertListEqual(self.gt_multiagent[1:], res)++ # Without tools+ res = await fmt.format([*self.msgs_system, *self.msgs_conversation])+ self.assertListEqual(self.gt_multiagent[:2], res)++ # System only+ res = await fmt.format(self.msgs_system)+ self.assertListEqual([self.gt_multiagent[0]], res)++ # Conversation only+ res = await fmt.format(self.msgs_conversation)+ self.assertListEqual([self.gt_multiagent[1]], res)++ # Tools only+ res = await fmt.format(self.msgs_tools)+ self.assertListEqual(+ [+ self._gt_tool_call,+ self._gt_tool_result,+ self._gt_trailing_asst,+ ],+ res,+ )++ # System + tools+ res = await fmt.format([*self.msgs_system, *self.msgs_tools])+ self.assertListEqual(+ [+ self.gt_multiagent[0],+ self._gt_tool_call,+ self._gt_tool_result,+ self._gt_trailing_asst,+ ],+ res,+ )++ # Empty+ self.assertListEqual([], await fmt.format([]))++ async def test_chat_formatter_complex_multi_step(self) -> None:+ """Complex multi-step sequence with interleaved thinking, text,+ tool calls, and tool results."""+ fmt = VolcengineChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ ThinkingBlock(thinking="thinking_1"),+ TextBlock(text="text_1"),+ ToolCallBlock(+ id="call_1",+ name="func_1",+ input='{"arg": "value1"}',+ ),+ ToolCallBlock(+ id="call_2",+ name="func_2",+ input='{"arg": "value2"}',+ ),+ ToolResultBlock(+ id="call_1",+ name="func_1",+ output=[TextBlock(text="result_1")],+ state=ToolResultState.SUCCESS,+ ),+ ToolResultBlock(+ id="call_2",+ name="func_2",+ output=[TextBlock(text="result_2")],+ state=ToolResultState.SUCCESS,+ ),+ ThinkingBlock(thinking="thinking_2"),+ TextBlock(text="text_2"),+ ToolCallBlock(+ id="call_3",+ name="func_3",+ input='{"arg": "value3"}',+ ),+ ToolResultBlock(+ id="call_3",+ name="func_3",+ output=[TextBlock(text="result_3")],+ state=ToolResultState.SUCCESS,+ ),+ ToolCallBlock(+ id="call_4",+ name="func_4",+ input='{"arg": "value4"}',+ ),+ ToolResultBlock(+ id="call_4",+ name="func_4",+ output=[TextBlock(text="result_4")],+ state=ToolResultState.SUCCESS,+ ),+ ThinkingBlock(thinking="thinking_3"),+ TextBlock(text="text_3"),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "assistant",+ "content": [{"type": "text", "text": "text_1"}],+ "reasoning_content": "thinking_1",+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {+ "name": "func_1",+ "arguments": '{"arg": "value1"}',+ },+ },+ {+ "id": "call_2",+ "type": "function",+ "function": {+ "name": "func_2",+ "arguments": '{"arg": "value2"}',+ },+ },+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_1",+ "content": "result_1",+ "name": "func_1",+ },+ {+ "role": "tool",+ "tool_call_id": "call_2",+ "content": "result_2",+ "name": "func_2",+ },+ {+ "role": "assistant",+ "content": [{"type": "text", "text": "text_2"}],+ "reasoning_content": "thinking_2",+ "tool_calls": [+ {+ "id": "call_3",+ "type": "function",+ "function": {+ "name": "func_3",+ "arguments": '{"arg": "value3"}',+ },+ },+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_3",+ "content": "result_3",+ "name": "func_3",+ },+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_4",+ "type": "function",+ "function": {+ "name": "func_4",+ "arguments": '{"arg": "value4"}',+ },+ },+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_4",+ "content": "result_4",+ "name": "func_4",+ },+ {+ "role": "assistant",+ "content": [{"type": "text", "text": "text_3"}],+ "reasoning_content": "thinking_3",+ },+ ],+ res,+ )++ async def test_chat_formatter_hint_block(self) -> None:+ """HintBlock flushes preceding content and becomes a user message."""+ fmt = VolcengineChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ TextBlock(text="Let me think about that."),+ HintBlock(hint="Remember to be concise."),+ TextBlock(text="Here is my answer."),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "Let me think about that."},+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Remember to be concise."},+ ],+ },+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "Here is my answer."},+ ],+ },+ ],+ res,+ )++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """HintBlock preserves supported image data."""+ fmt = VolcengineChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data="ZmFrZSBpbWFnZSBkYXRh",+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "Inspect this screenshot:",+ },+ {+ "type": "image_url",+ "image_url": {+ "url": (+ "data:image/png;base64,"+ "ZmFrZSBpbWFnZSBkYXRh"+ ),+ },+ },+ ],+ },+ ],+ res,+ )++ async def test_chat_formatter_multimodal_url_and_base64(self) -> None:+ """Ark image/video input accepts URLs and base64 data URIs."""+ fmt = VolcengineChatFormatter()+ msgs = [+ UserMsg(+ name="user",+ content=[+ TextBlock(text="Compare these images."),+ DataBlock(+ source=URLSource(+ url="https://example.com/first.png",+ media_type="image/png",+ ),+ ),+ DataBlock(+ source=Base64Source(+ data="ZmFrZQ==",+ media_type="image/jpeg",+ ),+ ),+ DataBlock(+ source=URLSource(+ url="https://example.com/video.mp4",+ media_type="video/mp4",+ ),+ ),+ DataBlock(+ source=Base64Source(+ data="dmlkZW8=",+ media_type="video/quicktime",+ ),+ ),+ ],+ ),+ ]++ self.assertListEqual(+ [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Compare these images."},+ {+ "type": "image_url",+ "image_url": {+ "url": "https://example.com/first.png",+ },+ },+ {+ "type": "image_url",+ "image_url": {+ "url": "data:image/jpeg;base64,ZmFrZQ==",+ },+ },+ {+ "type": "video_url",+ "video_url": {+ "url": "https://example.com/video.mp4",+ },+ },+ {+ "type": "video_url",+ "video_url": {+ "url": "data:video/quicktime;base64,dmlkZW8=",+ },+ },+ ],+ },+ ],+ await fmt.format(msgs),+ )++ async def test_multiagent_formatter_preserves_images(self) -> None:+ """Multi-agent history should retain supported image blocks."""+ fmt = VolcengineMultiAgentFormatter()+ msgs = [+ UserMsg(+ name="alice",+ content=[+ TextBlock(text="Describe this image."),+ DataBlock(+ source=URLSource(+ url="https://example.com/image.png",+ media_type="image/png",+ ),+ ),+ ],+ ),+ ]++ self.assertListEqual(+ [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": (+ fmt.conversation_history_prompt+ + "<history>\nalice: Describe this image.\n"+ "</history>"+ ),+ },+ {+ "type": "image_url",+ "image_url": {+ "url": "https://example.com/image.png",+ },+ },+ ],+ },+ ],+ await fmt.format(msgs),+ )diff --git a/tests/model_volcengine_test.py b/tests/model_volcengine_test.pynew file mode 100644index 000000000..a62879939--- /dev/null+++ b/tests/model_volcengine_test.py@@ -0,0 +1,852 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Unit tests for VolcengineChatModel with mocked API responses.++Tests cover both non-streaming and streaming modes, verifying that:+- Non-stream mode returns a single ChatResponse with is_last=True.+- Stream mode yields n delta ChatResponses (is_last=False) followed by+ 1 final ChatResponse (is_last=True) with the full accumulated content.+"""++from typing import Any+import unittest+from unittest import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, MagicMock++from utils import AnyString++from agentscope.message import TextBlock, ToolCallBlock, ThinkingBlock+from agentscope.model import VolcengineChatModel+from agentscope.credential import CredentialFactory, VolcengineCredential+from agentscope.tool import ToolChoice++A = AnyString()+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_model(stream: bool = False) -> Any:+ return VolcengineChatModel(+ credential=VolcengineCredential(api_key="test"),+ model="doubao-seed-2-1-pro-260628",+ stream=stream,+ context_size=65_536,+ )+++def _mock_completion(+ text: Any = None,+ tool_calls: Any = None,+ reasoning: Any = None,+ response_id: str = "volcengine-1",+) -> MagicMock:+ """Build a mock non-streaming ChatCompletion response."""+ msg = MagicMock()+ msg.content = text+ msg.reasoning_content = reasoning+ msg.tool_calls = None++ if tool_calls:+ tc_mocks = []+ for tc in tool_calls:+ m = MagicMock()+ m.id = tc["id"]+ m.function.name = tc["name"]+ m.function.arguments = tc["arguments"]+ tc_mocks.append(m)+ msg.tool_calls = tc_mocks++ choice = MagicMock()+ choice.message = msg++ resp = MagicMock()+ resp.id = response_id+ resp.choices = [choice]+ resp.usage.prompt_tokens = 10+ resp.usage.completion_tokens = 5+ resp.usage.prompt_tokens_details.cached_tokens = 0+ return resp+++def _make_stream_chunk(+ delta_text: str | None = None,+ delta_reasoning: str | None = None,+ tool_calls: list | None = None,+ response_id: str = "volcengine-1",+ usage: dict | None = None,+ has_choices: bool = True,+) -> MagicMock:+ """Build a single mock streaming chunk."""+ chunk = MagicMock()+ chunk.id = response_id++ if usage:+ chunk.usage = MagicMock()+ chunk.usage.prompt_tokens = usage.get("prompt_tokens", 0)+ chunk.usage.completion_tokens = usage.get("completion_tokens", 0)+ chunk.usage.prompt_tokens_details.cached_tokens = usage.get(+ "cached_tokens",+ 0,+ )+ else:+ chunk.usage = None++ if has_choices:+ delta = MagicMock()+ delta.content = delta_text+ delta.reasoning_content = delta_reasoning+ delta.tool_calls = tool_calls+ choice = MagicMock()+ choice.delta = delta+ chunk.choices = [choice]+ else:+ chunk.choices = []++ return chunk+++def _make_tool_call_delta(+ index: int,+ tc_id: str | None = None,+ name: str | None = None,+ arguments: str | None = None,+) -> MagicMock:+ """Build a tool_call delta item for streaming."""+ tc = MagicMock()+ tc.index = index+ tc.id = tc_id+ tc.function.name = name+ tc.function.arguments = arguments+ return tc+++class _MockAsyncStream:+ """Mock async stream that acts as an async context manager + iterator."""++ def __init__(self, chunks: list) -> None:+ self._chunks = chunks+ self._index = 0++ async def __aenter__(self) -> "_MockAsyncStream":+ return self++ async def __aexit__(self, *args: Any) -> None:+ pass++ def __aiter__(self) -> "_MockAsyncStream":+ return self++ async def __anext__(self) -> Any:+ if self._index >= len(self._chunks):+ raise StopAsyncIteration+ chunk = self._chunks[self._index]+ self._index += 1+ return chunk+++# ---------------------------------------------------------------------------+# Non-streaming tests+# ---------------------------------------------------------------------------+++class TestVolcengineNonStream(IsolatedAsyncioTestCase):+ """Tests for VolcengineChatModel in non-streaming mode."""++ def setUp(self) -> None:+ self.model = _make_model(stream=False)+ self.mock_client = MagicMock()+ self.model.client = self.mock_client++ async def test_text_response(self) -> None:+ """Non-stream text response returns a single ChatResponse."""+ mock_create = AsyncMock(+ return_value=_mock_completion(text="Hello world!"),+ )+ self.mock_client.chat.completions.create = mock_create++ result = await self.model([])++ self.assertEqual(+ (result.is_last, result.content),+ (+ True,+ [+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text="Hello world!",+ ),+ ],+ ),+ )+ self.assertEqual(result.id, "volcengine-1")++ async def test_tool_call_response(+ self,+ ) -> None:+ """Non-stream tool call response creates ToolCallBlocks."""+ mock_create = AsyncMock(+ return_value=_mock_completion(+ tool_calls=[+ {+ "id": "call-1",+ "name": "get_weather",+ "arguments": '{"city":"Beijing"}',+ },+ {+ "id": "call-2",+ "name": "get_time",+ "arguments": '{"tz":"UTC"}',+ },+ ],+ ),+ )+ self.mock_client.chat.completions.create = mock_create++ result = await self.model([])++ self.assertEqual(+ (result.is_last, result.content),+ (+ True,+ [+ ToolCallBlock.model_construct(+ created_at=A,+ id="call-1",+ name="get_weather",+ input='{"city":"Beijing"}',+ ),+ ToolCallBlock.model_construct(+ created_at=A,+ id="call-2",+ name="get_time",+ input='{"tz":"UTC"}',+ ),+ ],+ ),+ )++ async def test_thinking_response(+ self,+ ) -> None:+ """Non-stream response with reasoning creates ThinkingBlock."""+ mock_create = AsyncMock(+ return_value=_mock_completion(+ text="The answer is 42.",+ reasoning="Let me think step by step...",+ ),+ )+ self.mock_client.chat.completions.create = mock_create++ result = await self.model([])++ self.assertEqual(+ (result.is_last, result.content),+ (+ True,+ [+ ThinkingBlock.model_construct(+ id=A,+ created_at=A,+ thinking="Let me think step by step...",+ ),+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text="The answer is 42.",+ ),+ ],+ ),+ )+++# ---------------------------------------------------------------------------+# Streaming tests+# ---------------------------------------------------------------------------+++class TestVolcengineStream(IsolatedAsyncioTestCase):+ """Tests for VolcengineChatModel in streaming mode."""++ def setUp(self) -> None:+ self.model = _make_model(stream=True)+ self.mock_client = MagicMock()+ self.model.client = self.mock_client++ async def test_stream_text_response(+ self,+ ) -> None:+ """Stream text yields n deltas (is_last=False) + 1 final+ (is_last=True) with full content."""+ chunks = [+ _make_stream_chunk(delta_text="Hello"),+ _make_stream_chunk(delta_text=" world"),+ _make_stream_chunk(delta_text="!"),+ _make_stream_chunk(+ has_choices=False,+ usage={"prompt_tokens": 10, "completion_tokens": 3},+ ),+ ]+ mock_create = AsyncMock(return_value=_MockAsyncStream(chunks))+ self.mock_client.chat.completions.create = mock_create++ gen = await self.model([])+ responses = [r async for r in gen]++ self.assertListEqual(+ [(r.is_last, r.content) for r in responses],+ [+ (+ False,+ [+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text="Hello",+ ),+ ],+ ),+ (+ False,+ [+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text=" world",+ ),+ ],+ ),+ (+ False,+ [TextBlock.model_construct(id=A, created_at=A, text="!")],+ ),+ (+ True,+ [+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text="Hello world!",+ ),+ ],+ ),+ ],+ )+ self.assertEqual(responses[-1].id, "volcengine-1")++ async def test_stream_thinking_and_text(+ self,+ ) -> None:+ """Stream with thinking + text yields deltas then final with both."""+ chunks = [+ _make_stream_chunk(delta_reasoning="Think"),+ _make_stream_chunk(delta_reasoning="ing..."),+ _make_stream_chunk(delta_text="Answer"),+ _make_stream_chunk(delta_text=" here."),+ _make_stream_chunk(+ has_choices=False,+ usage={"prompt_tokens": 10, "completion_tokens": 8},+ ),+ ]+ mock_create = AsyncMock(return_value=_MockAsyncStream(chunks))+ self.mock_client.chat.completions.create = mock_create++ gen = await self.model([])+ responses = [r async for r in gen]++ self.assertListEqual(+ [(r.is_last, r.content) for r in responses],+ [+ (+ False,+ [+ ThinkingBlock.model_construct(+ id=A,+ created_at=A,+ thinking="Think",+ ),+ ],+ ),+ (+ False,+ [+ ThinkingBlock.model_construct(+ id=A,+ created_at=A,+ thinking="ing...",+ ),+ ],+ ),+ (+ False,+ [+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text="Answer",+ ),+ ],+ ),+ (+ False,+ [+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text=" here.",+ ),+ ],+ ),+ (+ True,+ [+ ThinkingBlock.model_construct(+ id=A,+ created_at=A,+ thinking="Thinking...",+ ),+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text="Answer here.",+ ),+ ],+ ),+ ],+ )++ async def test_stream_tool_calls(+ self,+ ) -> None:+ """Stream tool calls accumulate across chunks into final response."""+ chunks = [+ _make_stream_chunk(+ delta_text=None,+ tool_calls=[+ _make_tool_call_delta(0, "call-1", "get_weather", '{"ci'),+ ],+ ),+ _make_stream_chunk(+ delta_text=None,+ tool_calls=[+ _make_tool_call_delta(0, None, None, 'ty":"BJ"}'),+ ],+ ),+ _make_stream_chunk(+ has_choices=False,+ usage={"prompt_tokens": 10, "completion_tokens": 5},+ ),+ ]+ mock_create = AsyncMock(return_value=_MockAsyncStream(chunks))+ self.mock_client.chat.completions.create = mock_create++ gen = await self.model([])+ responses = [r async for r in gen]++ self.assertListEqual(+ [(r.is_last, r.content) for r in responses],+ [+ (+ False,+ [+ ToolCallBlock.model_construct(+ created_at=A,+ id="call-1",+ name="get_weather",+ input='{"ci',+ ),+ ],+ ),+ (+ False,+ [+ ToolCallBlock.model_construct(+ created_at=A,+ id="call-1",+ name="get_weather",+ input='ty":"BJ"}',+ ),+ ],+ ),+ (+ True,+ [+ ToolCallBlock.model_construct(+ created_at=A,+ id="call-1",+ name="get_weather",+ input='{"city":"BJ"}',+ ),+ ],+ ),+ ],+ )++ async def test_stream_text_then_tool_call(+ self,+ ) -> None:+ """Stream with text followed by tool call accumulates both."""+ chunks = [+ _make_stream_chunk(delta_reasoning="Let me check"),+ _make_stream_chunk(delta_text="I'll look it up."),+ _make_stream_chunk(+ delta_text=None,+ tool_calls=[+ _make_tool_call_delta(+ 0,+ "call-1",+ "search",+ '{"q":"weather"}',+ ),+ ],+ ),+ _make_stream_chunk(+ has_choices=False,+ usage={"prompt_tokens": 15, "completion_tokens": 10},+ ),+ ]+ mock_create = AsyncMock(return_value=_MockAsyncStream(chunks))+ self.mock_client.chat.completions.create = mock_create++ gen = await self.model([])+ responses = [r async for r in gen]++ self.assertListEqual(+ [(r.is_last, r.content) for r in responses],+ [+ (+ False,+ [+ ThinkingBlock.model_construct(+ id=A,+ created_at=A,+ thinking="Let me check",+ ),+ ],+ ),+ (+ False,+ [+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text="I'll look it up.",+ ),+ ],+ ),+ (+ False,+ [+ ToolCallBlock.model_construct(+ created_at=A,+ id="call-1",+ name="search",+ input='{"q":"weather"}',+ ),+ ],+ ),+ (+ True,+ [+ ThinkingBlock.model_construct(+ id=A,+ created_at=A,+ thinking="Let me check",+ ),+ TextBlock.model_construct(+ id=A,+ created_at=A,+ text="I'll look it up.",+ ),+ ToolCallBlock.model_construct(+ created_at=A,+ id="call-1",+ name="search",+ input='{"q":"weather"}',+ ),+ ],+ ),+ ],+ )++ async def test_stream_usage_in_final(+ self,+ ) -> None:+ """Usage information is captured and present in final response."""+ chunks = [+ _make_stream_chunk(delta_text="Hi"),+ _make_stream_chunk(+ has_choices=False,+ usage={+ "prompt_tokens": 100,+ "completion_tokens": 20,+ "cached_tokens": 50,+ },+ ),+ ]+ mock_create = AsyncMock(return_value=_MockAsyncStream(chunks))+ self.mock_client.chat.completions.create = mock_create++ gen = await self.model([])+ responses = [r async for r in gen]++ self.assertListEqual(+ [(r.is_last, r.content) for r in responses],+ [+ (+ False,+ [TextBlock.model_construct(id=A, created_at=A, text="Hi")],+ ),+ (+ True,+ [TextBlock.model_construct(id=A, created_at=A, text="Hi")],+ ),+ ],+ )+ self.assertEqual(responses[-1].usage.input_tokens, 100)+ self.assertEqual(responses[-1].usage.output_tokens, 20)+ self.assertEqual(responses[-1].usage.cache_input_tokens, 50)+++class TestVolcengineModelParameters(unittest.TestCase):+ """Tests for VolcengineChatModel.Parameters."""++ def test_thinking_enable_stored_on_model(self) -> None:+ """thinking_enable is accessible through model.parameters."""+ model = VolcengineChatModel(+ credential=VolcengineCredential(api_key="test"),+ model="doubao-seed-2-1-pro-260628",+ stream=False,+ context_size=65_536,+ parameters=VolcengineChatModel.Parameters(thinking_enable=True),+ )+ self.assertTrue(model.parameters.thinking_enable)+ self.assertIsNone(VolcengineChatModel.Parameters().thinking_enable)++ def test_reasoning_effort_stored_on_model(self) -> None:+ """reasoning_effort is accessible through model.parameters."""+ model = VolcengineChatModel(+ credential=VolcengineCredential(api_key="test"),+ model="doubao-seed-2-1-pro-260628",+ stream=False,+ context_size=65_536,+ parameters=VolcengineChatModel.Parameters(reasoning_effort="high"),+ )+ self.assertEqual(model.parameters.reasoning_effort, "high")++ with self.assertRaises(ValueError):+ VolcengineChatModel.Parameters.model_validate(+ {"reasoning_effort": "max"},+ )++ def test_verified_model_card(self) -> None:+ """The versioned model ID is discoverable with Ark capabilities."""+ cards = VolcengineChatModel.list_models()++ self.assertEqual(len(cards), 1)+ self.assertEqual(cards[0].name, "doubao-seed-2-1-pro-260628")+ self.assertEqual(cards[0].context_size, 256000)+ self.assertEqual(cards[0].output_size, 256000)+ self.assertIn("image/*", cards[0].input_types)+ self.assertIn("video/*", cards[0].input_types)+ self.assertIn("application/x-thinking", cards[0].output_types)+ reasoning_schema = cards[0].parameter_schema["properties"][+ "reasoning_effort"+ ]+ self.assertEqual(+ reasoning_schema["anyOf"][0]["enum"],+ ["minimal", "low", "medium", "high"],+ )+ self.assertNotIn("enum", reasoning_schema)+++class TestVolcengineRequestParameters(IsolatedAsyncioTestCase):+ """Tests for Ark-specific request parameters."""++ async def test_thinking_and_reasoning_effort_are_forwarded(self) -> None:+ """Thinking controls use the request shape accepted by Ark."""+ model = VolcengineChatModel(+ credential=VolcengineCredential(api_key="test"),+ model="doubao-seed-2-1-pro-260628",+ stream=False,+ parameters=VolcengineChatModel.Parameters(+ thinking_enable=True,+ reasoning_effort="low",+ ),+ )+ mock_create = AsyncMock(+ return_value=_mock_completion(text="answer"),+ )+ model.client = MagicMock()+ model.client.chat.completions.create = mock_create++ await model([])++ kwargs = mock_create.await_args.kwargs+ self.assertEqual(kwargs["reasoning_effort"], "low")+ self.assertEqual(+ kwargs["extra_body"],+ {"thinking": {"type": "enabled"}},+ )++ async def test_thinking_uses_ark_default_when_unspecified(self) -> None:+ """An unspecified thinking mode should preserve Ark's auto default."""+ model = _make_model(stream=False)+ mock_create = AsyncMock(+ return_value=_mock_completion(text="answer"),+ )+ model.client = MagicMock()+ model.client.chat.completions.create = mock_create++ await model([])++ kwargs = mock_create.await_args.kwargs+ self.assertNotIn("reasoning_effort", kwargs)+ self.assertNotIn("extra_body", kwargs)++ async def test_thinking_can_be_explicitly_disabled(self) -> None:+ """An explicit false value should disable Ark thinking mode."""+ model = VolcengineChatModel(+ credential=VolcengineCredential(api_key="test"),+ model="doubao-seed-2-1-pro-260628",+ stream=False,+ parameters=VolcengineChatModel.Parameters(+ thinking_enable=False,+ ),+ )+ mock_create = AsyncMock(+ return_value=_mock_completion(text="answer"),+ )+ model.client = MagicMock()+ model.client.chat.completions.create = mock_create++ await model([])++ kwargs = mock_create.await_args.kwargs+ self.assertEqual(+ kwargs["extra_body"],+ {"thinking": {"type": "disabled"}},+ )+++class TestVolcengineCredential(unittest.TestCase):+ """Tests for Volcengine Ark credential discovery and serialization."""++ def test_defaults_and_serialization(self) -> None:+ """The credential stores Ark's endpoint and round-trips via factory."""+ credential = VolcengineCredential(api_key="secret")+ data = credential.model_dump(mode="json")++ self.assertEqual(+ credential.base_url,+ "https://ark.cn-beijing.volces.com/api/v3",+ )+ restored = CredentialFactory.from_dict(data)+ self.assertIsInstance(restored, VolcengineCredential)+ self.assertEqual(restored.api_key.get_secret_value(), "**********")+ self.assertEqual(restored.base_url, credential.base_url)++ def test_factory_lookup(self) -> None:+ """The factory exposes the Volcengine credential discriminator."""+ self.assertIs(+ CredentialFactory.get_credential_class("volcengine_credential"),+ VolcengineCredential,+ )+++# ---------------------------------------------------------------------------+# Shared _format_tools fixtures+# ---------------------------------------------------------------------------++_FT_TOOLS = [+ {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Get the weather",+ "parameters": {+ "type": "object",+ "properties": {"city": {"type": "string"}},+ "required": ["city"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "get_time",+ "description": "Get the time",+ "parameters": {+ "type": "object",+ "properties": {"timezone": {"type": "string"}},+ "required": ["timezone"],+ },+ },+ },+]+++class TestVolcengineFormatTools(unittest.TestCase):+ """Tests for VolcengineChatModel._format_tools."""++ def setUp(self) -> None:+ """Set up model instance."""+ self.model = _make_model()++ def test_auto_mode(self) -> None:+ """Auto mode returns tools unchanged and string 'auto'."""+ fmt_tools, fmt_choice = self.model._format_tools(+ _FT_TOOLS,+ ToolChoice(mode="auto"),+ )+ self.assertEqual(fmt_tools, _FT_TOOLS)+ self.assertEqual(fmt_choice, "auto")++ def test_none_mode(self) -> None:+ """None mode returns tools unchanged and string 'none'."""+ fmt_tools, fmt_choice = self.model._format_tools(+ _FT_TOOLS,+ ToolChoice(mode="none"),+ )+ self.assertEqual(fmt_tools, _FT_TOOLS)+ self.assertEqual(fmt_choice, "none")++ def test_required_mode(self) -> None:+ """Required mode returns tools unchanged and string 'required'."""+ fmt_tools, fmt_choice = self.model._format_tools(+ _FT_TOOLS,+ ToolChoice(mode="required"),+ )+ self.assertEqual(fmt_tools, _FT_TOOLS)+ self.assertEqual(fmt_choice, "required")++ def test_str_mode_force_call(self) -> None:+ """A specific tool name returns a type=function dict."""+ fmt_tools, fmt_choice = self.model._format_tools(+ _FT_TOOLS,+ ToolChoice(mode="get_weather"),+ )+ self.assertEqual(fmt_tools, _FT_TOOLS)+ self.assertEqual(+ fmt_choice,+ {"type": "function", "function": {"name": "get_weather"}},+ )++ def test_tools_filtered(self) -> None:+ """When tool_choice.tools is set, only those tools are included."""+ fmt_tools, fmt_choice = self.model._format_tools(+ _FT_TOOLS,+ ToolChoice(mode="auto", tools=["get_weather"]),+ )+ self.assertEqual(len(fmt_tools), 1)+ self.assertEqual(fmt_tools[0]["function"]["name"], "get_weather")+ self.assertEqual(fmt_choice, "auto")++ def test_no_tool_choice(self) -> None:+ """Without tool_choice, returns tools and None."""+ fmt_tools, fmt_choice = self.model._format_tools(_FT_TOOLS, None)+ self.assertEqual(fmt_tools, _FT_TOOLS)+ self.assertIsNone(fmt_choice)diff --git a/tests/tracing_test.py b/tests/tracing_test.pyindex fdb7a59f0..89301a35d 100644--- a/tests/tracing_test.py+++ b/tests/tracing_test.py@@ -16,6 +16,7 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import (from utils import MockModelfrom agentscope.agent import Agent, InjectionConfig+from agentscope.credential import OpenAICredential, VolcengineCredentialfrom agentscope.event import (ConfirmResult,ExternalExecutionResultEvent,@@ -32,9 +33,16 @@ from agentscope.message import ()from agentscope.middleware._tracing._attributes import SpanAttributesfrom agentscope.middleware._tracing._extractor import (+ _get_provider_name,_get_llm_response_attributes,)-from agentscope.model import ChatResponse, ChatUsage, FinishedReason+from agentscope.model import (+ ChatResponse,+ ChatUsage,+ FinishedReason,+ OpenAIChatModel,+ VolcengineChatModel,+)from agentscope.permission import (PermissionContext,PermissionDecision,@@ -145,6 +153,27 @@ class ExternalWeatherTool(ToolBase):class TracingExtractorTest(TestCase):"""Tests for tracing attribute extraction helpers."""+ def test_volcengine_provider_name_from_model_class(self) -> None:+ """Volcengine models should use the Volcengine provider name."""+ model = VolcengineChatModel(+ credential=VolcengineCredential(api_key="test"),+ model="doubao-seed-2-1-pro-260628",+ )++ self.assertEqual(_get_provider_name(model), "volcengine")++ def test_volcengine_provider_name_from_openai_base_url(self) -> None:+ """Ark's OpenAI-compatible endpoint should map to Volcengine."""+ model = OpenAIChatModel(+ credential=OpenAICredential(+ api_key="test",+ base_url="https://ark.cn-beijing.volces.com/api/v3",+ ),+ model="doubao-seed-2-1-pro-260628",+ )++ self.assertEqual(_get_provider_name(model), "volcengine")+def test_llm_response_tracing_uses_chat_response_finish_reason(self,) -> None: