多智能体协作

This commit is contained in:
董宏凯 committed 2026-05-25 17:48:59 +08:00
1 parent 9a70329db2
commit 525218f9a7
13 files changed
+753 -180

No files matched your search

@@ -6,6 +6,8 @@ from collections.abc import Callable
from hashlib import sha256
from typing import override
from deerflow.tools.builtins.clarification_utils import resolve_allow_multiple
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware
from langchain_core.messages import ToolMessage
@@ -67,7 +69,7 @@ class ClarificationMiddleware(AgentMiddleware[ClarificationMiddlewareState]):
question = args.get("question", "")
clarification_type = args.get("clarification_type", "missing_info")
context = args.get("context")
options = self._normalize_options(args.get("options", []))
options = self._normalize_options(args.get("options", []))
# Type-specific icons
type_icons = {
@@ -95,62 +97,63 @@ class ClarificationMiddleware(AgentMiddleware[ClarificationMiddlewareState]):
# Add options in a cleaner format
if options and len(options) > 0:
message_parts.append("") # blank line for spacing
for i, option in enumerate(options, 1):
label = option.get("label") or option.get("id") or ""
message_parts.append(f" {i}. {label}")
return "\n".join(message_parts)
def _normalize_options(self, raw_options: object) -> list[dict[str, str]]:
"""Normalize model-produced options into a stable UI-friendly shape."""
options = raw_options
# Some models serialize array parameters as JSON strings instead of native arrays.
if isinstance(options, str):
try:
options = json.loads(options)
except (json.JSONDecodeError, TypeError):
options = [options]
if options is None:
values: list[object] = []
elif isinstance(options, list):
values = options
else:
values = [options]
normalized: list[dict[str, str]] = []
for index, value in enumerate(values, 1):
if isinstance(value, dict):
raw_label = value.get("label") or value.get("title") or value.get("name") or value.get("value") or value.get("id")
label = str(raw_label).strip() if raw_label is not None else ""
if not label:
continue
raw_id = value.get("id") or value.get("value") or f"option-{index}"
option = {
"id": str(raw_id).strip() or f"option-{index}",
"label": label,
}
description = value.get("description")
if description is not None and str(description).strip():
option["description"] = str(description).strip()
normalized.append(option)
else:
label = str(value).strip()
if label:
normalized.append({"id": f"option-{index}", "label": label})
return normalized
def _build_payload(self, args: dict) -> dict:
"""Build structured clarification data for rich clients."""
return {
"question": str(args.get("question", "")).strip(),
"clarification_type": args.get("clarification_type", "missing_info"),
"context": args.get("context"),
"options": self._normalize_options(args.get("options", [])),
"allow_custom": True,
}
for i, option in enumerate(options, 1):
label = option.get("label") or option.get("id") or ""
message_parts.append(f" {i}. {label}")
return "\n".join(message_parts)
def _normalize_options(self, raw_options: object) -> list[dict[str, str]]:
"""Normalize model-produced options into a stable UI-friendly shape."""
options = raw_options
# Some models serialize array parameters as JSON strings instead of native arrays.
if isinstance(options, str):
try:
options = json.loads(options)
except (json.JSONDecodeError, TypeError):
options = [options]
if options is None:
values: list[object] = []
elif isinstance(options, list):
values = options
else:
values = [options]
normalized: list[dict[str, str]] = []
for index, value in enumerate(values, 1):
if isinstance(value, dict):
raw_label = value.get("label") or value.get("title") or value.get("name") or value.get("value") or value.get("id")
label = str(raw_label).strip() if raw_label is not None else ""
if not label:
continue
raw_id = value.get("id") or value.get("value") or f"option-{index}"
option = {
"id": str(raw_id).strip() or f"option-{index}",
"label": label,
}
description = value.get("description")
if description is not None and str(description).strip():
option["description"] = str(description).strip()
normalized.append(option)
else:
label = str(value).strip()
if label:
normalized.append({"id": f"option-{index}", "label": label})
return normalized
def _build_payload(self, args: dict) -> dict:
"""Build structured clarification data for rich clients."""
return {
"question": str(args.get("question", "")).strip(),
"clarification_type": args.get("clarification_type", "missing_info"),
"context": args.get("context"),
"options": self._normalize_options(args.get("options", [])),
"allow_custom": True,
"allow_multiple": resolve_allow_multiple(args),
}
def _handle_clarification(self, request: ToolCallRequest) -> Command:
"""Handle clarification request and return command to interrupt execution.
@@ -176,13 +179,13 @@ class ClarificationMiddleware(AgentMiddleware[ClarificationMiddlewareState]):
# Create a ToolMessage with the formatted question
# This will be added to the message history
tool_message = ToolMessage(
id=self._stable_message_id(tool_call_id, formatted_message),
content=formatted_message,
tool_call_id=tool_call_id,
name="ask_clarification",
additional_kwargs={"clarification": self._build_payload(args)},
)
tool_message = ToolMessage(
id=self._stable_message_id(tool_call_id, formatted_message),
content=formatted_message,
tool_call_id=tool_call_id,
name="ask_clarification",
additional_kwargs={"clarification": self._build_payload(args)},
)
# Return a Command that:
# 1. Adds the formatted tool message
@@ -15,6 +15,7 @@ def ask_clarification_tool(
],
context: str | None = None,
options: list[str] | None = None,
allow_multiple: bool | None = None,
) -> str:
"""Ask the user for clarification when you need more information to proceed.
@@ -50,8 +51,9 @@ def ask_clarification_tool(
Best practices:
- One question per ask_clarification call — keep each `question` focused on a single decision.
- Be specific and clear in your question.
- Provide `options` (with concise labels) whenever there is a discrete set of reasonable choices —
this lets the user multi-select in the UI instead of typing free text.
- Provide `options` (with concise labels) whenever there is a discrete set of reasonable choices.
- By default the UI is **single-select** (click an option to send). Pass `allow_multiple=True`
only when the user may legitimately pick several options together (e.g. multiple constraints).
- Don't make assumptions when clarification is needed.
- For risky operations, ALWAYS ask for confirmation.
- After calling this tool (or several in one turn), execution will be interrupted automatically.
@@ -60,7 +62,9 @@ def ask_clarification_tool(
question: The clarification question to ask the user. Focused on a single decision; 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; the UI supports multi-select.
options: Optional list of choices. Present clear options for the user to choose from.
allow_multiple: When True, the UI allows multi-select plus a submit button. When False or
omitted, the UI is single-select and sends immediately on click (default).
"""
# This is a placeholder implementation
# The actual logic is handled by ClarificationMiddleware which intercepts this tool call
@@ -0,0 +1,27 @@
"""Shared helpers for ask_clarification option selection mode."""
from __future__ import annotations
def coerce_bool(value: object | None, *, default: bool) -> bool:
"""Parse model/tool args that may arrive as bool, number, or string."""
if value is None:
return default
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return bool(value)
if isinstance(value, str):
lowered = value.strip().lower()
if lowered in ("true", "1", "yes", "y", "on"):
return True
if lowered in ("false", "0", "no", "n", "off"):
return False
return bool(value)
def resolve_allow_multiple(args: dict) -> bool:
"""Return True only when the model explicitly requests multi-select."""
if "allow_multiple" in args and args["allow_multiple"] is not None:
return coerce_bool(args["allow_multiple"], default=False)
return False