mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 18:46:34 +08:00
Merge pull request #1068 from evan188199-tech
# Conflicts: # deeptutor/services/session/turn_runtime.py
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
"""Pre-execution capability routing for explicit turn requests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilityRoute:
|
||||
requested_capability: str
|
||||
capability: str
|
||||
confidence: float
|
||||
strategy: str
|
||||
reason: str
|
||||
|
||||
def as_metadata(self) -> dict[str, Any]:
|
||||
return {
|
||||
"requested_capability": self.requested_capability,
|
||||
"capability": self.capability,
|
||||
"confidence": self.confidence,
|
||||
"strategy": self.strategy,
|
||||
"reason": self.reason,
|
||||
"auto_routed": self.auto_routed,
|
||||
}
|
||||
|
||||
@property
|
||||
def auto_routed(self) -> bool:
|
||||
return self.capability != self.requested_capability
|
||||
|
||||
|
||||
# Deliberately narrow: an ambiguous mention of practice, a quiz, or an exam
|
||||
# stays in chat. Only a request to generate a reusable question set routes to
|
||||
# deep_question. Interactive requests such as "quiz me" stay in chat because
|
||||
# deep_question is a static generator, not a turn-by-turn quiz runner.
|
||||
_QUIZ_PATTERNS = (
|
||||
re.compile(
|
||||
r"\b(?:generate|create|make|write|give me|produce)\b[^.!?\n]{0,80}"
|
||||
r"\bquiz questions?\b",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
re.compile(r"(?:给我出|帮我出|生成|创建)[^.!?\n]{0,20}(?:测验|考试|测试)题?"),
|
||||
)
|
||||
|
||||
_QUIZ_REASON = "The user explicitly asked to generate a quiz question set."
|
||||
|
||||
|
||||
def route_explicit_quiz_request(
|
||||
content: Any,
|
||||
requested_capability: Any,
|
||||
*,
|
||||
enabled: bool,
|
||||
) -> CapabilityRoute | None:
|
||||
"""Return a rule-based route before turn creation, or None to keep chat.
|
||||
|
||||
The requested capability is retained even when routing does not occur so
|
||||
observability can distinguish an explicit chat selection from a missing one.
|
||||
"""
|
||||
requested = str(requested_capability or "chat")
|
||||
if not enabled or requested != "chat":
|
||||
return None
|
||||
|
||||
message = str(content or "").strip()
|
||||
if not message or not any(pattern.search(message) for pattern in _QUIZ_PATTERNS):
|
||||
return None
|
||||
|
||||
return CapabilityRoute(
|
||||
requested_capability=requested,
|
||||
capability="deep_question",
|
||||
confidence=0.96,
|
||||
strategy="rule",
|
||||
reason=_QUIZ_REASON,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["CapabilityRoute", "route_explicit_quiz_request"]
|
||||
@@ -33,6 +33,9 @@ DEFAULT_SYSTEM_SETTINGS: dict[str, Any] = {
|
||||
# deployment shapes; a stronger backend (runner sidecar / bwrap) still
|
||||
# takes precedence when available. Set false to disable host-side exec.
|
||||
"sandbox_allow_subprocess": True,
|
||||
# Conservative chat -> deep_question routing. Explicit requests only, and
|
||||
# callers can still pass config.auto_route=false for a single turn.
|
||||
"capability_routing_enabled": False,
|
||||
# Chat attachment policy. Size caps gate what the composer accepts and
|
||||
# what the turn runtime / partner upload endpoints extract; the char
|
||||
# budgets bound how much extracted text is inlined into the LLM context
|
||||
@@ -756,6 +759,8 @@ class RuntimeSettingsService:
|
||||
payload["chat_attachment_dir"] = value
|
||||
if value := self._process_env_value("DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS"):
|
||||
payload["sandbox_allow_subprocess"] = value
|
||||
if value := self._process_env_value("DEEPTUTOR_CAPABILITY_ROUTING_ENABLED"):
|
||||
payload["capability_routing_enabled"] = value
|
||||
if value := self._process_env_value("CHAT_ATTACHMENT_MAX_FILE_MB"):
|
||||
payload["chat_attachment_max_file_mb"] = value
|
||||
if value := self._process_env_value("CHAT_ATTACHMENT_MAX_TOTAL_MB"):
|
||||
@@ -1116,6 +1121,9 @@ class RuntimeSettingsService:
|
||||
"sandbox_allow_subprocess": _coerce_bool(
|
||||
settings.get("sandbox_allow_subprocess"), True
|
||||
),
|
||||
"capability_routing_enabled": _coerce_bool(
|
||||
settings.get("capability_routing_enabled"), False
|
||||
),
|
||||
"chat_attachment_max_file_mb": max_file_mb,
|
||||
"chat_attachment_max_total_mb": max_total_mb,
|
||||
"chat_attachment_max_chars_per_doc": _coerce_clamped_int(
|
||||
|
||||
@@ -15,6 +15,7 @@ import re
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
from deeptutor.core.stream import StreamEvent, StreamEventType
|
||||
from deeptutor.runtime.capability_routing import route_explicit_quiz_request
|
||||
from deeptutor.services.llm.utils import clean_thinking_tags
|
||||
from deeptutor.services.path_service import get_path_service
|
||||
from deeptutor.services.session.artifact_attachments import (
|
||||
@@ -51,6 +52,18 @@ def _should_capture_assistant_content(event: StreamEvent) -> bool:
|
||||
return metadata.get("call_kind") in _ANSWER_CONTENT_CALL_KINDS
|
||||
|
||||
|
||||
def _coerce_bool(value: Any, default: bool) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {"true", "1", "yes", "on"}:
|
||||
return True
|
||||
if normalized in {"false", "0", "no", "off"}:
|
||||
return False
|
||||
return default
|
||||
|
||||
|
||||
def _resolve_turn_outcome(
|
||||
assistant_events: Sequence[dict[str, Any]],
|
||||
done_event: StreamEvent | None,
|
||||
@@ -612,6 +625,9 @@ def _request_snapshot_metadata(
|
||||
snapshot["attachments"] = attachments
|
||||
if config:
|
||||
snapshot["config"] = dict(config)
|
||||
capability_route = payload.get("capability_route")
|
||||
if isinstance(capability_route, dict):
|
||||
snapshot["capabilityRoute"] = dict(capability_route)
|
||||
if notebook_references:
|
||||
snapshot["notebookReferences"] = notebook_references
|
||||
if history_references:
|
||||
@@ -1443,6 +1459,14 @@ class TurnRuntimeManager:
|
||||
|
||||
payload = {**payload, "language": get_response_language(default="en")}
|
||||
raw_config = dict(payload.get("config", {}) or {})
|
||||
per_turn_auto_route = raw_config.get("auto_route")
|
||||
routing_enabled = _coerce_bool(per_turn_auto_route, False)
|
||||
if per_turn_auto_route is not False:
|
||||
from deeptutor.services.config.runtime_settings import load_system_settings
|
||||
|
||||
routing_enabled = routing_enabled or _coerce_bool(
|
||||
load_system_settings().get("capability_routing_enabled"), False
|
||||
)
|
||||
runtime_only_keys = (
|
||||
"_persist_user_message",
|
||||
"_regenerate",
|
||||
@@ -1456,6 +1480,8 @@ class TurnRuntimeManager:
|
||||
# key — stripped before validation, merged back into the turn config
|
||||
# and read by the subagent capability from context.config_overrides.
|
||||
"subagent_consult_budget",
|
||||
# Per-turn routing escape hatch; never part of a capability schema.
|
||||
"auto_route",
|
||||
)
|
||||
runtime_only_config = {
|
||||
key: raw_config.pop(key) for key in runtime_only_keys if key in raw_config
|
||||
@@ -1493,7 +1519,17 @@ class TurnRuntimeManager:
|
||||
preferences=preferences,
|
||||
)
|
||||
|
||||
capability = str(payload.get("capability") or "chat")
|
||||
requested_capability = str(payload.get("capability") or "chat")
|
||||
capability_route = route_explicit_quiz_request(
|
||||
payload.get("content"),
|
||||
requested_capability,
|
||||
enabled=routing_enabled,
|
||||
)
|
||||
capability = (
|
||||
capability_route.capability
|
||||
if capability_route is not None
|
||||
else requested_capability
|
||||
)
|
||||
workspace_mode_explicit = "workspace_mode" in payload
|
||||
workspace_mode = _workspace_mode(
|
||||
payload.get("workspace_mode")
|
||||
@@ -1504,7 +1540,13 @@ class TurnRuntimeManager:
|
||||
try:
|
||||
from deeptutor.runtime.request_contracts import validate_capability_config
|
||||
|
||||
validated_public_config = validate_capability_config(capability, raw_config)
|
||||
# A routed capability owns a different schema. Chat-only options
|
||||
# must not be smuggled into the generator; the user request itself
|
||||
# carries the desired topic/count.
|
||||
validated_public_config = validate_capability_config(
|
||||
capability,
|
||||
{} if capability_route is not None else raw_config,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise RuntimeError(str(exc)) from exc
|
||||
payload = {
|
||||
@@ -1521,6 +1563,10 @@ class TurnRuntimeManager:
|
||||
if bound_course is not None
|
||||
else ""
|
||||
),
|
||||
"requested_capability": requested_capability,
|
||||
"capability_route": (
|
||||
capability_route.as_metadata() if capability_route is not None else None
|
||||
),
|
||||
"config": {**validated_public_config, **runtime_only_config},
|
||||
}
|
||||
reading_workspace_id = _reading_workspace_id(payload.get("reading_workspace_id"))
|
||||
@@ -1681,10 +1727,26 @@ class TurnRuntimeManager:
|
||||
**payload,
|
||||
"tools": [t for t in (payload.get("tools") or []) if t in allowed_tools],
|
||||
}
|
||||
if capability_route is not None and capability_route.auto_routed:
|
||||
from deeptutor.runtime.registry.capability_registry import (
|
||||
get_capability_registry,
|
||||
)
|
||||
|
||||
routed_capability = get_capability_registry().get(capability_route.capability)
|
||||
if routed_capability is not None:
|
||||
allowed_by_manifest = set(routed_capability.manifest.tools_used)
|
||||
payload = {
|
||||
**payload,
|
||||
"tools": [
|
||||
tool for tool in (payload.get("tools") or []) if tool in allowed_by_manifest
|
||||
],
|
||||
}
|
||||
payload = {**payload, "llm_selection": llm_selection}
|
||||
await self._recover_orphan_running_turns_for_session(session["id"])
|
||||
preference_update: dict[str, Any] = {
|
||||
"capability": capability,
|
||||
# Auto-routing is a one-turn execution choice; keep the durable
|
||||
# preference on what the caller explicitly selected.
|
||||
"capability": requested_capability,
|
||||
"tools": list(payload.get("tools") or []),
|
||||
"knowledge_bases": list(payload.get("knowledge_bases") or []),
|
||||
"language": str(payload.get("language") or "en"),
|
||||
@@ -1834,6 +1896,8 @@ class TurnRuntimeManager:
|
||||
session_metadata["superseded_turn_id"] = str(superseded_turn_id)
|
||||
if runtime_only_config.get("_regenerate"):
|
||||
session_metadata["regenerate"] = True
|
||||
if capability_route is not None:
|
||||
session_metadata["capability_route"] = capability_route.as_metadata()
|
||||
try:
|
||||
await self._publish_live_event(
|
||||
execution,
|
||||
@@ -2821,6 +2885,7 @@ class TurnRuntimeManager:
|
||||
"llm_model": str(getattr(llm_config, "model", "") or ""),
|
||||
"llm_provider": str(getattr(llm_config, "provider_name", "") or ""),
|
||||
"llm_reasoning_effort": str(getattr(llm_config, "reasoning_effort", "") or ""),
|
||||
"capability_route": payload.get("capability_route"),
|
||||
# Per-turn full-text payload for read_source. Empty when
|
||||
# the manifest is empty (non-chat capabilities, or chat
|
||||
# turns with no attached sources). Consumed by the chat
|
||||
@@ -2849,6 +2914,12 @@ class TurnRuntimeManager:
|
||||
continue
|
||||
if event.type == StreamEventType.DONE:
|
||||
pending_done_event = event
|
||||
capability_route = payload.get("capability_route")
|
||||
if isinstance(capability_route, dict):
|
||||
pending_done_event.metadata = {
|
||||
**pending_done_event.metadata,
|
||||
"capability_route": dict(capability_route),
|
||||
}
|
||||
continue
|
||||
payload_event = await self._publish_live_event(execution, event)
|
||||
if payload_event.get("type") not in {"done", "session"}:
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.runtime.capability_routing import route_explicit_quiz_request
|
||||
from deeptutor.runtime.request_contracts import (
|
||||
validate_capability_config,
|
||||
validate_chat_request_config,
|
||||
@@ -25,3 +26,24 @@ def test_chat_config_allows_subagent_consult_budget() -> None:
|
||||
def test_chat_config_still_rejects_unknown_keys() -> None:
|
||||
with pytest.raises(ValueError, match="Extra inputs are not permitted"):
|
||||
validate_chat_request_config({"totally_unknown_key": 1})
|
||||
|
||||
|
||||
def test_explicit_quiz_routing_rules() -> None:
|
||||
route = route_explicit_quiz_request(
|
||||
"Please generate 3 quiz questions",
|
||||
"chat",
|
||||
enabled=True,
|
||||
)
|
||||
assert route is not None
|
||||
assert route.capability == "deep_question"
|
||||
assert route.requested_capability == "chat"
|
||||
assert route.auto_routed is True
|
||||
|
||||
assert (
|
||||
route_explicit_quiz_request("What is formative assessment?", "chat", enabled=True) is None
|
||||
)
|
||||
assert route_explicit_quiz_request("Practice more", "chat", enabled=True) is None
|
||||
assert route_explicit_quiz_request("Quiz me on this chapter", "chat", enabled=True) is None
|
||||
assert route_explicit_quiz_request("Start a quiz", "chat", enabled=True) is None
|
||||
assert route_explicit_quiz_request("考考我", "chat", enabled=True) is None
|
||||
assert route_explicit_quiz_request("考考我", "deep_question", enabled=True) is None
|
||||
|
||||
@@ -60,6 +60,12 @@ def test_runtime_settings_creates_defaults_without_reading_dotenv(tmp_path: Path
|
||||
assert _read_json(service.path_for("auth"))["enabled"] is False
|
||||
|
||||
|
||||
def test_capability_routing_defaults_to_disabled(tmp_path) -> None:
|
||||
service = RuntimeSettingsService(tmp_path / "settings")
|
||||
|
||||
assert service.load_system()["capability_routing_enabled"] is False
|
||||
|
||||
|
||||
def test_runtime_process_env_is_explicit_override(tmp_path: Path) -> None:
|
||||
service = RuntimeSettingsService(
|
||||
tmp_path / "settings",
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Regression coverage for pre-execution chat quiz routing (#807)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.core.stream import StreamEvent, StreamEventType
|
||||
from deeptutor.services.session.sqlite_store import SQLiteSessionStore
|
||||
from deeptutor.services.session.turn_runtime import TurnRuntimeManager
|
||||
|
||||
|
||||
async def _noop_async(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
|
||||
def _fake_skill_service() -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
summary_entries=lambda: [],
|
||||
load_always_for_context=lambda: "",
|
||||
load_for_context=lambda _skills: "",
|
||||
list_skills=lambda: [],
|
||||
)
|
||||
|
||||
|
||||
def _fake_persona_service() -> SimpleNamespace:
|
||||
return SimpleNamespace(load_for_context=lambda _name: "")
|
||||
|
||||
|
||||
def _configure_runtime(monkeypatch: pytest.MonkeyPatch, captured: dict) -> None:
|
||||
class FakeContextBuilder:
|
||||
def __init__(self, *_args, **_kwargs) -> None:
|
||||
pass
|
||||
|
||||
async def build(self, **_kwargs):
|
||||
return SimpleNamespace(
|
||||
conversation_history=[],
|
||||
conversation_summary="",
|
||||
context_text="",
|
||||
token_count=0,
|
||||
budget=0,
|
||||
)
|
||||
|
||||
class FakeOrchestrator:
|
||||
async def handle(self, context):
|
||||
captured["active_capability"] = context.active_capability
|
||||
captured["metadata"] = context.metadata
|
||||
yield StreamEvent(
|
||||
type=StreamEventType.CONTENT,
|
||||
content="ok",
|
||||
metadata={"call_kind": "llm_final_response"},
|
||||
)
|
||||
yield StreamEvent(
|
||||
type=StreamEventType.DONE,
|
||||
source=context.active_capability,
|
||||
metadata={},
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"deeptutor.services.config.runtime_settings.load_system_settings",
|
||||
lambda: {"capability_routing_enabled": captured["global_enabled"]},
|
||||
)
|
||||
monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())
|
||||
monkeypatch.setattr(
|
||||
"deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder
|
||||
)
|
||||
monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)
|
||||
monkeypatch.setattr(
|
||||
"deeptutor.services.memory.get_memory_store",
|
||||
lambda: SimpleNamespace(read_l3_concat=lambda: "", emit=_noop_async),
|
||||
)
|
||||
monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)
|
||||
monkeypatch.setattr("deeptutor.services.persona.get_persona_service", _fake_persona_service)
|
||||
|
||||
|
||||
async def _run_quiz_turn(tmp_path, captured: dict, config: dict | None = None):
|
||||
runtime = TurnRuntimeManager(SQLiteSessionStore(tmp_path / "routing.db"))
|
||||
session, turn = await runtime.start_turn(
|
||||
{
|
||||
"type": "start_turn",
|
||||
"content": "Please generate 3 quiz questions",
|
||||
"session_id": None,
|
||||
"capability": "chat",
|
||||
"tools": ["web_search", "brainstorm"],
|
||||
"knowledge_bases": [],
|
||||
"attachments": [],
|
||||
"language": "en",
|
||||
"config": config or {},
|
||||
}
|
||||
)
|
||||
events = []
|
||||
async for _event in runtime.subscribe_turn(turn["id"], after_seq=0):
|
||||
events.append(_event)
|
||||
done = next(event for event in events if event["type"] == "done")
|
||||
captured["done_metadata"] = done["metadata"]
|
||||
detail = await runtime.store.get_session(session["id"])
|
||||
assert detail is not None
|
||||
return turn, detail
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_quiz_requests_stay_in_chat_by_default(tmp_path) -> None:
|
||||
captured: dict = {"global_enabled": False}
|
||||
_configure_runtime(pytest.MonkeyPatch(), captured)
|
||||
|
||||
turn, session = await _run_quiz_turn(tmp_path, captured)
|
||||
|
||||
assert turn["capability"] == "chat"
|
||||
assert captured["active_capability"] == "chat"
|
||||
assert captured["metadata"]["capability_route"] is None
|
||||
assert "capability_route" not in captured["done_metadata"]
|
||||
assert session["preferences"]["capability"] == "chat"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enabled_explicit_quiz_routes_for_one_turn(tmp_path) -> None:
|
||||
captured: dict = {"global_enabled": True}
|
||||
_configure_runtime(pytest.MonkeyPatch(), captured)
|
||||
|
||||
turn, session = await _run_quiz_turn(tmp_path, captured)
|
||||
|
||||
assert turn["capability"] == "deep_question"
|
||||
assert captured["active_capability"] == "deep_question"
|
||||
assert captured["metadata"]["capability_route"]["auto_routed"] is True
|
||||
assert captured["metadata"]["capability_route"]["strategy"] == "rule"
|
||||
assert captured["done_metadata"]["capability_route"]["capability"] == "deep_question"
|
||||
assert session["preferences"]["capability"] == "chat"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auto_route_false_overrides_global_setting(tmp_path) -> None:
|
||||
captured: dict = {"global_enabled": True}
|
||||
_configure_runtime(pytest.MonkeyPatch(), captured)
|
||||
|
||||
turn, session = await _run_quiz_turn(tmp_path, captured, {"auto_route": False})
|
||||
|
||||
assert turn["capability"] == "chat"
|
||||
assert captured["active_capability"] == "chat"
|
||||
assert session["preferences"]["capability"] == "chat"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_per_turn_flag_opts_in_when_global_default_is_off(tmp_path) -> None:
|
||||
captured: dict = {"global_enabled": False}
|
||||
_configure_runtime(pytest.MonkeyPatch(), captured)
|
||||
|
||||
turn, session = await _run_quiz_turn(tmp_path, captured, {"auto_route": True})
|
||||
|
||||
assert turn["capability"] == "deep_question"
|
||||
assert captured["active_capability"] == "deep_question"
|
||||
assert session["preferences"]["capability"] == "chat"
|
||||
Reference in New Issue
Block a user