问答模式智能路由智能体初始版

This commit is contained in:
许海洋 committed 2026-05-21 13:50:15 +08:00
1 parent 1b0060ded7
commit 7ee89405f5
11 files changed
+263 -46

No files matched your search

@@ -1,6 +1,8 @@
from .clarification_tool import ask_clarification_tool
from .fast_chat_tool import fast_chat_tool, fast_llm_answer
from .memory_tool import memory_tool
from .present_file_tool import present_file_tool
from .router_quality_tool import router_quality_check
from .scheduled_task_tool import scheduled_task_tool
from .setup_agent_tool import setup_agent
from .task_tool import task_tool
@@ -16,4 +18,5 @@ __all__ = [
"task_tool",
"fast_chat_tool",
"fast_llm_answer",
"router_quality_check",
]
@@ -92,18 +92,37 @@ async def fast_chat_tool(
req_url = f"{backend_url}/api/v1/new_chat"
# 从 context 获取 newChatToken
new_chat_token = _get_runtime_value(runtime, "newChatToken")
logger.info(
"fast_chat_tool request: thread_id=%s, prompt=%s, search_space_id=%s, model_name=%s, has_token=%s",
thread_id,
prompt[:100] if prompt else None,
effective_search_space_id,
effective_model_name,
bool(new_chat_token),
)
def _make_request():
data = json.dumps(req_body).encode("utf-8")
headers = {"Content-Type": "application/json"}
# 添加认证 token 到请求头
if new_chat_token:
headers["Authorization"] = f"Bearer {new_chat_token}"
req = urllib.request.Request(
req_url,
data=data,
headers={"Content-Type": "application/json"},
headers=headers,
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as response:
return response.read().decode("utf-8")
result = await asyncio.to_thread(_make_request)
logger.info("fast_chat_tool response: thread_id=%s, result=%s", thread_id, result[:500] if result else None)
return result
except urllib.error.HTTPError as exc:
@@ -37,6 +37,14 @@ def _get_runtime_app_config(runtime: Any) -> "AppConfig | None":
return None
def _get_runtime_stream_bridge(runtime: Any) -> Any:
"""Get StreamBridge from runtime context for publishing events to SSE."""
context = getattr(runtime, "context", None)
if isinstance(context, dict):
return context.get("stream_bridge")
return None
def _merge_skill_allowlists(parent: list[str] | None, child: list[str] | None) -> list[str] | None:
"""Return the effective subagent skill allowlist under the parent policy."""
if parent is None:
@@ -123,6 +131,8 @@ async def task_tool(
parent_model = None
trace_id = None
metadata: dict = {}
stream_bridge = None
run_id = None
if runtime is not None:
sandbox_state = runtime.state.get("sandbox")
@@ -138,6 +148,10 @@ async def task_tool(
# Get or generate trace_id for distributed tracing
trace_id = metadata.get("trace_id") or str(uuid.uuid4())[:8]
# Get StreamBridge from runtime context for SSE event publishing
stream_bridge = _get_runtime_stream_bridge(runtime)
run_id = runtime.context.get("run_id") if runtime.context else None
parent_available_skills = metadata.get("available_skills")
if parent_available_skills is not None:
overrides["skills"] = _merge_skill_allowlists(list(parent_available_skills), config.skills)
@@ -188,14 +202,22 @@ async def task_tool(
poll_count = 0
last_status = None
last_message_count = 0 # Track how many AI messages we've already sent
# Polling timeout: execution timeout + 60s buffer, checked every 5s
max_poll_count = (config.timeout_seconds + 60) // 5
# Polling timeout: execution timeout + 60s buffer, checked every 0.5s for near real-time streaming
max_poll_count = (config.timeout_seconds + 60) // 0.5
logger.info(f"[trace={trace_id}] Started background task {task_id} (subagent={subagent_type}, timeout={config.timeout_seconds}s, polling_limit={max_poll_count} polls)")
writer = get_stream_writer()
# Send Task Started message'
writer({"type": "task_started", "task_id": task_id, "description": description})
# Use StreamBridge for SSE events if available, otherwise fall back to StreamWriter
async def publish_event(event_type: str, data: Any) -> None:
"""Publish event to SSE stream via bridge or writer."""
if stream_bridge is not None and run_id is not None:
await stream_bridge.publish(run_id, event_type, data)
else:
writer = get_stream_writer()
writer({"type": event_type, **data})
# Send Task Started message
await publish_event("task_started", {"task_id": task_id, "description": description})
try:
while True:
@@ -203,7 +225,7 @@ async def task_tool(
if result is None:
logger.error(f"[trace={trace_id}] Task {task_id} not found in background tasks")
writer({"type": "task_failed", "task_id": task_id, "error": "Task disappeared from background tasks"})
await publish_event("task_failed", {"task_id": task_id, "error": "Task disappeared from background tasks"})
cleanup_background_task(task_id)
return f"Error: Task {task_id} disappeared from background tasks"
@@ -219,46 +241,43 @@ async def task_tool(
# Send task_running event for each new message
for i in range(last_message_count, current_message_count):
message = ai_messages[i]
writer(
{
"type": "task_running",
"task_id": task_id,
"message": message,
"message_index": i + 1, # 1-based index for display
"total_messages": current_message_count,
}
)
await publish_event("task_running", {
"task_id": task_id,
"message": message,
"message_index": i + 1, # 1-based index for display
"total_messages": current_message_count,
})
logger.info(f"[trace={trace_id}] Task {task_id} sent message #{i + 1}/{current_message_count}")
last_message_count = current_message_count
# Check if task completed, failed, or timed out
if result.status == SubagentStatus.COMPLETED:
writer({"type": "task_completed", "task_id": task_id, "result": result.result})
await publish_event("task_completed", {"task_id": task_id, "result": result.result})
logger.info(f"[trace={trace_id}] Task {task_id} completed after {poll_count} polls")
cleanup_background_task(task_id)
return f"Task Succeeded. Result: {result.result}"
elif result.status == SubagentStatus.FAILED:
writer({"type": "task_failed", "task_id": task_id, "error": result.error})
await publish_event("task_failed", {"task_id": task_id, "error": result.error})
logger.error(f"[trace={trace_id}] Task {task_id} failed: {result.error}")
cleanup_background_task(task_id)
return f"Task failed. Error: {result.error}"
elif result.status == SubagentStatus.CANCELLED:
writer({"type": "task_cancelled", "task_id": task_id, "error": result.error})
await publish_event("task_cancelled", {"task_id": task_id, "error": result.error})
logger.info(f"[trace={trace_id}] Task {task_id} cancelled: {result.error}")
cleanup_background_task(task_id)
return "Task cancelled by user."
elif result.status == SubagentStatus.TIMED_OUT:
writer({"type": "task_timed_out", "task_id": task_id, "error": result.error})
await publish_event("task_timed_out", {"task_id": task_id, "error": result.error})
logger.warning(f"[trace={trace_id}] Task {task_id} timed out: {result.error}")
cleanup_background_task(task_id)
return f"Task timed out. Error: {result.error}"
# Still running, wait before next poll
await asyncio.sleep(5)
# Still running, wait before next poll (reduced from 5s to 0.5s for near real-time streaming)
await asyncio.sleep(0.5)
poll_count += 1
# Polling timeout as a safety net (in case thread pool timeout doesn't work)
# Set to execution timeout + 60s buffer, in 5s poll intervals
# Set to execution timeout + 60s buffer, in 0.5s poll intervals for near real-time streaming
# This catches edge cases where the background task gets stuck
# Note: We don't call cleanup_background_task here because the task may
# still be running in the background. The cleanup will happen when the
@@ -292,7 +311,7 @@ async def task_tool(
logger.warning(f"[trace={trace_id}] Deferred cleanup for task {task_id} timed out after {cleanup_poll_count} polls")
return
await asyncio.sleep(5)
await asyncio.sleep(0.5)
cleanup_poll_count += 1
def log_cleanup_failure(cleanup_task: asyncio.Task[None]) -> None:
@@ -6,7 +6,7 @@ from deerflow.config import get_app_config
from deerflow.config.app_config import AppConfig
from deerflow.reflection import resolve_variable
from deerflow.sandbox.security import is_host_bash_allowed
from deerflow.tools.builtins import ask_clarification_tool, memory_tool, present_file_tool, scheduled_task_tool, task_tool, view_image_tool
from deerflow.tools.builtins import ask_clarification_tool, fast_chat_tool, fast_llm_answer, memory_tool, present_file_tool, router_quality_check, scheduled_task_tool, task_tool, view_image_tool
from deerflow.tools.builtins.tool_search import reset_deferred_registry
logger = logging.getLogger(__name__)
@@ -16,6 +16,7 @@ BUILTIN_TOOLS = [
ask_clarification_tool,
fast_chat_tool,
fast_llm_answer,
router_quality_check,
]
SUBAGENT_TOOLS = [