mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-25 10:52:19 +00:00
合入 W2-a 想 + 文档:问题意图词表、分析方法定稿(analysis.method@2)、助手建图认分析卡与分析工具(分析类问题的形状、自查只挡一轮、关分析工具的开关)、复核信号并成一条只写说明、内置模板 ⑪「异动分析(可追溯)」、中英文档(新增 analysis 一篇、七对文档与升级说明、README)
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
"""问题意图(app/analysis/intent.py):一句问题是不是分析类问题,给助手搭问数据的图时自查用。
|
||||
|
||||
只收明确的问法、宁可漏判:漏判只是少一条自查提醒,误判要让助手多改一轮。所以反例和正例一样多——问一个字段(退款原因)、
|
||||
问业务状态(异常订单)、问服务(系统正常吗)、筛选(波动超过 10%)、问时长(持续几天)都不算。问法都是虚构的零售场景。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.analysis.intent import INTENT_VERSION, KINDS, Intent, analysis_intent, is_analytical
|
||||
|
||||
POSITIVE = [
|
||||
# 原因
|
||||
("上周销售额为什么下降了", "why"),
|
||||
("华东的退款率为什么这么高", "why"),
|
||||
("为什么华东比华南的客单价低", "why"),
|
||||
("销售额下降了,为什么", "why"),
|
||||
("这周订单怎么会少了这么多", "why"),
|
||||
("销售额下滑的主要原因是什么", "why"),
|
||||
("什么原因导致线上订单减少", "why"),
|
||||
("本周销售额下滑了,原因是什么?", "why"),
|
||||
# 来源
|
||||
("这周和上周比,销售额怎么变了", "source"),
|
||||
("上周各渠道的销售额有什么变化", "source"),
|
||||
("哪个地区拖累了整体销售额", "source"),
|
||||
("谁贡献最大", "source"),
|
||||
("增长主要来自哪个地区", "source"),
|
||||
("各地区对销售额增长的贡献是多少", "source"),
|
||||
("销售额增长的驱动因素有哪些", "source"),
|
||||
("什么带动了订单增长", "source"),
|
||||
("把销售额的变化按地区拆开看看", "source"),
|
||||
("做个归因分析", "source"),
|
||||
# 异常
|
||||
("本周销售额是否异常", "anomaly"),
|
||||
("这周退款单数异常吗?", "anomaly"),
|
||||
("下降 12% 正常吗", "anomaly"),
|
||||
("这个降幅算不算异常", "anomaly"),
|
||||
("上周订单有没有异动", "anomaly"),
|
||||
("取消单是不是暴增了,有没有激增", "anomaly"),
|
||||
("这周的销售额是不是超出了正常范围", "anomaly"),
|
||||
# 波动
|
||||
("最近销售额波动大吗", "fluctuation"),
|
||||
("这是不是正常波动", "fluctuation"),
|
||||
("销售额同比变化大不大", "fluctuation"),
|
||||
# 趋势
|
||||
("线上销售额的趋势怎么样", "trend"),
|
||||
("看一下近半年订单数的走势", "trend"),
|
||||
("线上销售额是不是在持续上升", "trend"),
|
||||
("下降会持续吗", "trend"),
|
||||
("华南的销售额连续三周下降了吗", "trend"),
|
||||
("客单价是不是越来越低", "trend"),
|
||||
("退款率是不是一直在涨", "trend"),
|
||||
# 差异
|
||||
("华东的退款率是不是真的比华南高", "differ"),
|
||||
("线上和线下的转化率差异显著吗", "differ"),
|
||||
("两组的客单价有没有明显差别", "differ"),
|
||||
("这个差距是不是偶然", "differ"),
|
||||
# 英文
|
||||
("Why did sales drop last week?", "why"),
|
||||
("What drove the decline in online orders?", "source"),
|
||||
("Is this normal for a Monday?", "anomaly"),
|
||||
("Show me the trend of refunds", "trend"),
|
||||
("Is the refund rate in East significantly higher than South?", "differ"),
|
||||
]
|
||||
|
||||
NEGATIVE = [
|
||||
"上周销售额是多少",
|
||||
"列出华东、华南、华北、西南四个地区的订单数",
|
||||
"shop 里都有哪些表",
|
||||
"退款原因有哪些",
|
||||
"按取消原因统计上周的订单数",
|
||||
"订单主要来自哪些渠道",
|
||||
"有多少异常订单",
|
||||
"有没有异常记录",
|
||||
"列出状态为异常的订单",
|
||||
"系统正常吗",
|
||||
"数据源连接正常吗",
|
||||
"门店是否正常营业",
|
||||
"列出价格波动超过 10% 的商品",
|
||||
"网络波动大吗",
|
||||
"促销活动持续了几天",
|
||||
"这个活动会持续多久",
|
||||
"为什么报错了",
|
||||
"为什么查不到数据",
|
||||
"表结构有什么变化",
|
||||
"口径有什么变化",
|
||||
"按地区拆分订单",
|
||||
"导出上周的销售明细",
|
||||
"",
|
||||
" ",
|
||||
"How many orders did we get last week?",
|
||||
"Why is the query slow?",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("question, kind", POSITIVE)
|
||||
def test_analysis_questions_are_recognized(question, kind):
|
||||
found = analysis_intent(question)
|
||||
assert found is not None, question
|
||||
assert found.kind == kind, (question, found)
|
||||
assert found.text and found.text.rstrip("…") in question, found
|
||||
assert is_analytical(question)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("question", NEGATIVE)
|
||||
def test_other_questions_are_left_alone(question):
|
||||
assert analysis_intent(question) is None, (question, analysis_intent(question))
|
||||
assert not is_analytical(question)
|
||||
|
||||
|
||||
def test_the_lexicon_is_versioned_and_every_kind_has_a_label():
|
||||
assert INTENT_VERSION == 1
|
||||
assert {kind for _, kind in POSITIVE} == set(KINDS)
|
||||
found = analysis_intent("上周销售额为什么下降了")
|
||||
assert isinstance(found, Intent) and found.version == INTENT_VERSION and found.label == "原因"
|
||||
|
||||
|
||||
def test_sentences_are_read_one_at_a_time():
|
||||
"""问原因的词和变化要在同一句:前一句问报错、后一句问销售额,不拼在一起认;逗号不分句。"""
|
||||
assert analysis_intent("为什么报错了?上周销售额是多少") is None
|
||||
assert analysis_intent("上周销售额是多少?跟前一周比为什么少了").kind == "why"
|
||||
# 只有那一句是在问服务的,别的句子照认
|
||||
assert analysis_intent("系统正常吗?另外这周销售额是否异常").kind == "anomaly"
|
||||
|
||||
|
||||
def test_the_quoted_text_is_short():
|
||||
question = "为什么" + "华东" * 30 + "的销售额下降"
|
||||
found = analysis_intent(question)
|
||||
assert found is not None and len(found.text) <= 24 and found.text.endswith("…")
|
||||
|
||||
|
||||
def test_the_intent_lexicon_is_not_the_claims_lexicon():
|
||||
"""意图判用户的问题,说法核对判写作者的句子:「主要来自哪」是在问(意图认),「主要来自华东」是下判断(意图不认)。"""
|
||||
assert analysis_intent("下降主要来自哪个地区").kind == "source"
|
||||
assert analysis_intent("本周订单主要来自线上渠道") is None
|
||||
@@ -0,0 +1,47 @@
|
||||
"""平台内置的分析方法(tools/builtin/analysis.py 的 ANALYSIS_METHOD_PROMPT,第 2 波定稿,guide id analysis.method@2)。
|
||||
|
||||
方法随代码升版、绑了任一个分析工具就注入 Agent 的 system(注入本身见 tests/test_analysis_tools.py)。这里守方法里该写清的几件事
|
||||
都在:按问题选基期、周序列的期次怎么写、先现象后拆解再下钻的顺序、写明在验证什么、拆了不集中也是结论、不作因果断言、阈值
|
||||
不由模型定、算不了照实说、最后列出做过的分析;方法里点名的工具都是真有的那五个。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from app.analysis import contract
|
||||
from app.tools.builtin.analysis import ANALYSIS_METHOD_PROMPT, METHOD_GUIDE
|
||||
from app.tools.registry import all_specs
|
||||
|
||||
|
||||
def test_the_guide_is_the_second_version_and_shared_by_all_five_tools():
|
||||
assert METHOD_GUIDE.id == "analysis.method@2" and METHOD_GUIDE.text == ANALYSIS_METHOD_PROMPT
|
||||
specs = all_specs()
|
||||
assert {name for name, spec in specs.items() if spec.guide is METHOD_GUIDE} == set(contract.TOOL_NAMES.values())
|
||||
|
||||
|
||||
def test_the_method_says_how_to_pick_the_base_period():
|
||||
first = ANALYSIS_METHOD_PROMPT.split("\n2.")[0]
|
||||
for words in ("上周", "去年同期", "和目标比", "上一个整期", "lag", "52", "库里没有目标就照实说", "已经过完的整期"):
|
||||
assert words in first, words
|
||||
|
||||
|
||||
def test_the_method_says_how_to_write_weekly_periods():
|
||||
for words in ("每周第一天的日期", "ISO 周「YYYY-Www」", "SQLite 的 %W", "不是 ISO 周", "date(日期列, '-6 days', 'weekday 1')",
|
||||
"核对不了"):
|
||||
assert words in ANALYSIS_METHOD_PROMPT, words
|
||||
|
||||
|
||||
def test_the_method_orders_the_steps_and_names_only_real_tools():
|
||||
text = ANALYSIS_METHOD_PROMPT
|
||||
# 先可比性和基线,再拆因子与结构,再按维度由粗到细,找到主要来源再下钻一层
|
||||
order = [text.index(w) for w in ("analysis_comparable", "analysis_baseline", "factor", "ratio", "additive", "parent")]
|
||||
assert order == sorted(order), order
|
||||
named = set(re.findall(r"\banalysis_[a-z]+\b", text))
|
||||
assert named == set(contract.TOOL_NAMES.values()), named
|
||||
assert "由粗到细" in text and "下钻一层" in text and "headline" in text
|
||||
|
||||
|
||||
def test_the_method_keeps_the_round_rules():
|
||||
for words in ("hypothesis", "拆了没发现集中", "也是结论", "不作因果断言", "待核实的推测", "工具参数里没有阈值",
|
||||
"算不了", "照实说原因", "【分析 An】", "判定语原话", "没做的分析不要写成做过"):
|
||||
assert words in ANALYSIS_METHOD_PROMPT, words
|
||||
@@ -0,0 +1,360 @@
|
||||
"""助手搭图认分析能力(00-总方案 §3.7):节点手册教分析卡和分析工具、报告的分析结论引用写法;问数据的包装多一种「分析类
|
||||
问题」的形状;自查时问题是分析类(app/analysis/intent)、查库的 Agent 却没绑分析工具,交回模型改一轮(只挡一轮,照 coverage
|
||||
的样板),改过一轮仍在的不挡运行、留作提醒;报告的上游只有分析卡也算有可引用的来源。评测「分析工具开、关」对照的「关」那一臂
|
||||
(answer_ops 的 analysis_tools、chat/drive.TurnDriver 的同名属性):工具清单、节点手册、问数据的包装里都没有分析,图里绑了
|
||||
也按「绑定的工具不存在」挡,别的和开着时一样。
|
||||
|
||||
手册里举的引用标记交给真正的解析器,确认写法和系统认的是同一套(同 tests/test_copilot_entity_guide.py)。问法、节点、
|
||||
表都是虚构的零售场景。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from langchain_core.messages import AIMessageChunk
|
||||
|
||||
from app.analysis import contract
|
||||
from app.api.copilot import (_ASSIST_RULES, ANALYSIS_SHAPE_PROMPT, ANALYSIS_TOOLS_OFF, NODE_REFERENCE, GenerateIn,
|
||||
_evidence_source, _question_of, _tool_catalog, _user_message, node_reference)
|
||||
from app.api.copilot_gen import ANALYSIS_TOOLS_MISSING, GraphApplier, GraphChecker
|
||||
from app.engine.evidence import _CELL_REF, _ROW_REF, SUPPORTED_KINDS, parse_markers
|
||||
from app.engine.schema import ANALYSIS_CLAIMS_VALUES, ANALYSIS_SCOPE_VALUES, GraphNode, NodeType
|
||||
from tests.test_copilot_answer_ops import _sse, _use, client # noqa: F401
|
||||
|
||||
TOOLS = list(contract.TOOL_NAMES.values())
|
||||
|
||||
|
||||
def _section(start: str, end: str) -> str:
|
||||
i = NODE_REFERENCE.index(start)
|
||||
return NODE_REFERENCE[i:NODE_REFERENCE.index(end, i)]
|
||||
|
||||
|
||||
def _report() -> str:
|
||||
return _section("- report:", "\n- output")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 节点手册
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_card_entry_teaches_the_analysis_card():
|
||||
card = _section("- analysis:分析卡", "\n- dual_check")
|
||||
for words in (["items", "overrides", "from", "params", "hypothesis"], # 配置
|
||||
["模板里每次都要做的分析", "周报的异动"], # 用途
|
||||
["nodes.<id>.results.<项 id>", "verdict", "branch"], # 产出、按判定分支
|
||||
["tool 节点或 merge", "agent 不能当", "headline", "parent"], # 输入只认查询节点
|
||||
["不要把结果交给口径卡", "追不到原始数据"]): # D16
|
||||
assert all(w in card for w in words), [w for w in words if w not in card]
|
||||
assert all(op in card for op in contract.OPS)
|
||||
assert all(mode in card for modes in contract.MODES.values() for mode in modes)
|
||||
# 例子里的阈值键、判定码都是契约里的
|
||||
assert all(key in contract.DEFAULTS for key in re.findall(r"\b(k_warn|main_share|k_alert|flat_pct)\b", card))
|
||||
branch = re.search(r"verdict in \[([^\]]+)\]", card).group(1)
|
||||
assert {v.strip(" '") for v in branch.split(",")} <= set(contract.VERDICTS["baseline"])
|
||||
|
||||
|
||||
def test_the_agent_entry_names_the_five_analysis_tools():
|
||||
agent = _section("- agent:", "\n- supervisor")
|
||||
assert all(name in agent for name in TOOLS)
|
||||
for words in ("分析方法", "注入", "不要写阈值", "只绑给同时绑了", "db_query__", "不能放进 tool 节点"):
|
||||
assert words in agent, words
|
||||
|
||||
|
||||
def test_the_markers_of_analysis_conclusions_parse_as_the_system_reads_them():
|
||||
markers = [m for m in parse_markers(_report()) if "A1" in m["body"]]
|
||||
kinds = {m["kind"] for m in markers}
|
||||
assert {contract.MARKER_KIND, "v", "table", "see"} <= kinds <= SUPPORTED_KINDS
|
||||
by_kind = {m["kind"]: m for m in markers}
|
||||
plain = [m for m in markers if m["kind"] == contract.MARKER_KIND and m["ref"] == "A1"]
|
||||
named = [m for m in markers if m["kind"] == contract.MARKER_KIND and m["ref"] != "A1"]
|
||||
assert plain and named and named[0]["ref"] == "A1.top_share" and named[0]["conv"] == "pct"
|
||||
cell = _CELL_REF.match(by_kind["v"]["ref"])
|
||||
assert cell and cell.group("alias") == "A1" and cell.group("column") == "share"
|
||||
assert _ROW_REF.match(by_kind["table"]["ref"]).group("alias") == "A1"
|
||||
assert by_kind["see"]["refs"] == ["A1"]
|
||||
# 拆解结果表的列 id(判定写法里举的 delta、share)是真结果表的列
|
||||
from app.analysis.decompose import _FIXED_ADDITIVE
|
||||
|
||||
cols = by_kind["table"]["options"]["cols"].split(",")
|
||||
assert set(cols[1:]) <= set(_FIXED_ADDITIVE), cols
|
||||
|
||||
|
||||
def test_the_report_entry_spells_out_analysis_claims_and_scope():
|
||||
report = _report()
|
||||
assert "analysis_claims" in report and "analysis_scope" in report
|
||||
assert all(v in report for v in ANALYSIS_CLAIMS_VALUES) and all(v in report for v in ANALYSIS_SCOPE_VALUES)
|
||||
assert "off < check < strict" in report and "只能往严里改" in report
|
||||
for words in ("主要来自", "异常", "持续上升", "待核实的推测", "说明不了为什么"):
|
||||
assert words in report, words
|
||||
|
||||
|
||||
def test_governed_templates_and_the_publish_assist_keep_analysis_claims_strict():
|
||||
governed = NODE_REFERENCE[NODE_REFERENCE.index("要按受管级别发布的模板"):]
|
||||
assert 'analysis_claims: "strict"' in governed[:400]
|
||||
rules = " ".join(_ASSIST_RULES.split())
|
||||
assert re.search(r"analysis_claims.{0,40}只能往严里改|只能往严里改.{0,80}analysis_claims: strict", rules), rules
|
||||
assert "off < check < strict" in rules and "不改回 check" in rules
|
||||
|
||||
|
||||
def test_the_build_rules_bind_analysis_tools_for_analysis_questions():
|
||||
rules = NODE_REFERENCE[NODE_REFERENCE.index("搭图规则"):NODE_REFERENCE.index("模型字段")]
|
||||
seventh = rules[rules.index("\n7."):]
|
||||
assert "分析工具" in seventh and "分析卡" in seventh and "不进口径卡" in seventh
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 问数据的包装
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_answer_request_has_an_analysis_shape():
|
||||
text = _user_message(GenerateIn(instruction="上周销售额为什么下降", intent="answer"), patch=False)
|
||||
shape = next(line for line in text.splitlines() if line.startswith("- 问的是为什么"))
|
||||
assert "input → agent → report → output" in shape
|
||||
assert all(name in shape for name in TOOLS) and "db_query__" in shape and "db_schema__" in shape
|
||||
assert "按分析结论写" in shape and "判定语" in shape and "不写阈值" in shape
|
||||
# 问数是探索运行:不替人打开结论句策略(test_copilot_entity_guide 守着),说法核对用默认、不关
|
||||
assert not re.search(r"(?<!analysis_)claims\s*[:=]\s*['\"]?(require_citation|judge)", text)
|
||||
assert "analysis_claims " in shape and "不要关" in shape
|
||||
|
||||
|
||||
def test_the_question_for_the_self_check():
|
||||
"""自查按用户原本的问题判意图:问数据有原问题时用它(重来时 instruction 是带着原因的那段话),没给用 instruction;
|
||||
画布上用户说的是流程,不判。"""
|
||||
retry = "这个工作流上一次运行没有成功:用满了步数。\n\n请针对这个原因改它,改完继续回答原来的问题:上周销售额多少"
|
||||
assert _question_of(GenerateIn(instruction=retry, intent="answer", question="上周销售额多少")) == "上周销售额多少"
|
||||
assert _question_of(GenerateIn(instruction="上周销售额为什么下降", intent="answer")) == "上周销售额为什么下降"
|
||||
assert _question_of(GenerateIn(instruction="做一个分析销售额为什么下降的流程")) is None
|
||||
|
||||
|
||||
def test_the_chat_drivers_pass_the_original_question():
|
||||
from app.chat.drive import TurnDriver
|
||||
|
||||
driver = TurnDriver("上周销售额为什么下降", datasource_ids=[])
|
||||
payload = driver.generate_in("这个工作流上一次运行没有成功:…改完继续回答原来的问题:上周销售额为什么下降", None)
|
||||
assert payload.question == "上周销售额为什么下降" and payload.intent == "answer"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 报告的证据来源认分析卡
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_an_analysis_card_counts_as_an_evidence_source():
|
||||
card = GraphNode.model_validate({"id": "check", "type": "analysis", "data": {"label": "异动分析卡", "config": {}}})
|
||||
assert card.type == NodeType.ANALYSIS and _evidence_source(card)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 自查:分析类问题,查库的 Agent 要绑分析工具(只挡一轮)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _n(nid: str, ntype: str, **config) -> dict:
|
||||
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}}
|
||||
|
||||
|
||||
def _graph(*, tools=("db_query__shop", "db_schema__shop"), card=False):
|
||||
nodes = {"start": _n("start", "input"),
|
||||
"bot": _n("bot", "agent", prompt="{{ input.question }}", tools=list(tools)),
|
||||
"write": _n("write", "report", instructions="回答:{{ input.question }}"),
|
||||
"out": _n("out", "output", fields=[{"name": "回答", "value": "{{ nodes.write.text }}"}])}
|
||||
if card:
|
||||
nodes["check"] = _n("check", "analysis", items=[])
|
||||
order = ["start", "bot", "write", "out"]
|
||||
return nodes, [{"source": a, "target": b} for a, b in zip(order, order[1:])]
|
||||
|
||||
|
||||
async def test_an_analysis_question_without_analysis_tools_is_returned_once():
|
||||
nodes, edges = _graph()
|
||||
checker = GraphChecker(GraphApplier(nodes, edges), question="上周销售额为什么下降")
|
||||
[issue] = [i for i in await checker.issues() if i["code"] == ANALYSIS_TOOLS_MISSING]
|
||||
assert (issue["level"], issue["node_id"], issue["field"]) == ("error", "bot", "tools")
|
||||
assert issue["message"].startswith("问题问的是原因(「为什么下降」),查库的「bot」没有绑定分析工具")
|
||||
assert all(name in issue["for_model"] for name in TOOLS) and "explanation" in issue["for_model"]
|
||||
# 交回模型改过一轮:之后不再挡;收尾时作为提醒
|
||||
assert not [i for i in await checker.issues() if i["code"] == ANALYSIS_TOOLS_MISSING]
|
||||
[warning] = checker.analysis_gaps(level="warning")
|
||||
assert (warning["level"], warning["code"]) == ("warning", ANALYSIS_TOOLS_MISSING)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("question, graph", [
|
||||
("上周销售额为什么下降", _graph(tools=("db_query__shop", "db_schema__shop", "analysis_decompose"))), # 绑了一个就算
|
||||
("上周销售额为什么下降", _graph(card=True)), # 有分析卡
|
||||
("上周销售额为什么下降", _graph(tools=("current_time",))), # 没有查库的 Agent
|
||||
("上周销售额是多少", _graph()), # 不是分析类问题
|
||||
(None, _graph()), # 画布:没有问题
|
||||
])
|
||||
async def test_the_rule_stays_quiet_otherwise(question, graph):
|
||||
nodes, edges = graph
|
||||
checker = GraphChecker(GraphApplier(nodes, edges), question=question)
|
||||
assert not [i for i in await checker.issues() if i["code"] == ANALYSIS_TOOLS_MISSING]
|
||||
assert checker.analysis_gaps(level="warning") == []
|
||||
|
||||
|
||||
def _ops(tools: list[str]) -> list[dict]:
|
||||
nodes, edges = _graph(tools=tools)
|
||||
return [{"op": "plan", "summary": "查销售额"},
|
||||
*({"op": "add_node", "node": {"id": n["id"], "type": n["type"], "label": n["id"],
|
||||
"config": n["data"]["config"]}} for n in nodes.values()),
|
||||
*({"op": "add_edge", "edge": e} for e in edges), {"op": "done", "explanation": "查一下", "run": True}]
|
||||
|
||||
|
||||
def _scripted(first: list[dict], fix: list[dict], seen: list[str]):
|
||||
class Scripted:
|
||||
async def astream(self, messages):
|
||||
human = next(text for role, text in messages if role == "human")
|
||||
seen.append(human)
|
||||
for op in (fix if "上线前自查" in human else first):
|
||||
yield AIMessageChunk(content=json.dumps(op, ensure_ascii=False) + "\n")
|
||||
|
||||
return Scripted()
|
||||
|
||||
|
||||
async def test_the_stream_asks_for_one_repair_and_the_model_binds_the_tools(client, monkeypatch): # noqa: F811
|
||||
seen: list[str] = []
|
||||
fix = [{"op": "update_node", "id": "bot", "config": {"tools": ["db_query__shop", "db_schema__shop", *TOOLS]}},
|
||||
{"op": "done", "explanation": "绑上了分析工具"}]
|
||||
_use(monkeypatch, _scripted(_ops(["db_query__shop", "db_schema__shop"]), fix, seen))
|
||||
got = await _sse(client, {"instruction": "上周销售额为什么下降", "intent": "answer"})
|
||||
[repairing] = [op for op in got if op["op"] == "check" and op["status"] == "repairing"]
|
||||
assert ANALYSIS_TOOLS_MISSING in [i["code"] for i in repairing["issues"]]
|
||||
assert any("上线前自查" in h and "analysis_decompose" in h for h in seen), "交回模型改一轮"
|
||||
[final] = [op for op in got if op["op"] == "final"]
|
||||
bot = next(n for n in final["graph"]["nodes"] if n["id"] == "bot")
|
||||
assert set(TOOLS) <= set(bot["data"]["config"]["tools"])
|
||||
assert not [i for i in final["issues"] if i["code"] == ANALYSIS_TOOLS_MISSING]
|
||||
|
||||
|
||||
async def test_a_model_that_keeps_its_graph_still_runs_with_a_warning(client, monkeypatch): # noqa: F811
|
||||
seen: list[str] = []
|
||||
keep = [{"op": "done", "explanation": "这个问题其实只要一个数,不用分析"}]
|
||||
_use(monkeypatch, _scripted(_ops(["db_query__shop", "db_schema__shop"]), keep, seen))
|
||||
got = await _sse(client, {"instruction": "上周销售额为什么下降", "intent": "answer"})
|
||||
assert sum("上线前自查" in h for h in seen) == 1, "只挡一轮"
|
||||
[final] = [op for op in got if op["op"] == "final"]
|
||||
assert final["next"] == "run", "改过一轮仍在的不挡运行"
|
||||
assert [i["level"] for i in final["issues"] if i["code"] == ANALYSIS_TOOLS_MISSING] == ["warning"]
|
||||
|
||||
|
||||
async def test_a_retry_reads_the_original_question(client, monkeypatch): # noqa: F811
|
||||
"""重来时 instruction 是带着原因的那段话(里面有「原因」两个字):按原问题判,原问题不是分析类就不提。"""
|
||||
seen: list[str] = []
|
||||
_use(monkeypatch, _scripted(_ops(["db_query__shop", "db_schema__shop"]), [], seen))
|
||||
retry = "这个工作流上一次运行没有成功:用满了步数。\n\n请针对这个原因改它,改完继续回答原来的问题:上周销售额多少"
|
||||
got = await _sse(client, {"instruction": retry, "intent": "answer", "question": "上周销售额多少"})
|
||||
assert not [op for op in got if op["op"] == "check" and op["status"] == "repairing"]
|
||||
[final] = [op for op in got if op["op"] == "final"]
|
||||
assert not [i for i in final["issues"] if i["code"] == ANALYSIS_TOOLS_MISSING]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 关掉分析工具(评测「分析工具开、关」对照的「关」那一臂:answer_ops 的 analysis_tools、TurnDriver 的同名属性)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_catalog_and_the_manual_leave_analysis_out_when_switched_off():
|
||||
assert all(f"- {name}(" in _tool_catalog([]) for name in TOOLS)
|
||||
off = _tool_catalog([], analysis_tools=False)
|
||||
assert not [line for line in off.splitlines() if line.startswith("- analysis_")]
|
||||
assert off == "\n".join(line for line in _tool_catalog([]).splitlines() if not line.startswith("- analysis_"))
|
||||
assert node_reference() is NODE_REFERENCE
|
||||
manual = node_reference(analysis_tools=False)
|
||||
assert not any(name in manual for name in TOOLS)
|
||||
# 去掉的是 agent 段里「分析类问题绑分析工具」那一条、分析卡一整条、搭图规则第 7 条;报告段的引用写法、受管规则照留
|
||||
assert "- analysis:" not in manual and "\n7. " not in manual and "**问题问的是为什么" not in manual
|
||||
# 别的段落一字不少:只去掉那三段
|
||||
for kept in (" **默认不要写 max_steps", "- dual_check:", "\n模型字段", "- report:", "[[a:A1]]", "analysis_claims"):
|
||||
assert kept in manual, kept
|
||||
request = GenerateIn(instruction="上周销售额为什么下降", intent="answer")
|
||||
on, off_text = _user_message(request, patch=False), _user_message(request, patch=False, analysis_tools=False)
|
||||
assert ANALYSIS_SHAPE_PROMPT in on and ANALYSIS_SHAPE_PROMPT not in off_text
|
||||
assert on.replace(ANALYSIS_SHAPE_PROMPT, "") == off_text
|
||||
|
||||
|
||||
def _recording(first: list[dict], fix: list[dict], seen: list[list[tuple[str, str]]]):
|
||||
class Recording:
|
||||
async def astream(self, messages):
|
||||
seen.append(list(messages))
|
||||
human = next(text for role, text in messages if role == "human")
|
||||
for op in (fix if "上线前自查" in human else first):
|
||||
yield AIMessageChunk(content=json.dumps(op, ensure_ascii=False) + "\n")
|
||||
|
||||
return Recording()
|
||||
|
||||
|
||||
async def _ops_of(question: str, *, analysis_tools: bool) -> list[dict]:
|
||||
from app.api.copilot import answer_ops
|
||||
|
||||
return [op async for op in answer_ops(GenerateIn(instruction=question, intent="answer"),
|
||||
analysis_tools=analysis_tools)
|
||||
if op.get("op") not in ("heartbeat", "usage")]
|
||||
|
||||
|
||||
async def test_switched_off_the_copilot_sees_no_analysis_and_bound_tools_are_blocked(monkeypatch):
|
||||
seen: list[list[tuple[str, str]]] = []
|
||||
fix = [{"op": "update_node", "id": "bot", "config": {"tools": ["db_query__shop", "db_schema__shop"]}},
|
||||
{"op": "done", "explanation": "去掉了分析工具"}]
|
||||
_use(monkeypatch, _recording(_ops(["db_query__shop", "db_schema__shop", "analysis_decompose"]), fix, seen))
|
||||
got = await _ops_of("上周销售额为什么下降", analysis_tools=False)
|
||||
system = seen[0][0][1]
|
||||
assert seen[0][0][0] == "system" and not any(name in system for name in TOOLS)
|
||||
assert ANALYSIS_TOOLS_MISSING not in json.dumps(got, ensure_ascii=False), "问题意图那条自查不提"
|
||||
[repairing] = [op for op in got if op["op"] == "check" and op["status"] == "repairing"]
|
||||
[issue] = [i for i in repairing["issues"] if i["code"] == ANALYSIS_TOOLS_OFF]
|
||||
assert issue["node_id"] == "bot" and issue["message"].startswith("绑定的工具不存在:「bot」绑定的 analysis_decompose")
|
||||
[final] = [op for op in got if op["op"] == "final"]
|
||||
assert final["next"] == "run" and not [i for i in final["issues"] if i["code"] == ANALYSIS_TOOLS_OFF]
|
||||
|
||||
# 改不好:照实列出、不运行
|
||||
seen.clear()
|
||||
_use(monkeypatch, _recording(_ops(["db_query__shop", "analysis_decompose"]), [{"op": "done", "explanation": "x"}],
|
||||
seen))
|
||||
got = await _ops_of("上周销售额为什么下降", analysis_tools=False)
|
||||
[final] = [op for op in got if op["op"] == "final"]
|
||||
assert final["next"] == "fail" and [i["level"] for i in final["issues"] if i["code"] == ANALYSIS_TOOLS_OFF] == ["error"]
|
||||
|
||||
|
||||
async def test_switched_on_bound_analysis_tools_are_fine(monkeypatch):
|
||||
"""缺省开着:绑了分析工具不挡,和以前一样直接运行。"""
|
||||
seen: list[list[tuple[str, str]]] = []
|
||||
_use(monkeypatch, _recording(_ops(["db_query__shop", "db_schema__shop", *TOOLS]), [], seen))
|
||||
got = await _ops_of("上周销售额为什么下降", analysis_tools=True)
|
||||
assert all(name in seen[0][0][1] for name in TOOLS)
|
||||
assert not [op for op in got if op["op"] == "check" and op["status"] == "repairing"]
|
||||
[final] = [op for op in got if op["op"] == "final"]
|
||||
assert final["next"] == "run"
|
||||
|
||||
|
||||
async def test_other_turns_go_the_same_either_way(monkeypatch):
|
||||
"""没碰分析工具的一轮(不是分析类问题、图里没绑分析工具):开、关两臂交出的操作逐条一样,差的只是给助手看的那几段。"""
|
||||
runs = {}
|
||||
for flag in (True, False):
|
||||
seen: list[list[tuple[str, str]]] = []
|
||||
_use(monkeypatch, _recording(_ops(["db_query__shop", "db_schema__shop"]), [], seen))
|
||||
runs[flag] = (await _ops_of("上周销售额是多少", analysis_tools=flag), seen[0])
|
||||
assert runs[True][0] == runs[False][0]
|
||||
(_, system_on), (_, human_on) = runs[True][1]
|
||||
(_, system_off), (_, human_off) = runs[False][1]
|
||||
assert human_on.replace(ANALYSIS_SHAPE_PROMPT, "") == human_off and system_on != system_off
|
||||
|
||||
|
||||
async def test_the_turn_driver_passes_the_switch_through(monkeypatch):
|
||||
import app.api.copilot as copilot
|
||||
from app.chat.drive import TurnDriver
|
||||
|
||||
calls: list[dict] = []
|
||||
|
||||
async def fake_ops(payload, **kwargs):
|
||||
calls.append({"question": payload.question, **kwargs})
|
||||
yield {"op": "reply", "text": "上一轮已经查过了。"}
|
||||
|
||||
monkeypatch.setattr(copilot, "answer_ops", fake_ops)
|
||||
assert TurnDriver("上周销售额为什么下降", datasource_ids=[]).analysis_tools is True
|
||||
driver = TurnDriver("上周销售额为什么下降", datasource_ids=[], analysis_tools=False)
|
||||
ops, refused = await driver._generate("上周销售额为什么下降", None)
|
||||
assert refused is None and ops == [{"op": "reply", "text": "上一轮已经查过了。"}]
|
||||
assert calls == [{"question": "上周销售额为什么下降", "catalog_view": None, "analysis_tools": False}]
|
||||
@@ -494,7 +494,8 @@ def test_analysis_signals_are_registered_as_gaps_that_only_need_a_note():
|
||||
assert [(s.kind, s.severity) for s in signals] == [
|
||||
("report_analysis_claims", rv.DEGRADED), ("analysis_refused", rv.DEGRADED),
|
||||
("metric_comparability_skipped", rv.DEGRADED)]
|
||||
assert {s.kind for s in signals} == rv.NOTE_ONLY
|
||||
# NOTE_ONLY 另有一种不是日志代码的:分析调用写错了一直没改对(analysis_call_failed,见 tests/test_review_analysis.py)
|
||||
assert {s.kind for s in signals} == rv.NOTE_ONLY - {rv.ANALYSIS_CALL_FAILED}
|
||||
assert not rv.should_retry(signals) and not rv.NOTE_ONLY & (rv.RETRYABLE | rv.REBUILD)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
"""复核认分析能力一轮的信号(engine/review.py,00-总方案 §3.7):只写说明、不自动重来。
|
||||
|
||||
- 几次算不了的分析(analysis_refused)并成一条「有 n 次分析没做成」,点名是哪一项、为什么(叫法取契约的 OP_LABELS,不写工具名);
|
||||
- 分析调用写错了(tool.error 带 call_error):后来同一个分析工具做成了是 Agent 改对了,不报;一直没做成的并成一条
|
||||
analysis_call_failed,同样是缺口、不重来——以前它落成 tool_error(严重、可重来),一次写错的分析会让整轮问数据重来;
|
||||
- 判断词核对重写后仍有的(report_analysis_claims)照报告节点的原话说「报告有 n 处…重写 k 次仍未改掉」;
|
||||
- 这几种信号都在 NOTE_ONLY 里:全是它们时复核不叫模型,照信号原话写说明。
|
||||
|
||||
事件是手写的,名字、数都是虚构的。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.events import EventType
|
||||
from app.engine import review as rv
|
||||
from app.tools.analysis import CALL_ERROR_HEAD, REFUSED_CODE
|
||||
|
||||
OK_OUTPUT = {"结果": "周报:销售额 45,678.5元。"}
|
||||
|
||||
|
||||
def ev(etype, **data):
|
||||
return {"type": str(etype), "node_id": data.pop("node_id", ""), "data": data}
|
||||
|
||||
|
||||
def started(node_id, label):
|
||||
return ev(EventType.NODE_STARTED, node_id=node_id, label=label)
|
||||
|
||||
|
||||
def card_refused(item="wow", op="baseline", reason="历史只有 5 期,至少要 8 期"):
|
||||
return ev(EventType.LOG, node_id="card", level="warn", code=REFUSED_CODE, item=item, op=op, reason_code="history_short",
|
||||
reason=reason, message=f"「周报分析」的分析项「{item}」没有做成:{reason}")
|
||||
|
||||
|
||||
def agent_refused(tool="analysis_decompose", reason="本期数据只到 2026-10-16,还差 2 天"):
|
||||
return ev(EventType.LOG, node_id="bot", level="warn", code=REFUSED_CODE, call_id="c1", tool=tool,
|
||||
reason_code="partial_target", reason=reason, message=f"{tool} 没有做成:{reason}")
|
||||
|
||||
|
||||
def call_error(tool="analysis_decompose", message="列「区域」在 Q1 里没有:可用的列是 地区、周、销售额", node_id="bot"):
|
||||
text = f"{CALL_ERROR_HEAD}{message}"
|
||||
return ev(EventType.TOOL_ERROR, node_id=node_id, tool=tool, call_id="c2", error=text, call_error="unknown_column")
|
||||
|
||||
|
||||
def tool_end(tool="analysis_decompose", node_id="bot"):
|
||||
return ev(EventType.TOOL_END, node_id=node_id, tool=tool, call_id="c3")
|
||||
|
||||
|
||||
TITLES = [started("card", "周报分析"), started("bot", "数据查询")]
|
||||
|
||||
|
||||
def test_one_refused_analysis_names_the_item_and_the_reason():
|
||||
[signal] = rv.scan([*TITLES, agent_refused()], OK_OUTPUT)
|
||||
assert (signal.kind, signal.severity) == (REFUSED_CODE, rv.DEGRADED)
|
||||
# 叫法照契约写「变化拆解」,不写工具名
|
||||
assert signal.detail == "「数据查询」的变化拆解没有做成:本期数据只到 2026-10-16,还差 2 天"
|
||||
assert signal.reason is None
|
||||
[signal] = rv.scan([*TITLES, card_refused()], OK_OUTPUT)
|
||||
assert signal.detail == "「周报分析」的分析项「wow」(波动基线)没有做成:历史只有 5 期,至少要 8 期"
|
||||
|
||||
|
||||
def test_several_refused_analyses_become_one_count():
|
||||
rows = [*TITLES, card_refused(), agent_refused(),
|
||||
ev(EventType.LOG, node_id="team", level="warn", code=REFUSED_CODE, agent="取数员", tool="analysis_trend",
|
||||
reason="中间缺了 2026-W30", message="取数员 的 analysis_trend 没有做成:中间缺了 2026-W30"),
|
||||
started("team", "分析团队"),
|
||||
card_refused(item="where", op="decompose", reason="按地区只有 1 段,至少要 2 段才拆得开")]
|
||||
[signal] = rv.scan(rows, OK_OUTPUT)
|
||||
assert signal.kind == REFUSED_CODE
|
||||
assert signal.detail.startswith("有 4 次分析没做成。「周报分析」的分析项「wow」(波动基线):历史只有 5 期,至少要 8 期;"
|
||||
"「数据查询」的变化拆解:本期数据只到 2026-10-16,还差 2 天;")
|
||||
assert "「分析团队」的成员「取数员」的趋势判断:中间缺了 2026-W30" in signal.detail
|
||||
assert signal.detail.endswith(";……") and len(signal.detail) <= 300
|
||||
|
||||
|
||||
def test_old_events_without_the_structured_fields_keep_their_wording():
|
||||
plain = ev(EventType.LOG, level="warn", code=REFUSED_CODE, message="「周报分析」的波动基线没有做成:历史只有 5 期")
|
||||
assert [s.detail for s in rv.scan([plain], OK_OUTPUT)] == ["「周报分析」的波动基线没有做成:历史只有 5 期"]
|
||||
two = rv.scan([plain, ev(EventType.LOG, level="warn", code=REFUSED_CODE, message="趋势判断没有做成:中间缺期")], OK_OUTPUT)
|
||||
assert [s.detail for s in two] == ["有 2 次分析没做成。「周报分析」的波动基线没有做成:历史只有 5 期;趋势判断没有做成:中间缺期"]
|
||||
|
||||
|
||||
def test_the_merged_signal_keeps_its_place_among_the_others():
|
||||
skipped = ev(EventType.LOG, level="warn", code="metric_comparability_skipped", message="指标「销售额环比」没做成可比性检查")
|
||||
claims = ev(EventType.LOG, level="warn", code="report_analysis_claims", message="报告有 1 处分析说法未通过核对")
|
||||
kinds = [s.kind for s in rv.scan([*TITLES, claims, agent_refused(), skipped, card_refused()], OK_OUTPUT)]
|
||||
assert kinds == ["report_analysis_claims", REFUSED_CODE, "metric_comparability_skipped"]
|
||||
kinds = [s.kind for s in rv.scan([*TITLES, call_error(), claims, agent_refused()], OK_OUTPUT)]
|
||||
assert kinds == [rv.ANALYSIS_CALL_FAILED, "report_analysis_claims", REFUSED_CODE]
|
||||
|
||||
|
||||
def test_a_call_error_the_agent_fixed_is_not_a_gap():
|
||||
"""Agent 照交回的说明改了参数、同一个分析工具做成了:不报(以前记成 tool_args_fixed,为一次改对的调用叫一次复核模型)。"""
|
||||
assert rv.scan([*TITLES, call_error(), tool_end()], OK_OUTPUT) == []
|
||||
|
||||
|
||||
def test_a_call_error_never_fixed_is_a_note_not_a_retry():
|
||||
"""一直没改对:那次分析没做成,是缺口不是断裂;不落成 tool_error(严重、可重来)——重来一遍 Agent 照样可能不做这项分析。"""
|
||||
[signal] = rv.scan([*TITLES, call_error()], OK_OUTPUT)
|
||||
assert (signal.kind, signal.severity) == (rv.ANALYSIS_CALL_FAILED, rv.DEGRADED)
|
||||
assert signal.detail == ("「数据查询」的变化拆解的调用写错了、一直没改对,没有做成:列「区域」在 Q1 里没有:可用的列是 地区、周、"
|
||||
"销售额")
|
||||
assert not rv.should_retry([signal]) and rv.ANALYSIS_CALL_FAILED in rv.NOTE_ONLY
|
||||
exhausted = call_error(tool="analysis_baseline", message="这个 Agent 这次执行最多做 12 次分析,已经用完:用已有的分析结论写,不再新做分析")
|
||||
[signal] = rv.scan([*TITLES, call_error(), exhausted], OK_OUTPUT)
|
||||
assert signal.detail.startswith("有 2 次分析调用写错了、一直没改对,没有做成。「数据查询」的变化拆解:列「区域」")
|
||||
assert "「数据查询」的波动基线:这个 Agent 这次执行最多做 12 次分析,已经用完" in signal.detail
|
||||
|
||||
|
||||
def test_other_failures_of_an_analysis_tool_stay_tool_errors():
|
||||
"""不是调用写错(没有 call_error:快照取不回来这类)的照旧是工具失败。"""
|
||||
broken = ev(EventType.TOOL_ERROR, node_id="bot", tool="analysis_decompose", error="工具执行失败:Q1 的查询快照已不存在")
|
||||
assert [(s.kind, s.severity) for s in rv.scan([broken], OK_OUTPUT)] == [("tool_error", rv.BROKEN)]
|
||||
|
||||
|
||||
def test_the_claims_leftover_says_how_many_are_left_after_the_rewrite():
|
||||
message = ("报告有 2 处分析说法未通过核对(1 处判断没挂分析结论、1 处原因没有依据:「主要来自」「由于」),已要求模型重写 1 次仍未"
|
||||
"改掉:判断要挂对应的分析结论并照判定写,原因要有知识库原话或运行输入作依据。报告照常产出,这几处已标注")
|
||||
[signal] = rv.scan([ev(EventType.LOG, node_id="write", level="warn", code="report_analysis_claims", count=2,
|
||||
mode="check", message=message)], OK_OUTPUT)
|
||||
assert signal.kind == "report_analysis_claims" and "报告有 2 处分析说法未通过核对" in signal.detail
|
||||
assert "重写 1 次仍未改掉" in signal.detail
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_run_with_only_analysis_gaps_gets_a_note_without_the_model():
|
||||
class Never:
|
||||
def with_structured_output(self, *_a, **_k):
|
||||
raise AssertionError("不该叫模型")
|
||||
|
||||
signals = rv.scan([*TITLES, agent_refused(), card_refused(), call_error()], OK_OUTPUT)
|
||||
result = await rv.review(Never(), question="上周销售额为什么下降", answer="答案", signals=signals, locked=True)
|
||||
assert result.verdict == "annotated" and result.retry is False and result.severity == rv.DEGRADED
|
||||
assert result.note.startswith("有 2 次分析没做成。") and "「数据查询」的变化拆解的调用写错了" in result.note
|
||||
|
||||
|
||||
def test_every_new_log_code_of_the_analysis_round_is_registered():
|
||||
"""第 1 波各包新加的分析日志代码都登记了,严重程度是缺口,不在重来的两组里。"""
|
||||
from app.engine.nodes.metrics import COMPARABILITY_SKIPPED
|
||||
|
||||
for code in (REFUSED_CODE, COMPARABILITY_SKIPPED, "report_analysis_claims"):
|
||||
assert rv.WARN_CODES[code] == (code, rv.DEGRADED), code
|
||||
assert code in rv.NOTE_ONLY and code not in rv.RETRYABLE | rv.REBUILD
|
||||
assert rv.ANALYSIS_CALL_FAILED not in rv.RETRYABLE | rv.REBUILD
|
||||
@@ -0,0 +1,156 @@
|
||||
"""内置模板「⑪ 异动分析(可追溯)」:取数(整体按周 26 周、按地区两周)→ 分析卡(波动基线 + 带总数的变化拆解)→ 报告撰写
|
||||
(分析说法严格核对)→ 出具(引用模式,单元格引用)。
|
||||
|
||||
模板既是示范也是活文档(同 tests/test_template_traceable.py 守模板 ⑨):要通过画布校验、能直接按受管级别发布(发布检查
|
||||
没有错误),接上一份虚构的零售库 shop(orders(order_date, region, amount):华东、华南、华北、西南四个地区,26 周每天一笔)
|
||||
要能从头到尾运行、两项分析都做成、完整出具。期次是每周第一天的日期,分析卡认得出每一期覆盖哪几天,本期过没过完核对得了。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import sqlite3
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
from langchain_core.messages import AIMessage
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.base import SessionLocal
|
||||
from app.db.models import Run, RunEvent
|
||||
from app.engine.governance import lint_for_publish, publish_issues
|
||||
from app.engine.runner import run_manager
|
||||
from app.engine.schema import GraphSpec, validate_graph
|
||||
from app.seed import TEMPLATES
|
||||
|
||||
NAME = "⑪ 异动分析(可追溯)"
|
||||
REGIONS = {"华东": 400, "华南": 300, "华北": 200, "西南": 100}
|
||||
|
||||
|
||||
def template() -> dict:
|
||||
return next(t for t in TEMPLATES if t["name"] == NAME)
|
||||
|
||||
|
||||
def graph() -> dict:
|
||||
t = template()
|
||||
return copy.deepcopy({"nodes": t["nodes"], "edges": t["edges"]})
|
||||
|
||||
|
||||
def test_the_template_is_listed_once_after_the_others():
|
||||
names = [t["name"] for t in TEMPLATES]
|
||||
assert names.count(NAME) == 1 and names[-1] == NAME
|
||||
assert any(n.startswith("⑨ 可追溯周报") for n in names)
|
||||
|
||||
|
||||
def test_the_template_passes_validation():
|
||||
report = validate_graph(GraphSpec.model_validate(graph()))
|
||||
assert report.ok, [i.message for i in report.issues if i.level == "error"]
|
||||
types = {n["id"]: n["type"] for n in template()["nodes"]}
|
||||
assert list(types.values()).count("analysis") == 1 and "metrics" not in types.values()
|
||||
card = next(n for n in template()["nodes"] if n["type"] == "analysis")["data"]["config"]
|
||||
assert [(i["id"], i["op"], i.get("mode")) for i in card["items"]] == [("wow", "baseline", None),
|
||||
("where", "decompose", "additive")]
|
||||
assert card["items"][1]["params"]["headline"] == {"base": "weekly.r1.销售额", "target": "weekly.r0.销售额"}
|
||||
assert "overrides" not in card, "阈值取设置,模板不写死"
|
||||
|
||||
|
||||
def test_the_template_publishes_as_governed():
|
||||
"""拿来就能按受管级别发布:发布检查(和真正发布同一套)没有错误,证据门禁 G1–G5 和分析卡的受管规则都过。"""
|
||||
spec = GraphSpec.model_validate(graph())
|
||||
errors = [i for i in publish_issues(spec, level="governed") if i.level == "error"]
|
||||
assert errors == [], [i.message for i in errors]
|
||||
report = next(n for n in template()["nodes"] if n["type"] == "report")["data"]["config"]
|
||||
assert {k: report[k] for k in ("numbers", "on_violation", "claims", "analysis_claims")} == {
|
||||
"numbers": "strict", "on_violation": "fail", "claims": "require_citation", "analysis_claims": "strict"}
|
||||
out = next(n for n in template()["nodes"] if n["type"] == "output")["data"]["config"]
|
||||
assert out["contract"] == {"report_from": "write", "cells": True, "strict": True}
|
||||
assert out["fields"] == [{"name": "异动分析", "value": "{{ nodes.write.text }}"}]
|
||||
|
||||
|
||||
def test_template_nine_also_publishes_as_governed():
|
||||
"""模板 ⑨ 在第 1 波补了分析说法核对设为严格:同样直接按受管级别发布,没有错误。"""
|
||||
nine = next(t for t in TEMPLATES if t["name"].startswith("⑨"))
|
||||
spec = GraphSpec.model_validate(copy.deepcopy({"nodes": nine["nodes"], "edges": nine["edges"]}))
|
||||
errors = [i for i in publish_issues(spec, level="governed") if i.level == "error"]
|
||||
assert errors == [], [i.message for i in errors]
|
||||
assert not [i for i in lint_for_publish(spec, level="governed").issues if i.code == "governed.report_policy"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 接一份虚构的零售库从头到尾运行
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _last_week() -> date:
|
||||
"""最近一个已经过完的整周的周一(运行当天往前,本周没过完)。"""
|
||||
today = date.today()
|
||||
return today - timedelta(days=today.weekday() + 7)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def shop(tmp_path, scratch_source):
|
||||
"""26 周、每个地区每天一笔:各周略有起伏;最后一周(最近一个过完的整周)华东掉了四成,别的地区照常。"""
|
||||
monday = _last_week()
|
||||
first = monday - timedelta(weeks=25)
|
||||
path = tmp_path / "shop.db"
|
||||
db = sqlite3.connect(path)
|
||||
db.executescript("CREATE TABLE orders (id INTEGER PRIMARY KEY, order_date TEXT, region TEXT, amount REAL);")
|
||||
rows, n = [], 0
|
||||
for week in range(26):
|
||||
for day in range(7):
|
||||
when = first + timedelta(weeks=week, days=day)
|
||||
for k, (region, base) in enumerate(REGIONS.items()):
|
||||
amount = base + (week * 7 + day * 3 + k * 5) % 11
|
||||
if week == 25 and region == "华东":
|
||||
amount = round(amount * 0.6, 2)
|
||||
n += 1
|
||||
rows.append((n, when.isoformat(), region, float(amount)))
|
||||
db.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)", rows)
|
||||
db.commit()
|
||||
db.close()
|
||||
await scratch_source("shop", path)
|
||||
return monday
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def engine_up():
|
||||
await run_manager.setup()
|
||||
yield
|
||||
await run_manager.shutdown()
|
||||
|
||||
|
||||
async def _wait(run_id: str) -> Run:
|
||||
for _ in range(600):
|
||||
await asyncio.sleep(0.05)
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(Run, run_id)
|
||||
if row.status in ("succeeded", "failed") and row.manifest_seq is not None:
|
||||
return row
|
||||
raise AssertionError(f"run {run_id} 没有结束:{row.status}")
|
||||
|
||||
|
||||
async def test_the_template_runs_end_to_end_and_issues_formally(engine_up, shop, monkeypatch):
|
||||
from app.providers import mock_model
|
||||
|
||||
text = ("## 本周异动\n\n本周销售额 [[v:Q1.r0.销售额]],上周 [[v:Q1.r1.销售额]]。[[see:Q1]]\n\n"
|
||||
"[[a:A1]]。[[see:A1]]\n\n[[a:A2]]。[[see:A2]]\n\n[[table:A2 cols=地区,base,target,delta]]")
|
||||
monkeypatch.setattr(mock_model.MockChatModel, "_decide", lambda self, messages: AIMessage(content=text))
|
||||
monday = shop
|
||||
run = await run_manager.start(graph=graph(), input_payload={
|
||||
"week": monday.isoformat(), "prev_week": (monday - timedelta(weeks=1)).isoformat()})
|
||||
row = await _wait(run.id)
|
||||
assert row.status == "succeeded", row.error
|
||||
async with SessionLocal() as session:
|
||||
ends = [e.data for e in (await session.execute(
|
||||
select(RunEvent).where(RunEvent.run_id == run.id, RunEvent.type == "analysis.end")
|
||||
.order_by(RunEvent.seq))).scalars()]
|
||||
by_item = {e["item"]: e for e in ends}
|
||||
# 两项都做成了:本周的变化放回 25 周的历史里看(期次认得出、本期过完了),华东主导了这次下降(各段之和和总数闭合)
|
||||
assert by_item["wow"]["status"] == "ok", by_item["wow"]
|
||||
assert by_item["wow"]["verdict"] in ("outside_band", "far_outside_band"), by_item["wow"]
|
||||
assert (by_item["where"]["status"], by_item["where"]["verdict"]) == ("ok", "driver"), by_item["where"]
|
||||
assert "主要来自华东" in by_item["where"]["phrase"]
|
||||
issuance = row.output["_issuance"]
|
||||
assert issuance["mode"] == "citations" and issuance["tier"] == "formal", issuance
|
||||
report = row.output["异动分析"]
|
||||
assert by_item["where"]["phrase"] in report and by_item["wow"]["phrase"] in report
|
||||
Reference in New Issue
Block a user