Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(msg): formalize Msg type rules and constraints and add message related tests (#1454)
DavdGaof894a1c6d690
diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.ymlindex 9b6741a69..475e7f318 100644--- a/.github/workflows/pre-commit.yml+++ b/.github/workflows/pre-commit.yml@@ -11,13 +11,13 @@ jobs:os: [ubuntu-latest]env:OS: ${{ matrix.os }}- PYTHON: '3.10'+ PYTHON: '3.11'steps:- uses: actions/checkout@master- name: Install uvuses: astral-sh/setup-uv@v5with:- python-version: '3.10'+ python-version: '3.11'- name: Install AgentScoperun: |uv pip install -q -e .[dev]diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.ymlindex 33e084a83..58f4f08a1 100644--- a/.github/workflows/publish-pypi.yml+++ b/.github/workflows/publish-pypi.yml@@ -26,7 +26,7 @@ jobs:- name: Install uvuses: astral-sh/setup-uv@v5with:- python-version: '3.10'+ python-version: '3.11'- name: Install dependenciesrun: |uv pip install builddiff --git a/.github/workflows/sphinx_docs.yml b/.github/workflows/sphinx_docs.ymldeleted file mode 100644index 030eca16e..000000000--- a/.github/workflows/sphinx_docs.yml+++ /dev/null@@ -1,95 +0,0 @@-name: Deploy Sphinx documentation to Pages--on:- push:- branches:- - main--jobs:- build_en:- timeout-minutes: 20- runs-on: ${{ matrix.os }}- strategy:- matrix:- os: [ubuntu-latest]- python-version: ['3.10']- env:- OS: ${{ matrix.os }}- PYTHON: '3.10'- steps:- - uses: actions/checkout@v6- - name: Setup Python- uses: actions/setup-python@v6- with:- python-version: '3.10'- - name: Update setuptools- run: |- pip install setuptools==78.1.1 wheel==0.45.1- - name: Install Dependencies- run: |- pip install -q -e .[dev]- - name: Add execute permission to build.sh- run: |- chmod +x docs/tutorial/en/build.sh- - name: Build English Documentation- env:- DASHSCOPE_API_KEY: ${{ secrets.DASHSCOPE_API_KEY }}- GAODE_API_KEY: ${{ secrets.GAODE_API_KEY }}- run: |- cd docs/tutorial/en/- ./build.sh- - name: Deploy English Documentation- uses: peaceiris/actions-gh-pages@v4- with:- github_token: ${{ secrets.GITHUB_TOKEN }}- publish_dir: docs/tutorial/en/build/html- cname: doc.agentscope.io- keep_files: true-- build_zh:- needs: build_en- timeout-minutes: 20- runs-on: ${{ matrix.os }}- strategy:- matrix:- os: [ ubuntu-latest ]- python-version: [ '3.10' ]- env:- OS: ${{ matrix.os }}- PYTHON: '3.10'- steps:- - uses: actions/checkout@v6- - name: Setup Python- uses: actions/setup-python@v6- with:- python-version: '3.10'- - name: Setup Node.js- uses: actions/setup-node@v6- with:- node-version: '16'- - name: Verify npm installation- run: npm --version- - name: Update setuptools- run: |- pip install setuptools==78.1.1 wheel==0.45.1- - name: Install Dependencies- run: |- pip install -q -e .[dev]- - name: Add execute permission to build.sh- run: |- chmod +x docs/tutorial/zh_CN/build.sh- - name: Build Chinese Documentation- env:- DASHSCOPE_API_KEY: ${{ secrets.DASHSCOPE_API_KEY }}- GAODE_API_KEY: ${{ secrets.GAODE_API_KEY }}- run: |- cd docs/tutorial/zh_CN/- ./build.sh- - name: Deploy Chinese Documentation- uses: peaceiris/actions-gh-pages@v4- with:- github_token: ${{ secrets.GITHUB_TOKEN }}- publish_dir: docs/tutorial/zh_CN/build/html- destination_dir: zh_CN- cname: doc.agentscope.io- keep_files: true\ No newline at end of filediff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.ymlindex f4f38383c..3b9fd773a 100644--- a/.github/workflows/unittest.yml+++ b/.github/workflows/unittest.yml@@ -9,7 +9,7 @@ jobs:strategy:matrix:os: [ubuntu-latest, windows-latest, macos-15]- python-version: ['3.12']+ python-version: ['3.11']env:OS: ${{ matrix.os }}steps:diff --git a/pyproject.toml b/pyproject.tomlindex e3615dd69..d3c7d7adf 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -8,17 +8,17 @@ authors = [{ name = "SysML team of Alibaba Tongyi Lab", email = "[email protected]" }]license = "Apache-2.0"-keywords = ["deep-learning", "multi agents", "agents"]+keywords = ["agent", "multi-agent", "LLM", "AI"]classifiers = ["Development Status :: 4 - Beta","Programming Language :: Python :: 3",- "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11","Operating System :: OS Independent","Intended Audience :: Developers","Intended Audience :: Science/Research","Topic :: Scientific/Engineering :: Artificial Intelligence",]-requires-python = ">=3.10"+requires-python = ">=3.11"dependencies = ["aioitertools","anthropic",@@ -27,7 +27,7 @@ dependencies = ["filetype","json5","json_repair",- "mcp>=1.13",+ "mcp","numpy","openai","python-datauri",@@ -37,25 +37,11 @@ dependencies = ["opentelemetry-semantic-conventions>=0.60b0","python-socketio","shortuuid",- "tiktoken",- "sounddevice",- "sqlalchemy","python-frontmatter","aiofiles",][project.optional-dependencies]-# ------------ A2A protocol -------------a2a = [- "a2a-sdk",- "httpx",- # TODO: split the card resolvers from the a2a dependency- "nacos-sdk-python>=3.0.0",-]--# ------------ Realtime --------------realtime = ["websockets>=14.0", "scipy"]-# ------------ Model APIs ------------gemini = ["google-genai"]ollama = ["ollama>=0.5.4"]@@ -64,104 +50,9 @@ models = ["agentscope[gemini]",]-# ------------ Tokenizers -------------tokens = [- "Pillow",- "transformers",- "jinja2",-]--# ------------ Memory -------------redis_memory = ["redis"]--mem0ai = [- "mem0ai<=1.0.3",- "packaging"-]-reme = ["reme-ai>=0.2.0.3"]-memory = [- "agentscope[redis_memory]",- "agentscope[mem0ai]",- "agentscope[reme]",-]--# ------------ RAG -------------# readers-text-reader = ["nltk"]-pdf-reader = [- "agentscope[text-reader]",- # TODO: the latest pypdf has some issues with parsing PDFs- # (2026-01-13), so we fix the version here temporarily.- "pypdf<=6.5.0",-]-docx-reader = [- "agentscope[text-reader]",- "python-docx"-]-excel-reader = [- "agentscope[text-reader]",- "pandas",- "openpyxl",-]-ppt-reader = [- "agentscope[text-reader]",- "python-pptx"-]-readers = [- "agentscope[text-reader]",- "agentscope[pdf-reader]",- "agentscope[docx-reader]",- "agentscope[excel-reader]",- "agentscope[ppt-reader]",-]--# vdb-# The qdrant-client >= 1.16.0 has conflicts with pymilvus, so we fix-# the version to 1.15.1 here.-qdrant = ["qdrant-client==1.15.1"]-milvus = ["pymilvus[milvus_lite]==2.6.2"]-ali_mysql = ["mysql-connector-python"]-mongodb = ["pymongo"]-oceanbase = ["pyobvector>=0.2.0,<0.3.0"]-vdbs = [- "agentscope[ali_mysql]",- "agentscope[qdrant]",- "agentscope[milvus]",- "agentscope[mongodb]",- "agentscope[oceanbase]",-]--rag = [- "agentscope[readers]",- "agentscope[vdbs]",-]--# ------------ Evaluation -------------evaluate = ["ray"]--# ------------ Tuner -------------tuner = [- "dspy>=3.1.0",- "datasets>=4.0.0",- "litellm[proxy]>=1.75.3",-]--tuner-gpu = [- "trinity-rft>=0.5.0",- "dspy>=3.1.0",- "datasets>=4.0.0",- "litellm[proxy]>=1.75.3"-]-# ------------ Full ------------full = [- "agentscope[a2a]","agentscope[models]",- "agentscope[tokens]",- "agentscope[memory]",- "agentscope[rag]",- "agentscope[evaluate]",- "agentscope[realtime]",]# ------------ Development ------------@@ -176,15 +67,6 @@ dev = ["furo","myst_parser","matplotlib",- # For unittests- # For mocking redis in unittests- "fakeredis",- "aiosqlite",- "greenlet",- # For openjudge- "py-openjudge",- # For tuner- "dspy",][project.urls]diff --git a/src/agentscope/_utils/_common.py b/src/agentscope/_utils/_common.pyindex cc09f48f1..995954f74 100644--- a/src/agentscope/_utils/_common.py+++ b/src/agentscope/_utils/_common.py@@ -6,14 +6,11 @@ import functoolsimport inspectimport jsonimport os-import tempfileimport types-import typingimport uuidfrom datetime import datetimefrom typing import Any, Callable, Type, Dict-import numpy as npimport requestsfrom docstring_parser import parsefrom json_repair import repair_json@@ -22,11 +19,6 @@ from pydantic import BaseModel, Field, create_model, ConfigDictfrom .._logging import loggerfrom ..types import ToolFunction-if typing.TYPE_CHECKING:- from mcp.types import Tool-else:- Tool = "mcp.types.Tool"-def _json_loads_with_repair(json_str: str,@@ -69,40 +61,6 @@ def _json_loads_with_repair(return {}-def _parse_streaming_json_dict(- json_str: str,- last_input: dict | None = None,-) -> dict:- """Parse a streaming JSON dict without regressing on incomplete chunks.-- If the current chunk already forms a valid JSON dict, prefer it directly.- Otherwise, fall back to repaired JSON and keep the previous parsed value- only when repair would shrink the intermediate structure.- """- json_str = json_str or "{}"- try:- result = json.loads(json_str)- if isinstance(result, dict):- return result- except Exception:- pass-- repaired_input = _json_loads_with_repair(json_str)- last_input = last_input or {}- if len(json.dumps(last_input)) > len(json.dumps(repaired_input)):- return last_input- return repaired_input---def _is_accessible_local_file(url: str) -> bool:- """Check if the given URL is a local URL."""- # First identify if it's an uri with 'file://' schema,- if url.startswith("file://"):- local_path = url.removeprefix("file://")- return os.path.isfile(local_path)- return os.path.isfile(url)--def _get_timestamp(add_random_suffix: bool = False) -> str:"""Get the current timestamp in the format YYYY-MM-DD HH:MM:SS.sss."""timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]@@ -189,53 +147,6 @@ def _get_bytes_from_web_url()-def _save_base64_data(- media_type: str,- base64_data: str,-) -> str:- """Save the base64 data to a temp file and return the file path. The- extension is guessed from the MIME type.-- Args:- media_type (`str`):- The MIME type of the data, e.g. "image/png", "audio/mpeg".- base64_data (`str`):- The base64 data to be saved.- """- extension = "." + media_type.split("/")[-1]-- with tempfile.NamedTemporaryFile(- suffix=extension,- delete=False,- ) as temp_file:- decoded_data = base64.b64decode(base64_data)- temp_file.write(decoded_data)- return temp_file.name---def _extract_json_schema_from_mcp_tool(tool: Tool) -> dict[str, Any]:- """Extract JSON schema from MCP tool."""-- return {- "type": "function",- "function": {- "name": tool.name,- "description": tool.description,- "parameters": {- "type": "object",- "properties": tool.inputSchema.get(- "properties",- {},- ),- "required": tool.inputSchema.get(- "required",- [],- ),- },- },- }--def _remove_title_field(schema: dict) -> None:"""Remove the title field from the JSON schema to avoidmisleading the LLM."""@@ -453,50 +364,3 @@ def _parse_tool_function(func_json_schema["function"]["description"] = func_descriptionreturn func_json_schema---def _resample_pcm_delta(- pcm_base64: str,- sample_rate: int,- target_rate: int,-) -> str:- """Resampling the input pcm base64 data into the target rate.-- Args:- pcm_base64 (`str`):- The input base64 audio data in pcm format.- sample_rate (`int`):- The sampling rate of the input data.- target_rate (`int`):- The target rate of the input data.-- Returns:- `str`:- The resampling base64 audio data in the required sampling- rate.- """- pcm_data = base64.b64decode(pcm_base64)-- # Into numpy array first- audio_array = np.frombuffer(pcm_data, dtype=np.int16)-- # return directly if the same- if sample_rate == target_rate:- return pcm_base64-- # compute the number of samples- num_samples = int(len(audio_array) * target_rate / sample_rate)-- from scipy import signal-- # Use scipy to resample- resampled_audio = signal.resample(audio_array, num_samples)-- # Turn it back into bytes- resampled_audio = np.clip(resampled_audio, -32768, 32767).astype(np.int16)-- # into base64- resampled_bytes = resampled_audio.tobytes()- resampled_base64 = base64.b64encode(resampled_bytes).decode("utf-8")-- return resampled_base64diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.pyindex fcb8460f2..f9b3ca943 100644--- a/src/agentscope/event/_event.py+++ b/src/agentscope/event/_event.py@@ -54,7 +54,7 @@ class EventBase(BaseModel):id: str = Field(default_factory=lambda: uuid.uuid4().hex)"""Unique event identifier."""- created_at: str = Field(default_factory=lambda: datetime.now().isoformat())+ created_at: str = Field(default_factory=datetime.now().isoformat)"""ISO 8601 timestamp of when the event was created."""diff --git a/src/agentscope/message/_base.py b/src/agentscope/message/_base.pyindex 26e859499..8697bca12 100644--- a/src/agentscope/message/_base.py+++ b/src/agentscope/message/_base.py@@ -1,10 +1,10 @@# -*- coding: utf-8 -*-"""The message class in agentscope."""from datetime import datetime-from typing import Literal, List, overload, Sequence+from typing import Literal, List, overload, Sequence, Selfimport shortuuid-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, model_validatorfrom ._block import (TextBlock,@@ -43,15 +43,33 @@ def _assert_system_content_blocks(class Msg(BaseModel):- """The message class in agentscope."""+ """The message class in AgentScope, responsible for information storage+ and transmission among different agents."""name: str+ """The name of the sender."""content: str | list[ContentBlock]+ """The message content, a string or a list of content blocks."""role: Literal["user", "assistant", "system"]-+ """The role of the sender."""id: str = Field(default_factory=shortuuid.uuid)+ """The message identifier."""metadata: dict = Field(default_factory=dict)+ """The metadata of the message"""created_at: str = Field(default_factory=datetime.now().isoformat)+ """The creation time of the message"""++ @model_validator(mode="after")+ def validate_role_content(self) -> Self:+ """Validate content blocks according to the role."""+ match self.role:+ case "user":+ _assert_user_content_blocks(self.content)+ case "system":+ _assert_system_content_blocks(self.content)+ case "assistant":+ pass+ return selfdef has_content_blocks(self,@@ -198,7 +216,6 @@ def UserMsg(`Msg`:The created user message."""- _assert_user_content_blocks(content)return Msg(name=name,@@ -264,7 +281,6 @@ def SystemMsg(`Msg`:The created system message."""- _assert_system_content_blocks(content)return Msg(name=name,diff --git a/src/agentscope/message/_block.py b/src/agentscope/message/_block.pyindex 366091491..5ffe5e085 100644--- a/src/agentscope/message/_block.py+++ b/src/agentscope/message/_block.py@@ -2,77 +2,115 @@"""The content blocks of messages."""import uuidfrom typing import Literal, List, TypeAlias-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, AnyUrl, field_serializerclass TextBlock(BaseModel):"""The text block."""type: Literal["text"] = "text"+ """The type of the text block, which is always 'text'."""text: str+ """The text content of the block."""id: str = Field(default_factory=lambda: uuid.uuid4().hex)+ """The unique identifier of the block."""class ThinkingBlock(BaseModel):"""The thinking block."""type: Literal["thinking"] = "thinking"+ """The type of the thinking block, which is always 'thinking'."""thinking: str+ """The thinking content of the block."""id: str = Field(default_factory=lambda: uuid.uuid4().hex)+ """The unique identifier of the block."""class HintBlock(BaseModel):- """The hint block."""+ """A block used to provide instructions or hints to the LLM during the+ reasoning-acting loop. When passed to the LLM API, the hint block is+ converted into a user message.+ """type: Literal["hint"] = "hint"+ """The type of the hint block, which is always 'hint'."""hint: str+ """The hint content of the block."""id: str = Field(default_factory=lambda: uuid.uuid4().hex)+ """The unique identifier of the block."""class Base64Source(BaseModel):"""The base64 source."""type: Literal["base64"] = "base64"+ """The type of the base64 source, which is always 'base64'."""data: str+ """The base64-encoded data."""media_type: str+ """The media type of the data, e.g., 'image/png', 'audio/mpeg', etc."""class URLSource(BaseModel):"""The URL source."""type: Literal["url"] = "url"- url: str+ """The type of the URL source, which is always 'url'."""+ url: AnyUrl+ """A valid URI string conforming to RFC 3986."""media_type: str+ """The media type of the data, e.g., 'image/png', 'audio/mpeg', etc."""++ @field_serializer("url")+ def serialize_url(self, url: AnyUrl) -> str:+ """Serialize the URL to a string."""+ return str(url)class DataBlock(BaseModel):"""The data block for binary content (images, audio, video, etc.)."""type: Literal["data"] = "data"+ """The type of the data block, which is always 'data'."""id: str = Field(default_factory=lambda: uuid.uuid4().hex)+ """The unique identifier of the block."""source: Base64Source | URLSource+ """The source of the data, which can be either a base64-encoded string or+ a URL."""name: str | None = None+ """The name of the data block, which is optional."""class ToolCallBlock(BaseModel):"""The tool call block."""type: Literal["tool_call"] = "tool_call"+ """The type of the tool call block, which is always 'tool_call'."""id: str+ """The unique identifier of the tool call block."""name: str+ """The name of the tool to be called."""input: str"""The raw JSON string input of the tool, accumulated during streaming."""await_user_confirmation: bool = False+ """Whether to await user confirmation before executing the tool."""class ToolResultBlock(BaseModel):"""The tool result block."""type: Literal["tool_result"] = "tool_result"+ """The type of the tool result block, which is always 'tool_result'."""id: str+ """The unique identifier of the tool result block."""name: str+ """The name of the tool."""output: str | List[TextBlock | DataBlock]+ """The output of the tool, which can be a raw string of a list of+ text and multimodal blocks."""state: Literal["success", "error", "interrupted", "running"]+ """The execution state of the tool."""ContentBlock: TypeAlias = (diff --git a/src/agentscope/tool/__init__.py b/src/agentscope/tool/__init__.pyindex a77ff2747..bafcf15bc 100644--- a/src/agentscope/tool/__init__.py+++ b/src/agentscope/tool/__init__.py@@ -2,43 +2,9 @@"""The tool module in agentscope."""from ._response import ToolResponse-from ._coding import (- execute_python_code,- execute_shell_command,-)-from ._text_file import (- view_text_file,- write_text_file,- insert_text_file,-)-from ._multi_modality import (- dashscope_text_to_image,- dashscope_text_to_audio,- dashscope_image_to_text,- openai_text_to_image,- openai_text_to_audio,- openai_edit_image,- openai_create_image_variation,- openai_image_to_text,- openai_audio_to_text,-)from ._toolkit import Toolkit__all__ = ["Toolkit","ToolResponse",- "execute_python_code",- "execute_shell_command",- "view_text_file",- "write_text_file",- "insert_text_file",- "dashscope_text_to_image",- "dashscope_text_to_audio",- "dashscope_image_to_text",- "openai_text_to_image",- "openai_text_to_audio",- "openai_edit_image",- "openai_create_image_variation",- "openai_image_to_text",- "openai_audio_to_text",]diff --git a/tests/message_test.py b/tests/message_test.pynew file mode 100644index 000000000..7d89b65c8--- /dev/null+++ b/tests/message_test.py@@ -0,0 +1,249 @@+# -*- coding: utf-8 -*-+"""A template test case."""+from unittest.async_case import IsolatedAsyncioTestCase+from utils import AnyString++from agentscope.message import (+ UserMsg,+ TextBlock,+ DataBlock,+ URLSource,+ Base64Source,+ ThinkingBlock,+ AssistantMsg,+ HintBlock,+ Msg,+ ToolCallBlock,+ ToolResultBlock,+)+++class MessageTest(IsolatedAsyncioTestCase):+ """The template test case."""++ async def test_creating_message(self) -> None:+ """The template test."""+ # Test string content+ user_msg = UserMsg(name="user", content="hello world")+ self.assertDictEqual(+ user_msg.model_dump(),+ {+ "id": AnyString(),+ "name": "user",+ "role": "user",+ "content": "hello world",+ "metadata": {},+ "created_at": AnyString(),+ },+ )++ # Test list of content+ user_msg = UserMsg(+ name="user",+ content=[TextBlock(text="1"), TextBlock(text="2")],+ )+ self.assertDictEqual(+ user_msg.model_dump(),+ {+ "id": AnyString(),+ "name": "user",+ "role": "user",+ "content": [+ {"type": "text", "text": "1", "id": AnyString()},+ {"type": "text", "text": "2", "id": AnyString()},+ ],+ "metadata": {},+ "created_at": AnyString(),+ },+ )++ # Test DataBlock content+ user_msg = UserMsg(+ name="user",+ content=[+ TextBlock(text="1"),+ DataBlock(+ source=URLSource(+ url="https://example.com/image.png",+ media_type="image/png",+ ),+ ),+ DataBlock(+ source=Base64Source(+ data="iVBORw0KGgoAAAANSUhEUgAAAAUA",+ media_type="image/png",+ ),+ ),+ ],+ )++ self.assertDictEqual(+ user_msg.model_dump(),+ {+ "id": AnyString(),+ "name": "user",+ "role": "user",+ "content": [+ {"type": "text", "text": "1", "id": AnyString()},+ {+ "type": "data",+ "id": AnyString(),+ "source": {+ "type": "url",+ "url": "https://example.com/image.png",+ "media_type": "image/png",+ },+ "name": None,+ },+ {+ "type": "data",+ "id": AnyString(),+ "source": {+ "type": "base64",+ "data": "iVBORw0KGgoAAAANSUhEUgAAAAUA",+ "media_type": "image/png",+ },+ "name": None,+ },+ ],+ "metadata": {},+ "created_at": AnyString(),+ },+ )++ # Test thinking content+ msg = AssistantMsg(+ name="assistant",+ content=[ThinkingBlock(thinking="thinking...")],+ )+ self.assertDictEqual(+ msg.model_dump(),+ {+ "id": AnyString(),+ "name": "assistant",+ "role": "assistant",+ "content": [+ {+ "type": "thinking",+ "thinking": "thinking...",+ "id": AnyString(),+ },+ ],+ "metadata": {},+ "created_at": AnyString(),+ },+ )++ # Test hint content+ msg = AssistantMsg(+ name="assistant",+ content=[HintBlock(hint="hint...")],+ )+ self.assertDictEqual(+ msg.model_dump(),+ {+ "id": AnyString(),+ "name": "assistant",+ "role": "assistant",+ "content": [+ {"type": "hint", "hint": "hint...", "id": AnyString()},+ ],+ "metadata": {},+ "created_at": AnyString(),+ },+ )++ async def test_invalid_message(self) -> None:+ """Test invalid message creation."""+ # User message with thinking block should raise ValueError+ with self.assertRaises(ValueError):+ Msg(+ name="user",+ role="user",+ content=[ThinkingBlock(thinking="thinking...")],+ )++ # User message with hint block should raise ValueError+ with self.assertRaises(ValueError):+ Msg(+ name="user",+ role="user",+ content=[HintBlock(hint="hint...")],+ )++ # User message with tool call block should raise ValueError+ with self.assertRaises(ValueError):+ Msg(+ name="user",+ role="user",+ content=[ToolCallBlock(id="1", name="tool", input="{}")],+ )++ # User message with tool result block should raise ValueError+ with self.assertRaises(ValueError):+ Msg(+ name="user",+ role="user",+ content=[+ ToolResultBlock(+ id="1",+ name="tool",+ output="result",+ state="success",+ ),+ ],+ )++ # System message with data block should raise ValueError+ with self.assertRaises(ValueError):+ Msg(+ name="system",+ role="system",+ content=[+ DataBlock(+ source=URLSource(+ url="https://example.com/image.png",+ media_type="image/png",+ ),+ ),+ ],+ )++ # System message with thinking block should raise ValueError+ with self.assertRaises(ValueError):+ Msg(+ name="system",+ role="system",+ content=[ThinkingBlock(thinking="thinking...")],+ )++ # System message with hint block should raise ValueError+ with self.assertRaises(ValueError):+ Msg(+ name="system",+ role="system",+ content=[HintBlock(hint="hint...")],+ )++ # System message with tool call block should raise ValueError+ with self.assertRaises(ValueError):+ Msg(+ name="system",+ role="system",+ content=[ToolCallBlock(id="1", name="tool", input="{}")],+ )++ # System message with tool result block should raise ValueError+ with self.assertRaises(ValueError):+ Msg(+ name="system",+ role="system",+ content=[+ ToolResultBlock(+ id="1",+ name="tool",+ output="result",+ state="success",+ ),+ ],+ )diff --git a/tests/test_template.py b/tests/test_template.pyindex 418f58898..b7260e948 100644--- a/tests/test_template.py+++ b/tests/test_template.py@@ -6,5 +6,11 @@ from unittest.async_case import IsolatedAsyncioTestCaseclass TemplateTest(IsolatedAsyncioTestCase):"""The template test case."""+ async def asyncSetUp(self) -> None:+ """The async setup method."""+async def test_template(self) -> None:"""The template test."""++ async def asyncTearDown(self) -> None:+ """The async teardown method."""diff --git a/tests/utils.py b/tests/utils.pynew file mode 100644index 000000000..0c8c38448--- /dev/null+++ b/tests/utils.py@@ -0,0 +1,14 @@+# -*- coding: utf-8 -*-+"""The utility module for unit tests in agentscope."""+++class AnyString:+ """A helper class for asserting any string value in unit tests."""++ def __eq__(self, other: object) -> bool:+ """Override equality check to match any string."""+ return isinstance(other, str)++ def __repr__(self) -> str:+ """Return a string representation for debugging purposes."""+ return "<AnyString>"