Files
cowork-local/core/routing/classifier.py
T
anhtnm1andClaude Opus 5 e29a0ccdbd refactor: vá 4 hồi quy, tách 4 file chạm trần LOC, docstring lên 100%
Hồi quy đã vá
-------------
F-12  Kéo–thả hoặc dán tệp vào ô chat ném NameError. R08 tách `_Input` sang
      `chat_input_box.py` nhưng để `_paths_from_mime()` ở lại
      `composer_widget.py`, nên hai hàm sự kiện Qt gọi một cái tên không tồn
      tại. Bốn hàm dùng chung chuyển sang `composer_mime.py` — module thứ ba
      là chỗ duy nhất không lặp lại được lỗi này. Đo lại: cả thả lẫn dán đều
      gắn 1 tệp, khớp bản trước refactor.

F-01  Đổi provider thì bộ chọn model AI-Edit không làm gì. Hook cũ kiểm
      `folder.ai_model_combo`, thuộc tính R08-T12 đã dời sang
      `ai_panel.resolver`. Làm mới vô điều kiện, đúng như tab cũ: lần lấy đầu
      tiên hỏng thì đổi provider chính là lúc phải thử lại.

F-07  Hàng chọn kỳ của Dashboard bị đẩy xuống dưới các thẻ số liệu. Hàng này
      lọc CẢ BA thẻ con chứ không riêng biểu đồ, nên để nó nằm dưới là bắt
      người dùng đọc con số trước khi thấy con số đó tính cho kỳ nào. Kèm
      theo: `TokenUsageCardWidget` bị bỏ sót `setContentsMargins(0,0,0,0)`
      mà hai thẻ con còn lại đã có, đẩy cả hàng thẻ lệch 9px.
      `check_layout_geometry` nay khớp TỪNG BYTE với bản trước refactor.

F-11  Hai lớp khai trùng tên phương thức; Python giữ bản sau nên bản đầu là
      mã chết. `co4e_tab.py::showEvent` bản đầu gọi `_narrow_guard.attach()`
      và không bao giờ chạy.

Tách file (F-09)
----------------
Bốn file chạm trần 400 dòng, mỗi lần cắt ra một trách nhiệm thật:

    graph_renderer.py         -> graph_scene_builder.py + graph_export.py
    co4e_workflow_service.py  -> co4e_run_history.py
    json_config_repository.py -> config_sections.py
    agents_admin_tab.py       -> shared/agent_kind_visuals.py

File cuối còn xoá 3 bản sao của hàm đã có trong `shared/formatters.py`,
giống hệt đến từng dòng — nay định dạng thời gian và avatar không lệch nhau
giữa các bảng Giám sát nữa.

Docstring
---------
41,6% -> 100% (3.478/3.478 định nghĩa production), kể cả module dormant và
phương thức dunder. Toàn bộ phần bổ sung viết bằng tiếng Việt; comment tiếng
Anh có sẵn giữ nguyên — dịch ngược là một đợt riêng.

Seam chưa nối dây (F-05)
------------------------
9 seam mang nhãn `SEAM · dựng <ngày>` kèm hai câu: được nối khi nào, và để
dormant thì hỏng gì. Ngày lấy từ lịch sử git, không phải hạn tự đặt. Gate O
đọc nhãn đó và nhắc khi quá 30 ngày.

859 test xanh · 4/4 cổng CASAN · 19/24 checker khớp từng byte bản cũ.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 10:41:45 +09:00

128 lines
4.8 KiB
Python

