Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(backend/copilot): support multiple questions in ask_question tool

Zamil Majdya0efbbba9058
diff --git a/autogpt_platform/backend/backend/copilot/tools/ask_question.py b/autogpt_platform/backend/backend/copilot/tools/ask_question.py
index cf0226533e..181a77b22c 100644
--- a/autogpt_platform/backend/backend/copilot/tools/ask_question.py
+++ b/autogpt_platform/backend/backend/copilot/tools/ask_question.py
@@ -1,4 +1,4 @@
-"""AskQuestionTool - Ask the user a clarifying question before proceeding."""
+"""AskQuestionTool - Ask the user one or more clarifying questions."""
from typing import Any
@@ -9,12 +9,19 @@ from .models import ClarificationNeededResponse, ClarifyingQuestion, ToolRespons
class AskQuestionTool(BaseTool):
- """Ask the user a clarifying question and wait for their answer.
+ """Ask the user one or more clarifying questions and wait for answers.
Use this tool when the user's request is ambiguous and you need more
information before proceeding. Call find_block or other discovery tools
- first to ground your question in real platform options, then call this
- tool with a concrete question listing those options.
+ first to ground your questions in real platform options, then call this
+ tool with concrete questions listing those options.
+
+ Supports two calling conventions (backward-compatible):
+ 1. Single question: ``question="Which channel?"``
+ 2. Multiple questions: ``questions=[{...}, {...}]``
+
+ When *questions* (plural) is provided, the *question*, *options*, and
+ *keyword* top-level parameters are ignored.
"""
@property
@@ -24,9 +31,10 @@ class AskQuestionTool(BaseTool):
@property
def description(self) -> str:
return (
- "Ask the user a clarifying question. Use when the request is "
- "ambiguous and you need to confirm intent, choose between options, "
- "or gather missing details before proceeding."
+ "Ask the user one or more clarifying questions. Use when the "
+ "request is ambiguous and you need to confirm intent, choose "
+ "between options, or gather missing details before proceeding. "
+ "Pass a single question via 'question' or multiple via 'questions'."
)
@property
@@ -37,30 +45,88 @@ class AskQuestionTool(BaseTool):
"question": {
"type": "string",
"description": (
- "The concrete question to ask the user. Should list "
- "real options when applicable."
+ "A single concrete question to ask the user. "
+ "Ignored when 'questions' is provided."
),
},
"options": {
"type": "array",
"items": {"type": "string"},
"description": (
- "Options for the user to choose from "
- "(e.g. ['Email', 'Slack', 'Google Docs'])."
+ "Options for the single question "
+ "(e.g. ['Email', 'Slack', 'Google Docs']). "
+ "Ignored when 'questions' is provided."
),
},
"keyword": {
"type": "string",
- "description": "Short label identifying what the question is about.",
+ "description": (
+ "Short label for the single question. "
+ "Ignored when 'questions' is provided."
+ ),
+ },
+ "questions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "question": {
+ "type": "string",
+ "description": "The question text.",
+ },
+ "options": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Options for this question.",
+ },
+ "keyword": {
+ "type": "string",
+ "description": "Short label for this question.",
+ },
+ },
+ "required": ["question"],
+ },
+ "description": (
+ "Ask multiple questions at once. Each item has "
+ "'question' (required), 'options', and 'keyword'."
+ ),
},
},
- "required": ["question"],
+ "required": [],
+ "anyOf": [
+ {"required": ["question"]},
+ {"required": ["questions"]},
+ ],
}
@property
def requires_auth(self) -> bool:
return False
+ # ------------------------------------------------------------------
+ # Helpers
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _build_question(
+ question: str,
+ options: list[str] | None = None,
+ keyword: str = "",
+ ) -> ClarifyingQuestion:
+ """Build a single ``ClarifyingQuestion`` from raw inputs."""
+ safe_options = (
+ [str(o) for o in options if o] if isinstance(options, list) else []
+ )
+ return ClarifyingQuestion(
+ question=question,
+ keyword=keyword,
+ example=", ".join(safe_options) if safe_options else None,
+ )
+
+ # ------------------------------------------------------------------
+ # Execute
+ # ------------------------------------------------------------------
+
async def _execute(
self,
user_id: str | None,
@@ -68,26 +134,70 @@ class AskQuestionTool(BaseTool):
**kwargs: Any,
) -> ToolResponseBase:
del user_id # unused; required by BaseTool contract
+ session_id = session.session_id if session else None
+
+ raw_questions = kwargs.get("questions")
+ if isinstance(raw_questions, list) and raw_questions:
+ return self._execute_multi(raw_questions, session_id)
+
+ return self._execute_single(kwargs, session_id)
+
+ def _execute_single(
+ self,
+ kwargs: dict[str, Any],
+ session_id: str | None,
+ ) -> ClarificationNeededResponse:
+ """Original single-question path (backward-compatible)."""
question_raw = kwargs.get("question")
if not isinstance(question_raw, str) or not question_raw.strip():
raise ValueError("ask_question requires a non-empty 'question' string")
question = question_raw.strip()
+
raw_options = kwargs.get("options", [])
if not isinstance(raw_options, list):
raw_options = []
options: list[str] = [str(o) for o in raw_options if o]
+
raw_keyword = kwargs.get("keyword", "")
keyword: str = str(raw_keyword) if raw_keyword else ""
- session_id = session.session_id if session else None
- example = ", ".join(options) if options else None
- clarifying_question = ClarifyingQuestion(
- question=question,
- keyword=keyword,
- example=example,
- )
+ clarifying_question = self._build_question(question, options, keyword)
return ClarificationNeededResponse(
message=question,
session_id=session_id,
questions=[clarifying_question],
)
+
+ def _execute_multi(
+ self,
+ raw_questions: list[Any],
+ session_id: str | None,
+ ) -> ClarificationNeededResponse:
+ """New multi-question path."""
+ clarifying_questions: list[ClarifyingQuestion] = []
+ for idx, item in enumerate(raw_questions):
+ if not isinstance(item, dict):
+ continue
+ q_text = item.get("question")
+ if not isinstance(q_text, str) or not q_text.strip():
+ continue
+ keyword = str(item.get("keyword", "")) or f"question-{idx}"
+ clarifying_questions.append(
+ self._build_question(
+ question=q_text.strip(),
+ options=item.get("options"),
+ keyword=keyword,
+ )
+ )
+
+ if not clarifying_questions:
+ raise ValueError(
+ "ask_question requires at least one valid question in 'questions'"
+ )
+
+ message = clarifying_questions[0].question
+ return ClarificationNeededResponse(
+ message=message,
+ session_id=session_id,
+ questions=clarifying_questions,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/ask_question_test.py b/autogpt_platform/backend/backend/copilot/tools/ask_question_test.py
index 607d50e872..b6e1c9bebc 100644
--- a/autogpt_platform/backend/backend/copilot/tools/ask_question_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/ask_question_test.py
@@ -17,6 +17,9 @@ def session() -> ChatSession:
return ChatSession.new(user_id="test-user", dry_run=False)
+# ── Single-question (backward-compatible) ────────────────────────────
+
+
@pytest.mark.asyncio
async def test_execute_with_options(tool: AskQuestionTool, session: ChatSession):
result = await tool._execute(
@@ -97,3 +100,121 @@ async def test_execute_coerces_invalid_options(
assert isinstance(result, ClarificationNeededResponse)
q = result.questions[0]
assert q.example is None
+
+
+# ── Multi-question ───────────────────────────────────────────────────
+
+
+async def test_execute_multiple_questions(tool: AskQuestionTool, session: ChatSession):
+ result = await tool._execute(
+ user_id=None,
+ session=session,
+ questions=[
+ {
+ "question": "Which channel?",
+ "options": ["Email", "Slack"],
+ "keyword": "channel",
+ },
+ {
+ "question": "How often?",
+ "options": ["Daily", "Weekly"],
+ "keyword": "frequency",
+ },
+ {
+ "question": "Any extra notes?",
+ },
+ ],
+ )
+
+ assert isinstance(result, ClarificationNeededResponse)
+ assert len(result.questions) == 3
+ assert result.message == "Which channel?"
+
+ q0 = result.questions[0]
+ assert q0.question == "Which channel?"
+ assert q0.keyword == "channel"
+ assert q0.example == "Email, Slack"
+
+ q1 = result.questions[1]
+ assert q1.question == "How often?"
+ assert q1.keyword == "frequency"
+ assert q1.example == "Daily, Weekly"
+
+ q2 = result.questions[2]
+ assert q2.question == "Any extra notes?"
+ assert q2.keyword == "question-2"
+ assert q2.example is None
+
+
+async def test_execute_multiple_questions_skips_invalid_items(
+ tool: AskQuestionTool, session: ChatSession
+):
+ """Non-dict items and items without a question are silently skipped."""
+ result = await tool._execute(
+ user_id=None,
+ session=session,
+ questions=[
+ "not-a-dict",
+ {"keyword": "missing-question"},
+ {"question": ""},
+ {"question": " Valid question ", "keyword": "valid"},
+ ],
+ )
+
+ assert isinstance(result, ClarificationNeededResponse)
+ assert len(result.questions) == 1
+ assert result.questions[0].question == "Valid question"
+ assert result.questions[0].keyword == "valid"
+
+
+async def test_execute_multiple_questions_rejects_all_invalid(
+ tool: AskQuestionTool, session: ChatSession
+):
+ """If every item in questions is invalid, raise ValueError."""
+ with pytest.raises(ValueError, match="at least one valid question"):
+ await tool._execute(
+ user_id=None,
+ session=session,
+ questions=[{"keyword": "no-question"}, "bad"],
+ )
+
+
+async def test_execute_multiple_questions_ignores_single_params(
+ tool: AskQuestionTool, session: ChatSession
+):
+ """When 'questions' is provided, 'question'/'options'/'keyword' are ignored."""
+ result = await tool._execute(
+ user_id=None,
+ session=session,
+ question="Should be ignored",
+ options=["A", "B"],
+ keyword="ignored",
+ questions=[
+ {"question": "Real question?", "keyword": "real"},
+ ],
+ )
+
+ assert len(result.questions) == 1
+ assert result.questions[0].question == "Real question?"
+ assert result.questions[0].keyword == "real"
+
+
+async def test_execute_empty_questions_falls_back_to_single(
+ tool: AskQuestionTool, session: ChatSession
+):
+ """An empty 'questions' list falls back to the single-question path."""
+ result = await tool._execute(
+ user_id=None,
+ session=session,
+ question="Fallback question?",
+ questions=[],
+ )
+
+ assert isinstance(result, ClarificationNeededResponse)
+ assert len(result.questions) == 1
+ assert result.questions[0].question == "Fallback question?"