多智能体协作
This commit is contained in:
1 parent
9a70329db2
commit
525218f9a7
13 files changed
+753
-180
No files matched your search
@@ -35,6 +35,7 @@ from app.gateway.routers.multi_agent import (
|
||||
_run_payload,
|
||||
_stream_upstream,
|
||||
)
|
||||
from deerflow.tools.builtins.clarification_utils import resolve_allow_multiple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api/intent", tags=["intent"])
|
||||
@@ -83,9 +84,12 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
through transparently, then appends one status frame:
|
||||
|
||||
{
|
||||
"status": "asking" | "done" | "error",
|
||||
"status": "asking" | "clarification" | "done" | "error",
|
||||
"content": "<final AI text>",
|
||||
"summary": {...} | null // only present when status == "done"
|
||||
"summary": {...} | null, // only when status == "done"
|
||||
// when status == "clarification":
|
||||
"question", "clarification_type", "clarification_context",
|
||||
"options", "allow_custom", "allow_multiple"
|
||||
}
|
||||
"""
|
||||
thread_id = str(payload.get("thread_id") or "").strip()
|
||||
@@ -143,44 +147,10 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
captured = done
|
||||
|
||||
messages = _parse_last_messages(captured)
|
||||
# Find the latest AIMessage with tool_calls (typically
|
||||
# ask_clarification) — falls back to the latest plain
|
||||
# AIMessage when the model produced no tool call.
|
||||
dispatch_msg = _find_dispatch_message(messages)
|
||||
content = _flatten_content(dispatch_msg.get("content", ""))
|
||||
tool_calls = dispatch_msg.get("tool_calls") or []
|
||||
|
||||
# Clarification branch: the agent ended its run by calling
|
||||
# ask_clarification. ClarificationMiddleware intercepts with
|
||||
# Command(goto=END) and stashes the structured question in the
|
||||
# tool_call args, so the AIMessage `content` is only the
|
||||
# preamble ("下面我用几个问题确认:") and stops there. We splice
|
||||
# the question back into the user-facing text so the frontend
|
||||
# actually shows what the agent wants to ask.
|
||||
clarification_call = next(
|
||||
(tc for tc in tool_calls if (tc.get("name") or "").lower() == "ask_clarification"),
|
||||
None,
|
||||
)
|
||||
if clarification_call is not None:
|
||||
cargs = clarification_call.get("args") or {}
|
||||
question = str(cargs.get("question") or "").strip()
|
||||
follow_up = _find_trailing_ai_text(messages, exclude_text=content)
|
||||
# Build a single content string the frontend can render
|
||||
# as-is: preamble (if any) + the actual question.
|
||||
parts: list[str] = []
|
||||
if content.strip():
|
||||
parts.append(content.strip())
|
||||
if follow_up and follow_up != question:
|
||||
parts.append(follow_up)
|
||||
if question:
|
||||
parts.append(question)
|
||||
content = "\n\n".join(parts) if parts else content
|
||||
|
||||
# Scan ALL AI messages for the [INTENT_READY] marker, not just
|
||||
# dispatch_msg.content. The model often emits the summary in an
|
||||
# earlier AI message and then keeps yapping (or doing extra
|
||||
# tool calls) — the marker is the source of truth, wherever it
|
||||
# appears in the run.
|
||||
# [INTENT_READY] wins over ask_clarification: the model may emit
|
||||
# the handoff marker in an earlier AI message while the latest
|
||||
# dispatch still carries a stale clarification tool call.
|
||||
summary: dict[str, Any] | None = None
|
||||
ready_text: str = ""
|
||||
for msg in reversed(messages):
|
||||
@@ -198,17 +168,49 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
summary = None
|
||||
ready_text = msg_text
|
||||
break
|
||||
# When the marker was found in an earlier message, surface that
|
||||
# message's text (which contains the user-facing 📋 汇总 + JSON)
|
||||
# instead of the final filler AI text like "好的,收到".
|
||||
if summary and ready_text:
|
||||
content = ready_text
|
||||
final_frame = {
|
||||
"status": "done",
|
||||
"content": ready_text,
|
||||
"summary": summary,
|
||||
}
|
||||
yield f"data: {json.dumps(final_frame, ensure_ascii=False)}\n\n"
|
||||
return
|
||||
|
||||
# Find the latest AIMessage with tool_calls (typically
|
||||
# ask_clarification) — falls back to the latest plain
|
||||
# AIMessage when the model produced no tool call.
|
||||
dispatch_msg = _find_dispatch_message(messages)
|
||||
content = _flatten_content(dispatch_msg.get("content", ""))
|
||||
tool_calls = dispatch_msg.get("tool_calls") or []
|
||||
|
||||
clarification_call = next(
|
||||
(tc for tc in tool_calls if (tc.get("name") or "").lower() == "ask_clarification"),
|
||||
None,
|
||||
)
|
||||
if clarification_call is not None:
|
||||
cargs = clarification_call.get("args") or {}
|
||||
question = str(cargs.get("question") or "").strip()
|
||||
follow_up = _find_trailing_ai_text(messages, exclude_text=content)
|
||||
display_content = follow_up or content or question
|
||||
final_frame: dict[str, Any] = {
|
||||
"status": "clarification",
|
||||
"content": display_content,
|
||||
"question": question,
|
||||
"clarification_type": str(cargs.get("clarification_type") or ""),
|
||||
"clarification_context": str(cargs.get("context") or ""),
|
||||
"options": cargs.get("options") or [],
|
||||
"allow_custom": bool(cargs.get("allow_custom", True)),
|
||||
"allow_multiple": resolve_allow_multiple(cargs),
|
||||
"summary": None,
|
||||
}
|
||||
yield f"data: {json.dumps(final_frame, ensure_ascii=False)}\n\n"
|
||||
return
|
||||
|
||||
status_value = "done" if summary else "asking"
|
||||
final_frame: dict[str, Any] = {
|
||||
"status": status_value,
|
||||
"status": "asking",
|
||||
"content": content,
|
||||
"summary": summary,
|
||||
"summary": None,
|
||||
}
|
||||
yield f"data: {json.dumps(final_frame, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import time
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
import httpx
|
||||
from deerflow.tools.builtins.clarification_utils import resolve_allow_multiple
|
||||
from fastapi import APIRouter, Body, HTTPException, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
@@ -616,6 +617,7 @@ async def _leader_run(
|
||||
"clarification_context": str(cargs.get("context") or ""),
|
||||
"options": cargs.get("options") or [],
|
||||
"allow_custom": bool(cargs.get("allow_custom", True)),
|
||||
"allow_multiple": resolve_allow_multiple(cargs),
|
||||
"agent_name": agent_name,
|
||||
}
|
||||
return
|
||||
|
||||
+67
-64
@@ -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
|
||||
|
||||
+7
-3
@@ -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
|
||||
|
||||
+27
@@ -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
|
||||
Reference in new issue
Block a user