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>
169 lines
6.1 KiB
Python
169 lines
6.1 KiB
Python
"""Orchestrate a full assessment run: enrich → probe → score → store.
|
||
|
||
``check_and_update`` is the single entry point the API/scheduler call. It:
|
||
|
||
1. Enriches each candidate's static metadata (price / context / capabilities).
|
||
2. Probes every candidate on every task type concurrently, bounded per provider
|
||
(delegated to ``prober.probe_candidates``), grading each answer with one
|
||
fixed judge.
|
||
3. Computes fit scores per task type under the active policy.
|
||
4. Persists the results atomically, backing up the previous version to history
|
||
first (so a model that *degrades* between runs can be spotted).
|
||
|
||
Cost-awareness: probing spends real tokens, so this runs only on a schedule,
|
||
when a model is added, or on an explicit reassess — never per chat turn. The
|
||
number of API calls made is logged so the cost is visible.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from typing import Callable, Dict, List, Optional, Tuple
|
||
|
||
from .clients import ProbeClient
|
||
from .metadata import LLMDeclarer, enrich
|
||
from .models import ModelAssessment, Policy, TaskType, candidate_key
|
||
from .prober import JudgeFn, make_judge, probe_candidates
|
||
from .scorer import compute_fit_score
|
||
from .store import AssessmentStore, utc_now_iso
|
||
|
||
logger = logging.getLogger("cowork_local.routing")
|
||
|
||
# A candidate to assess: (provider, model_id, tier|None).
|
||
Candidate = Tuple[str, str, Optional[str]]
|
||
|
||
|
||
def build_assessment(
|
||
provider: str,
|
||
model_id: str,
|
||
tier: Optional[str],
|
||
probes: Dict[str, "object"],
|
||
policy: Policy,
|
||
*,
|
||
config=None,
|
||
task_types: Optional[List[TaskType]] = None,
|
||
llm_declarer: Optional[LLMDeclarer] = None,
|
||
) -> ModelAssessment:
|
||
"""Assemble one :class:`ModelAssessment` from its probe results.
|
||
|
||
Pure except for metadata enrichment (which may read the config price
|
||
sheet). Kept separate from I/O so it's unit-testable without any network.
|
||
"""
|
||
from .models import ProbeResult
|
||
|
||
task_types = task_types or list(TaskType)
|
||
meta = enrich(provider, model_id, config=config, tier=tier, llm_declarer=llm_declarer)
|
||
|
||
# A model that failed EVERY probe is effectively unavailable this run.
|
||
typed_probes: Dict[str, ProbeResult] = {}
|
||
any_success = False
|
||
for tt in task_types:
|
||
probe = probes.get(tt.value)
|
||
if isinstance(probe, ProbeResult):
|
||
typed_probes[tt.value] = probe
|
||
any_success = any_success or probe.success
|
||
if typed_probes and not any_success:
|
||
meta.available = False
|
||
|
||
fit_scores: Dict[str, float] = {}
|
||
for tt in task_types:
|
||
probe = typed_probes.get(tt.value)
|
||
if probe is not None:
|
||
fit_scores[tt.value] = compute_fit_score(meta, probe, policy)
|
||
|
||
return ModelAssessment(
|
||
metadata=meta,
|
||
probes=typed_probes,
|
||
fit_scores=fit_scores,
|
||
assessed_at=utc_now_iso(),
|
||
)
|
||
|
||
|
||
def check_and_update(
|
||
candidates: List[Candidate],
|
||
client: ProbeClient,
|
||
*,
|
||
judge: Optional[JudgeFn] = None,
|
||
judge_provider: str = "",
|
||
judge_model: str = "",
|
||
store: Optional[AssessmentStore] = None,
|
||
config=None,
|
||
policy: Policy = Policy.BALANCED,
|
||
task_types: Optional[List[TaskType]] = None,
|
||
per_provider_concurrency: int = 2,
|
||
max_workers: int = 8,
|
||
llm_declarer: Optional[LLMDeclarer] = None,
|
||
persist: bool = True,
|
||
) -> Dict[str, ModelAssessment]:
|
||
"""Assess every candidate and (optionally) persist the results.
|
||
|
||
Provide either a ready ``judge`` callable, or ``judge_provider`` +
|
||
``judge_model`` to build the standard rubric judge from ``client``.
|
||
|
||
Returns ``{candidate_key: ModelAssessment}``. ``persist=False`` skips the
|
||
store write (used by tests / dry runs).
|
||
"""
|
||
task_types = task_types or list(TaskType)
|
||
if not candidates:
|
||
logger.info("routing.reassess: no candidates configured — nothing to do")
|
||
return {}
|
||
|
||
if judge is None:
|
||
if not (judge_provider and judge_model):
|
||
raise ValueError("check_and_update needs either `judge` or judge_provider+judge_model")
|
||
judge = make_judge(client, judge_provider, judge_model)
|
||
|
||
judge_key = candidate_key(judge_provider, judge_model) if judge_provider else None
|
||
if judge_key and any(candidate_key(p, m) == judge_key for p, m, _ in candidates):
|
||
# The judge is also a candidate — its own answers are self-graded. We
|
||
# keep it routable (it may genuinely be a fine cheap model) but flag the
|
||
# bias so it's not mistaken for an independent score.
|
||
logger.warning(
|
||
"routing.reassess: judge model %s is also a candidate — its quality "
|
||
"scores are self-judged and may be optimistic", judge_key,
|
||
)
|
||
|
||
# --- count API calls so the cost of a reassess is visible ------------- #
|
||
call_count = {"n": 0}
|
||
|
||
def _tick() -> None:
|
||
"""Một nhịp đếm trong lúc chờ người dùng xác nhận đổi model — đếm lùi và tự
|
||
quyết định khi hết giờ.
|
||
"""
|
||
call_count["n"] += 1
|
||
|
||
pairs = [(p, m) for (p, m, _tier) in candidates]
|
||
probe_map = probe_candidates(
|
||
client, pairs, task_types, judge,
|
||
per_provider_concurrency=per_provider_concurrency,
|
||
max_workers=max_workers,
|
||
call_counter=_tick,
|
||
)
|
||
|
||
assessments: Dict[str, ModelAssessment] = {}
|
||
for (provider, model_id, tier) in candidates:
|
||
key = candidate_key(provider, model_id)
|
||
assessments[key] = build_assessment(
|
||
provider, model_id, tier,
|
||
probe_map.get(key, {}), policy,
|
||
config=config, task_types=task_types, llm_declarer=llm_declarer,
|
||
)
|
||
|
||
# ~1 probe call + 1 judge call per (candidate, task). The counter above only
|
||
# counts probe calls (judge calls happen inside probe_model), so report both.
|
||
probe_calls = call_count["n"]
|
||
logger.info(
|
||
"routing.reassess: %d candidate(s) × %d task(s) → ~%d probe calls "
|
||
"(+~%d judge calls), policy=%s",
|
||
len(candidates), len(task_types), probe_calls, probe_calls, policy.value,
|
||
)
|
||
|
||
if persist:
|
||
store = store or AssessmentStore()
|
||
store.save(assessments, policy)
|
||
store.prune_history(keep=30)
|
||
|
||
return assessments
|
||
|
||
|
||
__all__ = ["check_and_update", "build_assessment", "Candidate"]
|