mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-07-29 09:26:00 +00:00
* feat(clarification): structured form fields for human-input cards Add a request-side v2 `form` mode to the ask_clarification protocol so business flows (e.g. expense reimbursement) can collect several values in one card instead of sequential free-text questions: - `ask_clarification` gains a restricted `fields` parameter (text / textarea / number / select / multi_select / checkbox / date) - ClarificationMiddleware validates and normalizes fields explicitly (whitelisted types, unknown -> text, select-likes without options -> text, duplicate/invalid entries dropped, all-invalid falls back to the legacy modes) since the middleware short-circuits before tool execution; the plain-text fallback lists fields for IM channels - Form payloads carry `version: 2` so older frontends degrade to the text fallback; replies stay on the v1 response protocol — the card submits a readable summary as `response_kind: "text"`, so journal persistence and answered-card recovery are unchanged - Frontend renders typed field controls with required-field validation and compact multi-select chips Part of #4400 (scope narrowed per maintainer feedback: request-side only, no new response kinds, no top-level multi_choice). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(clarification): harden form protocol per review feedback Address the five review points on #4406: - Reject field names colliding with JS Object.prototype members on both sides; frontend reads form values via own-property access only, so `constructor`/`toString`-style names can no longer leak inherited members into required validation or the submitted summary - Close open requests answered through the legacy text fallback: a visible plain human reply (no response metadata) now marks every previously-opened request as answered, so upgrading to a v2-aware frontend cannot leave the composer locked on an already-answered card - Give checkbox fields deterministic boolean semantics: values are seeded to an explicit false ("no" in the summary) and `required` means must-agree/consent; documented in the tool schema - Make middleware field validation atomic: structurally broken entries (bad/duplicate/reserved names, over-cap field/option counts or text lengths) degrade the whole form instead of silently dropping fields; options are trimmed/deduped with blanks removed so the backend never emits payloads the frontend parser rejects - Associate form labels/controls (htmlFor/id), aria-required, aria-invalid, and error descriptions for accessibility Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(clarification): type the fields item schema via TypedDict Replace `fields: list[dict[str, Any]]` with `list[ClarificationFormField]` (a TypedDict with `name` required and the type whitelist as a Literal) so the provider-facing tool schema documents the item shape instead of an opaque object relying on the docstring. Runtime validation is unchanged and stays in ClarificationMiddleware, which intercepts the call before tool execution. Addresses the non-blocking review suggestion on #4406. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(frontend): drop unsupported aria-invalid from multi-select group jsx-a11y: role=group does not support aria-invalid; the error linkage stays via aria-describedby. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(clarification): coerce numeric required flags and normalize fields once - `_normalize_bool` now coerces 1/0 (some providers serialize booleans as integers), so `required: 1` no longer silently flips to optional - `_handle_clarification` normalizes `fields` once and passes the result to both the text fallback and the payload builder Addresses the non-blocking review nits on #4406. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(clarification): harden form protocol per contract review round 2 Backend: - Guard unhashable JSON in the intercept path: `type: []`/`{}` degrades the field to text and `clarification_type: []` coerces to str instead of raising TypeError (which, with return_direct, ended the turn with an error and no card or fallback) - Add a total budget over the serialized normalized fields (16KB UTF-8 bytes): per-item caps alone admitted forms whose IM text fallback exceeded channel delivery limits (Slack 40k chars, Feishu ~30KB card), silently truncating trailing fields; a boundary test proves any accepted form's fallback stays deliverable Frontend: - Submission value now appends a JSON block keyed by stable field names (readable summary alone is delimiter-ambiguous), with a collision regression test - Parser boundary tightened to match backend constraints: empty option values (Radix SelectItem crash), duplicate option ids/values, duplicate field names, and the form<->version-2 binding are rejected - Keep the error node mounted while any field is still invalid so aria-describedby never points at a removed element (happy-dom interaction test) - Required semantics are now accessible: native checkbox control (no HTML required attribute — it would intercept the custom submit path), visually-hidden localized "required" markers next to the aria-hidden asterisks - Legacy-fallback closure narrowed to the latest unanswered request: nothing guarantees a single outstanding clarification across runs, and closing all would silently swallow older decisions; an older request left open becomes the active card again Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(frontend): keep clarification selects controlled --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
93 lines
4.8 KiB
Python
93 lines
4.8 KiB
Python
from typing import Literal, Required, TypedDict
|
|
|
|
from langchain.tools import tool
|
|
|
|
|
|
class ClarificationFormField(TypedDict, total=False):
|
|
"""One form field definition for a structured clarification card.
|
|
|
|
The model-visible schema documents the item shape; runtime validation
|
|
still happens defensively in ``ClarificationMiddleware`` because the
|
|
middleware intercepts the call before tool execution.
|
|
"""
|
|
|
|
name: Required[str]
|
|
label: str
|
|
type: Literal["text", "textarea", "number", "select", "multi_select", "checkbox", "date"]
|
|
required: bool
|
|
options: list[str]
|
|
placeholder: str
|
|
|
|
|
|
@tool("ask_clarification", parse_docstring=True, return_direct=True)
|
|
def ask_clarification_tool(
|
|
question: str,
|
|
clarification_type: Literal[
|
|
"missing_info",
|
|
"ambiguous_requirement",
|
|
"approach_choice",
|
|
"risk_confirmation",
|
|
"suggestion",
|
|
],
|
|
context: str | None = None,
|
|
options: list[str] | None = None,
|
|
fields: list[ClarificationFormField] | None = None,
|
|
) -> str:
|
|
"""Ask the user for clarification when you need more information to proceed.
|
|
|
|
Use this tool when you encounter situations where you cannot proceed without user input:
|
|
|
|
- **Missing information**: Required details not provided (e.g., file paths, URLs, specific requirements)
|
|
- **Ambiguous requirements**: Multiple valid interpretations exist
|
|
- **Approach choices**: Several valid approaches exist and you need user preference
|
|
- **Risky operations**: Destructive actions that need explicit confirmation (e.g., deleting files, modifying production)
|
|
- **Suggestions**: You have a recommendation but want user approval before proceeding
|
|
|
|
The execution will be interrupted and the question will be presented to the user.
|
|
Wait for the user's response before continuing.
|
|
|
|
When to use ask_clarification:
|
|
- You need information that wasn't provided in the user's request
|
|
- The requirement can be interpreted in multiple ways
|
|
- Multiple valid implementation approaches exist
|
|
- You're about to perform a potentially dangerous operation
|
|
- You have a recommendation but need user approval
|
|
|
|
Choosing the interaction shape:
|
|
- One open question -> just `question` (free text input)
|
|
- Pick exactly one option -> `options`
|
|
- Pick several options -> a single `fields` entry of type `multi_select`
|
|
- Collect several values at once (e.g. a set of parameters for one action) ->
|
|
`fields`, which renders a single structured form instead of several
|
|
sequential questions. Prefer one form over asking field-by-field.
|
|
|
|
Best practices:
|
|
- Ask ONE clarification at a time for clarity; a form with several fields
|
|
still counts as one clarification
|
|
- Be specific and clear in your question
|
|
- Don't make assumptions when clarification is needed
|
|
- For risky operations, ALWAYS ask for confirmation
|
|
- If a skill provides a predefined field template, pass it through `fields`
|
|
unchanged instead of redesigning it
|
|
- After calling this tool, execution will be interrupted automatically
|
|
|
|
Args:
|
|
question: The clarification question to ask the user. Be specific and clear.
|
|
clarification_type: The type of clarification needed (missing_info, ambiguous_requirement, approach_choice, risk_confirmation, suggestion).
|
|
context: Optional context explaining why clarification is needed. Helps the user understand the situation.
|
|
options: Optional list of choices (for approach_choice or suggestion types). Present clear options for the user to choose from.
|
|
fields: Optional form field definitions for collecting multiple values in one card; takes precedence over `options`.
|
|
Each field is an object with `name` (unique identifier, required; avoid JavaScript prototype names like
|
|
`constructor` or `toString`), `label` (display text, defaults to name), `type` (one of: text, textarea,
|
|
number, select, multi_select, checkbox, date; defaults to text), `required` (boolean, defaults to false),
|
|
`options` (list of strings, required for select/multi_select types), and `placeholder` (optional hint text).
|
|
A `checkbox` field is a boolean that defaults to "no"; set `required` on a checkbox only for
|
|
must-agree/consent semantics (the user has to tick it to submit). Keep forms bounded: at most 16 fields,
|
|
24 options per field, and 200 characters per name/label/option/placeholder — exceeding a limit degrades
|
|
the whole request to a plain-text question.
|
|
"""
|
|
# This is a placeholder implementation
|
|
# The actual logic is handled by ClarificationMiddleware which intercepts this tool call
|
|
# and interrupts execution to present the question to the user
|
|
return "Clarification request processed by middleware"
|