Skip to content

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

fix(event): validate tool result data source (#2370)

Xinmin Zeng56eea457c49f
diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.py
index ad2e65465..774a60bcf 100644
--- a/src/agentscope/event/_event.py
+++ b/src/agentscope/event/_event.py
@@ -2,9 +2,9 @@
"""Event types for agent execution."""
from datetime import datetime
from enum import StrEnum
-from typing import Any, Dict, Literal, List, TypeAlias
+from typing import Any, Dict, Literal, List, Self, TypeAlias
-from pydantic import BaseModel, Field, ConfigDict
+from pydantic import BaseModel, Field, ConfigDict, model_validator
from typing_extensions import deprecated
from .._utils._common import _generate_id
@@ -376,6 +376,15 @@ class ToolResultDataDeltaEvent(EventBase):
url: str | None = None
"""URL pointing to the binary content, mutually exclusive with `data`."""
+ @model_validator(mode="after")
+ def validate_data_source(self) -> Self:
+ """Ensure exactly one data source is provided."""
+ if (self.data is None) == (self.url is None):
+ raise ValueError(
+ "Exactly one of `data` or `url` must be provided.",
+ )
+ return self
+
class ToolResultEndEvent(EventBase):
"""Tool result end event."""
diff --git a/tests/event_test.py b/tests/event_test.py
index f766d9556..d2069db0f 100644
--- a/tests/event_test.py
+++ b/tests/event_test.py
@@ -1,8 +1,11 @@
# -*- coding: utf-8 -*-
"""Event test"""
from unittest.async_case import IsolatedAsyncioTestCase
+
+from pydantic import ValidationError
+
from utils import AnyString
-from agentscope.event import ReplyStartEvent
+from agentscope.event import ReplyStartEvent, ToolResultDataDeltaEvent
class EventTest(IsolatedAsyncioTestCase):
@@ -46,5 +49,44 @@ class EventTest(IsolatedAsyncioTestCase):
}
ReplyStartEvent.model_validate(data)
+ async def test_tool_result_data_delta_source_validation(self) -> None:
+ """Test exactly one data source is required."""
+ common = {
+ "reply_id": "test_reply",
+ "tool_call_id": "test_tool_call",
+ "media_type": "image/png",
+ }
+
+ data_event = ToolResultDataDeltaEvent(
+ **common,
+ data="iVBOR==",
+ )
+ self.assertEqual(data_event.data, "iVBOR==")
+ self.assertIsNone(data_event.url)
+
+ url_event = ToolResultDataDeltaEvent(
+ **common,
+ url="https://example.com/image.png",
+ )
+ self.assertIsNone(url_event.data)
+ self.assertEqual(url_event.url, "https://example.com/image.png")
+
+ for invalid_source in (
+ {},
+ {
+ "data": "iVBOR==",
+ "url": "https://example.com/image.png",
+ },
+ ):
+ with self.subTest(source=invalid_source):
+ with self.assertRaisesRegex(
+ ValidationError,
+ "Exactly one of",
+ ):
+ ToolResultDataDeltaEvent(
+ **common,
+ **invalid_source,
+ )
+
async def asyncTearDown(self) -> None:
"""The async teardown method."""