新增:智能分析图表与报告快照,支持环状图和柏拉图

This commit is contained in:
2026-10-23 20:25:12 +08:00
parent 8684ce1a4d
commit 13695da433
23 changed files with 5252 additions and 57 deletions
+86
View File
@@ -0,0 +1,86 @@
"""Read this turn's bounded, private quality evidence for deterministic charts.
This path never sends data to a model or reads original workbooks. In particular
it must not use the finalizer's presentation-truncated evidence as a full dataset.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
import re
import stat
import time
FILE_LIMIT = 4 * 1024 * 1024
TOTAL_LIMIT = 16 * 1024 * 1024
DOCUMENT_LIMIT = 100
def load_visual_evidence(directory: Path, release_id: str, *, exclude_files=frozenset(),
cancel_event=None, budget_seconds: float = 0.3) -> list[dict]:
"""Fail closed on bad identity, permissions, excessive size, or a changed file.
The caller already owns an isolated actor/session directory. The pre-turn
file inventory prevents previous questions from supplying the new answer's
charts. Bounds count bytes before parsing any document.
"""
if directory.is_symlink():
raise ValueError('invalid evidence directory')
started = time.monotonic()
documents: list[dict] = []
total = 0
for path in sorted(directory.glob('nao-quality-*.json')):
if cancel_event is not None and cancel_event.is_set():
return []
if time.monotonic() - started > budget_seconds:
raise ValueError('visual evidence deadline')
if path.name in exclude_files:
continue
if not re.fullmatch(r'nao-quality-[a-f0-9]{32}\.json', path.name):
continue
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
with os.fdopen(fd, 'rb') as source:
before = os.fstat(source.fileno())
if (not stat.S_ISREG(before.st_mode) or before.st_mode & 0o077
or before.st_uid != os.getuid() or before.st_size > FILE_LIMIT):
raise ValueError('invalid evidence file')
total += before.st_size
if total > TOTAL_LIMIT or len(documents) >= DOCUMENT_LIMIT:
raise ValueError('visual evidence limit')
raw = source.read(FILE_LIMIT + 1)
after = os.fstat(source.fileno())
if (len(raw) > FILE_LIMIT or before.st_size != after.st_size
or before.st_mtime_ns != after.st_mtime_ns):
raise ValueError('evidence changed while reading')
document = json.loads(raw)
if not isinstance(document, dict):
raise ValueError('invalid evidence document')
result = document.get('result')
if (document.get('tool') != 'quality_data' or document.get('releaseId') != release_id
or not isinstance(result, dict) or result.get('releaseId') != release_id
or not re.fullmatch(r'Q[A-F0-9]{8}', str(document.get('evidenceRef', '')))):
raise ValueError('evidence binding mismatch')
if document.get('mode') in ('query', 'compare', 'top', 'changes', 'defects'):
documents.append(document)
return documents
def visual_result(directory: Path, release_id: str, question: str, turn_id: str,
*, exclude_files=frozenset(), cancel_event=None) -> dict:
"""A chart failure is presentation-only and must never change turn status."""
if os.environ.get('QUALITY_ANALYSIS_VISUALS_ENABLED', 'true').lower() not in ('true', '1', 'yes'):
return {'visualSchemaVersion': 1, 'visualState': 'not_requested', 'visuals': []}
if cancel_event is not None and cancel_event.is_set():
return {'visualSchemaVersion': 1, 'visualState': 'unavailable', 'visuals': []}
try:
from analysis_visuals import build_visuals
evidence = load_visual_evidence(directory, release_id, exclude_files=exclude_files,
cancel_event=cancel_event)
if cancel_event is not None and cancel_event.is_set():
return {'visualSchemaVersion': 1, 'visualState': 'unavailable', 'visuals': []}
return build_visuals(evidence, question, turn_id)
except Exception:
# Presentation must not turn an otherwise successful business answer into
# a failed task, including unexpected adapter bugs. Do not expose paths.
return {'visualSchemaVersion': 1, 'visualState': 'failed', 'visuals': []}
File diff suppressed because it is too large Load Diff
+6
View File
@@ -1765,6 +1765,7 @@ def _sse_request(
)
prompt = (f"【仅内部查询约束,禁止向用户复述】本轮数据查询使用 releaseId={release_id},后续所有数据查询必须沿用该标识。"
"如果当前数据下的证据不足,请如实说明,不要切换数据。用户可见的欢迎语、回答和报告只写业务问题、期间、范围、指标、结果与必要局限;不展示 releaseId、发布版本号、Story ID/version,也不说‘固定版本’。不要展示‘原始明细不发AI’等内部流程提示。"
+ "\n【平台配图约束】图表由平台从 quality_data 的真实结果自动绘制。只查询必要的正式统计;禁止为图表调用 execute_sql、数据库或 story,不探测图表服务,不声称前端图表不可用。拿到所需数据即完成文字答复。"
+ context_text + "\n\n用户问题:\n" + question)
body: dict[str, Any] = {
"message": {"text": prompt},
@@ -2047,6 +2048,11 @@ def run_turn(payload: dict[str, Any], *, stdout: Any = sys.stdout, stdin: Any =
}
if finalized:
result["evidenceCompletion"] = evidence_completion
if answer and status in ("COMPLETED", "PARTIAL") and not cancel_event.is_set():
from analysis_visual_evidence import visual_result
result.update(visual_result(actor_root / "evidence", request["releaseId"],
request["question"], request["turnId"],
exclude_files=prior_evidence_files, cancel_event=cancel_event))
if report_markdown is not None:
result["reportMarkdown"] = report_markdown
if report_html is not None: