mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 03:09:49 +08:00
Each capability now owns its own answer-now branch so the early-exit respects the capability's natural output shape: - chat -> synthesize markdown answer (existing behavior) - deep_solve -> skip planning + reasoning, jump to writer - deep_question -> skip ideation, emit full quiz JSON in one structured call - deep_research -> skip rephrase/decompose/research, write report directly - math_animator -> skip analysis/design/summary, KEEP code-gen + render - visualize -> skip analysis/review, emit renderable code in one call The orchestrator no longer rewrites answer_now turns into chat. It now preserves active_capability and only falls back to chat when the originally selected capability is missing from the registry. Shared plumbing lives in deeptutor/capabilities/_answer_now.py (extract gate, trace summary formatter, skip notice, LLM stream wrapper, chunk joiner). Each fast-path preserves the same result envelope so QuizViewer / MathAnimatorViewer / VisualizationViewer render unchanged, and prepends a "Skipped X stage(s)" notice so the user knows it was a best-effort early exit. Frontend: handleAnswerNow no longer overrides snapshot.capability. Tests: rewrote the orchestrator routing tests for the new contract; added tests/capabilities/test_answer_now.py with 28 cases covering the helpers and every per-capability fast-path (including unparseable JSON / invalid render_type / fence-wrapped JSON recovery, and a math_animator test that verifies analysis/design/summary are NOT invoked while code-gen + render ARE). Updated v1.1.1 release notes to reflect the new design. Made-with: Cursor
144 lines
5.2 KiB
Python
144 lines
5.2 KiB
Python
"""
|
|
Chat Orchestrator
|
|
=================
|
|
|
|
Unified entry point that routes user messages to the appropriate capability.
|
|
All consumers (CLI, WebSocket, SDK) call the orchestrator.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
import uuid
|
|
from typing import Any, AsyncIterator
|
|
|
|
from deeptutor.core.context import UnifiedContext
|
|
from deeptutor.core.stream import StreamEvent, StreamEventType
|
|
from deeptutor.core.stream_bus import StreamBus
|
|
from deeptutor.events.event_bus import Event, EventType, get_event_bus
|
|
from deeptutor.runtime.registry.capability_registry import get_capability_registry
|
|
from deeptutor.runtime.registry.tool_registry import get_tool_registry
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class ChatOrchestrator:
|
|
"""
|
|
Routes a ``UnifiedContext`` to the correct capability, manages
|
|
the ``StreamBus`` lifecycle, and publishes completion events.
|
|
"""
|
|
|
|
def __init__(self) -> None:
|
|
self._cap_registry = get_capability_registry()
|
|
self._tool_registry = get_tool_registry()
|
|
|
|
async def handle(self, context: UnifiedContext) -> AsyncIterator[StreamEvent]:
|
|
"""
|
|
Execute a single user turn and yield streaming events.
|
|
|
|
If ``context.active_capability`` is set, the corresponding capability
|
|
handles the turn. Otherwise, the default ``chat`` capability is used.
|
|
"""
|
|
if not context.session_id:
|
|
context.session_id = str(uuid.uuid4())
|
|
|
|
# "Answer now" is a universal escape hatch but the actual fast-path
|
|
# is *capability-specific* (deep_solve jumps to writing, deep_question
|
|
# jumps to generation, math_animator skips analysis/design but still
|
|
# renders, etc.). Each capability inspects ``answer_now_context`` at
|
|
# the top of its own ``run()``; the orchestrator only adds a defensive
|
|
# fallback here: if the requested capability has been removed from
|
|
# the registry but the user is mid-``answer_now``, route to ``chat``
|
|
# so they still get *some* response instead of a hard error.
|
|
cap_name = context.active_capability or "chat"
|
|
capability = self._cap_registry.get(cap_name)
|
|
|
|
is_answer_now = bool(
|
|
isinstance(context.config_overrides, dict)
|
|
and context.config_overrides.get("answer_now_context")
|
|
)
|
|
if capability is None and is_answer_now:
|
|
fallback = self._cap_registry.get("chat")
|
|
if fallback is not None:
|
|
logger.info(
|
|
"Capability %s missing for answer_now; falling back to chat.",
|
|
cap_name,
|
|
)
|
|
cap_name = "chat"
|
|
capability = fallback
|
|
|
|
if capability is None:
|
|
bus = StreamBus()
|
|
await bus.error(
|
|
f"Unknown capability: {cap_name}. "
|
|
f"Available: {self._cap_registry.list_capabilities()}",
|
|
source="orchestrator",
|
|
)
|
|
await bus.close()
|
|
async for event in bus.subscribe():
|
|
yield event
|
|
return
|
|
|
|
yield StreamEvent(
|
|
type=StreamEventType.SESSION,
|
|
source="orchestrator",
|
|
metadata={
|
|
"session_id": context.session_id,
|
|
"turn_id": str(context.metadata.get("turn_id", "")),
|
|
},
|
|
)
|
|
|
|
bus = StreamBus()
|
|
|
|
async def _run() -> None:
|
|
try:
|
|
await capability.run(context, bus)
|
|
except Exception as exc:
|
|
logger.error("Capability %s failed: %s", cap_name, exc, exc_info=True)
|
|
await bus.error(str(exc), source=cap_name)
|
|
finally:
|
|
await bus.emit(StreamEvent(type=StreamEventType.DONE, source=cap_name))
|
|
await bus.close()
|
|
|
|
stream = bus.subscribe()
|
|
task = asyncio.create_task(_run())
|
|
|
|
async for event in stream:
|
|
yield event
|
|
|
|
await task
|
|
await self._publish_completion(context, cap_name)
|
|
|
|
async def _publish_completion(self, context: UnifiedContext, cap_name: str) -> None:
|
|
"""Publish CAPABILITY_COMPLETE to the global EventBus."""
|
|
try:
|
|
bus = get_event_bus()
|
|
await bus.publish(
|
|
Event(
|
|
type=EventType.CAPABILITY_COMPLETE,
|
|
task_id=str(context.metadata.get("turn_id") or context.session_id),
|
|
user_input=context.user_message,
|
|
agent_output="",
|
|
metadata={
|
|
"capability": cap_name,
|
|
"session_id": context.session_id,
|
|
"turn_id": str(context.metadata.get("turn_id", "")),
|
|
},
|
|
)
|
|
)
|
|
except Exception:
|
|
logger.debug("EventBus publish failed (may not be running)", exc_info=True)
|
|
|
|
def list_tools(self) -> list[str]:
|
|
return self._tool_registry.list_tools()
|
|
|
|
def list_capabilities(self) -> list[str]:
|
|
return self._cap_registry.list_capabilities()
|
|
|
|
def get_capability_manifests(self) -> list[dict[str, Any]]:
|
|
return self._cap_registry.get_manifests()
|
|
|
|
def get_tool_schemas(self, names: list[str] | None = None) -> list[dict[str, Any]]:
|
|
return self._tool_registry.build_openai_schemas(names)
|