Skip to content

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

fix(tool): validate AskUser question constraints (#2586)

WuWenbo8625818347be
diff --git a/src/agentscope/tool/_builtin/_ask_user.py b/src/agentscope/tool/_builtin/_ask_user.py
index 62f3c2882..4a1ea64a0 100644
--- a/src/agentscope/tool/_builtin/_ask_user.py
+++ b/src/agentscope/tool/_builtin/_ask_user.py
@@ -2,7 +2,7 @@
"""The asking user tool class."""
from typing import Any
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, model_validator
from .._base import ToolBase
from ...permission import (
@@ -94,6 +94,14 @@ class _Question(BaseModel):
),
)
+ @model_validator(mode="after")
+ def _validate_options(self) -> "_Question":
+ """Reject ambiguous or unsupported option combinations."""
+ labels = [option.label for option in self.options]
+ if len(labels) != len(set(labels)):
+ raise ValueError("option labels must be unique within a question")
+ return self
+
class AskUserAnswer(BaseModel):
"""One question's answer, as the caller must return it.
@@ -146,6 +154,14 @@ class AskUserParams(BaseModel):
),
)
+ @model_validator(mode="after")
+ def _validate_question_texts(self) -> "AskUserParams":
+ """Reject question batches whose answers cannot be correlated."""
+ questions = [question.question for question in self.questions]
+ if len(questions) != len(set(questions)):
+ raise ValueError("question texts must be unique across the batch")
+ return self
+
class AskUser(ToolBase):
"""The tool to collect information from the user via multiple-choice
diff --git a/tests/ask_user_tool_test.py b/tests/ask_user_tool_test.py
index 1e860c619..2b520cdb5 100644
--- a/tests/ask_user_tool_test.py
+++ b/tests/ask_user_tool_test.py
@@ -69,6 +69,36 @@ class AskUserTest(IsolatedAsyncioTestCase):
},
)
+ async def test_question_texts_must_be_unique(self) -> None:
+ """Answers use the question text as their correlation key."""
+ question = {
+ "question": "Which?",
+ "header": "Pick",
+ "options": [
+ {"label": "a", "description": "first"},
+ {"label": "b", "description": "second"},
+ ],
+ }
+ with self.assertRaises(ValidationError):
+ AskUserParams.model_validate({"questions": [question, question]})
+
+ async def test_option_labels_must_be_unique(self) -> None:
+ """A selected label must identify exactly one option."""
+ payload = {
+ "questions": [
+ {
+ "question": "Which?",
+ "header": "Pick",
+ "options": [
+ {"label": "same", "description": "first"},
+ {"label": "same", "description": "second"},
+ ],
+ },
+ ],
+ }
+ with self.assertRaises(ValidationError):
+ AskUserParams.model_validate(payload)
+
async def test_a_result_that_breaks_its_promise_is_refused(self) -> None:
"""The shape is the caller's to keep; prose alone is not enough."""
result = ToolResultBlock(