"""Classify a user prompt into a :class:`TaskType`.
Routing runs on every turn, so classification must be cheap — a keyword
heuristic first, with an optional one-shot LLM fallback only when the heuristic
is unsure. The heuristic is intentionally conservative: it defaults to ``QA``
(the safest general bucket) rather than mis-routing an ambiguous prompt.
"""
from __future__ import annotations
import re
from typing import Callable, List, Optional, Tuple
from .models import TaskType
# Signal words per task type. Matched case-insensitively on word boundaries.
# Ordered by specificity when scoring ties (CODING/REASONING beat QA).
_KEYWORDS: dict[TaskType, List[str]] = {
TaskType.CODING: [
"code", "function", "class", "bug", "debug", "refactor", "compile",
"stack trace", "traceback", "python", "javascript", "typescript",
"java", "c++", "golang", "rust", "sql", "regex", "api", "endpoint",
"unit test", "pytest", "npm", "docker", "git", "implement", "algorithm",
"syntax", "exception", "import", "def ", "async", "lập trình", "hàm",
"sửa lỗi", "biên dịch",
],
TaskType.REASONING: [
"why", "prove", "explain why", "reason", "logic", "deduce", "infer",
"step by step", "step-by-step", "solve", "calculate", "how many",
"puzzle", "riddle", "strategy", "trade-off", "tradeoff", "analyze",
"compare and", "chứng minh", "suy luận", "tính toán", "phân tích",
],
TaskType.SUMMARIZATION: [
"summarize", "summary", "tl;dr", "tldr", "condense", "shorten",
"key points", "in short", "brief", "recap", "abstract of", "gist",
"tóm tắt", "rút gọn", "tóm lược",
],
TaskType.CREATIVE: [
"poem", "story", "write a", "creative", "imagine", "fiction", "lyrics",
"song", "haiku", "screenplay", "dialogue", "brainstorm", "slogan",
"tagline", "marketing copy", "viết truyện", "bài thơ", "sáng tạo",
"kịch bản",
],
TaskType.QA: [
"what is", "who is", "when did", "where is", "define", "meaning of",
"how do i", "how to", "is it", "does", "can you tell", "fact",
"là gì", "ai là", "khi nào", "ở đâu", "định nghĩa",
],
}
# Precompiled boundary regexes; ASCII \b doesn't hug Vietnamese diacritics well,
# so multi-word/diacritic phrases fall back to plain substring matching.
_COMPILED: dict[TaskType, List[Tuple[str, Optional[re.Pattern]]]] = {}
for _tt, _words in _KEYWORDS.items():
entries: List[Tuple[str, Optional[re.Pattern]]] = []
for w in _words:
if w.isascii() and " " not in w and w.strip().isalpha():
entries.append((w, re.compile(rf"\b{re.escape(w)}\b", re.IGNORECASE)))
else:
entries.append((w, None)) # substring match
_COMPILED[_tt] = entries
# Tie-break priority when multiple task types score equally.
_PRIORITY = [
TaskType.CODING,
TaskType.REASONING,
TaskType.SUMMARIZATION,
TaskType.CREATIVE,
TaskType.QA,
]
# LLM fallback: given the prompt, return a TaskType value string.
LLMClassifier = Callable[[str], str]
def _heuristic_scores(text: str) -> dict[TaskType, int]:
"""Chấm điểm loại việc bằng từ khoá, không cần gọi model.
Bước lọc rẻ đứng trước bộ phân loại bằng AI: phần lớn câu hỏi phân loại được
ngay tại đây mà không tốn lượt gọi nào.
"""
low = (text or "").lower()
scores: dict[TaskType, int] = {tt: 0 for tt in TaskType}
for tt, entries in _COMPILED.items():
for raw, pat in entries:
if pat is not None:
if pat.search(low):
scores[tt] += 1
elif raw in low:
scores[tt] += 1
return scores
def classify(
text: str,
*,
llm_classifier: Optional[LLMClassifier] = None,
min_confidence: int = 1,
) -> TaskType:
"""Return the most likely :class:`TaskType` for ``text``.
Uses the keyword heuristic first. If nothing scores at least
``min_confidence`` and an ``llm_classifier`` is provided, defers to it once;
otherwise defaults to :attr:`TaskType.QA`.
"""
scores = _heuristic_scores(text)
best_score = max(scores.values()) if scores else 0
if best_score >= min_confidence:
# Highest score, ties broken by _PRIORITY order.
for tt in _PRIORITY:
if scores[tt] == best_score:
return tt
if llm_classifier is not None:
try:
raw = (llm_classifier(text) or "").strip().lower()
return TaskType(raw)
except Exception: # noqa: BLE001 — bad/failed classification → default
pass
return TaskType.QA
__all__ = ["classify", "LLMClassifier", "BENCHMARK_HINT"]
# Small doc alias so callers can show which task types exist.
BENCHMARK_HINT = [tt.value for tt in TaskType]