mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-24 16:12:03 +00:00
按口径正式出具与口径对账(口径账本做法 5、6,拍板 L1、L5)
为什么:问数据的答案整题等价于已发布口径时,要能按那一版发起一次完整走过门禁的正式运行(路径一、二a);只是相关、不等价时,要能看「差多少」(路径二b)。两条路都不能让客户端冒充来源、自己传参数,也不能在 Python 里算差值。
正式出具(新增 ledger/issue.py):
- POST /api/ledger/answers/{run_id}/issue {workflow_id, version}:参数只从比对工件的绑定取,补入口缺省值再过 apps/forms 校验;经 launch_run 发起正式运行,来源 ledger_issue,origin 记 source_run、conversation_id、turn_id、binding_hash、口径和认法、是否自动;按 expect_hash 钉 graph_hash。
- 不能出具照实写原因:整题不等价、点名别的口径、版本退役或没发布、图里有人工节点或写入(apps/backfill._side_effect 抽成共用的 graph_side_effect)、缺入口字段、超过每日上限、权限(L5:使用者只能按他有权使用的应用固定着的版本出具,复用应用授权,origin 记 granted_by_app;别的写「请搭建者出具」)。
- 自动出具(L1):比对完(只在运行一封存就比的那一次)整题独立等价、版本受管、设置开着、当天没超上限才自动;助手选用的只给一键。不自动的原因写进 actions 的 auto_reason。
- 同一运行、同一口径、同一组参数只发起一次(input_key 去重),进程内按(运行、工作流、版本)串行。
- 设置加 ledger 一组:自动出具开关、每日上限、比对时限(ledger/match 读它)。
口径对账(新增 ledger/reconcile.py,derive 扩 reconcile_graph / ours_block / assemble 的出口契约):
- POST /api/ledger/answers/{run_id}/reconcile:按那一版确定性派生只读图(这次的取数 ours_q1 → 口径的取数 → 口径卡 → 对账卡,出口契约 metrics_from,不加报告、不调模型),来源 reconcile 的探索运行;对账卡算这次、口径、差值、相对差。
- 参数是启发得来的、不全、含遮罩值时先让人核对(needs_check,没核对的 409);指标式不是取数一格、差异有兜底时要人选对照哪个指标,选择记进 origin。
- 多行结果:被引用的行按维度列经合并查询 LEFT JOIN 对齐、按引用先后排,最多 10 行;维度是遮罩列、合并键不唯一照实拒绝。使用者发起带 MASK_RESULTS / READ_ONLY,搭建者也带 READ_ONLY。
- GET /api/runs/{id}/ledger 的 actions 补上出具、对账两类,issued、reconciled 列出发起过的运行。
测试:tests/test_ledger_issue.py(自动出具、只给一键的几种、拒绝原因、使用者的应用授权、并发只发一次、设置)、tests/test_ledger_reconcile.py(核对参数、派生图确定与契约、差值和相对差、出处链、要人选列、多行对齐、遮罩维度和重复键拒绝、使用者只读遮罩);第 2 波 test_ledger_api 的 actions 断言按这一波改。
This commit is contained in:
@@ -3,10 +3,15 @@
|
||||
不另建存储:ActionRecord 本身带着工作流、版本、graph_hash、能力版本、payload_hash、回执;「口径 → 应用」就是固定这一版的
|
||||
应用版本。用在发布弹窗、退役确认、版本列表三处。
|
||||
|
||||
口径账本(docs/design/next-round/02-口径账本.md)在这里加两个只读接口:
|
||||
口径账本(docs/design/next-round/02-口径账本.md)在这里加的接口:
|
||||
- GET /api/runs/{run_id}/ledger(runs_router,和证据同一道门):一次运行里每个数的口径标签、整题判断、每条查询的比对、能做的
|
||||
动作(app/ledger/view.py);
|
||||
- GET /api/ledger/stats(router,搭建者):账本自身给出的统计 E1–E4,从比对工件、运行、审计现算(app/ledger/stats.py)。
|
||||
动作、出具过的正式运行、对过的账(app/ledger/view.py);
|
||||
- GET /api/ledger/stats(router,搭建者):账本自身给出的统计 E1–E4,从比对工件、运行、审计现算(app/ledger/stats.py);
|
||||
- POST /api/ledger/answers/{run_id}/issue(answers_router,登录即可,第 3 波):按口径正式出具(app/ledger/issue.py,拍板
|
||||
L1、L5:参数只从比对工件取,使用者只能按他有权使用的应用固定着的版本出具);
|
||||
- POST /api/ledger/answers/{run_id}/reconcile(同上):口径对账,点开才跑一次确定性派生的只读图(app/ledger/reconcile.py);
|
||||
- GET /api/ledger/certify-queue、POST /api/ledger/certify-queue/dismiss(router,搭建者,第 3 波):可沉淀的问题、「不是口径」
|
||||
(app/ledger/certify.py)。这几个新接口都不放给访问密钥(auth/keys.KEY_ROUTES 不登记)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,6 +20,7 @@ from typing import Any
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -100,3 +106,58 @@ async def ledger_stats(since: datetime | None = Query(default=None, description=
|
||||
|
||||
origins = [o.strip() for o in (origin or "").split(",") if o.strip()] or None
|
||||
return await compute_stats(session, since=since, until=until, origins=origins, principal=current_principal())
|
||||
|
||||
|
||||
class IssueIn(BaseModel):
|
||||
"""按哪份口径出具:只能选口径,参数由服务端从比对工件里取(不收客户端传的参数)。"""
|
||||
|
||||
workflow_id: str = Field(min_length=1, max_length=32)
|
||||
version: int = Field(ge=1)
|
||||
|
||||
|
||||
@answers_router.post("/{run_id}/issue")
|
||||
async def issue_answer(run_id: str, payload: IssueIn) -> dict[str, Any]:
|
||||
"""按口径正式出具这次问数据的答案(app/ledger/issue.py):经 launch_run 发起正式运行,来源 ledger_issue。同一运行、同一
|
||||
口径、同一组参数只发起一次,再点交回已经发起的那一次(created 为假)。不能出具时回 409(整题不等价、版本退役、有人工
|
||||
节点或写入、缺入口字段……)、403(权限不够:使用者只能按他有权使用的应用固定着的版本出具)、429(超过每日上限),
|
||||
detail 写明原因。"""
|
||||
from app.api.coded import CodedHTTPException
|
||||
from app.api.deps import current_principal
|
||||
from app.ledger import issue as ledger_issue
|
||||
|
||||
try:
|
||||
run, created = await ledger_issue.issue(run_id, payload.workflow_id, payload.version,
|
||||
principal=current_principal())
|
||||
except ledger_issue.IssueRefused as e:
|
||||
raise CodedHTTPException(e.status_code, e.message, e.code) from e
|
||||
return {"run_id": run.id, "created": created, "issued": ledger_issue.issued_view(run)}
|
||||
|
||||
|
||||
class ReconcileIn(BaseModel):
|
||||
"""对哪条查询、和哪份相关口径对账。inputs + confirm:参数要核对时(动作里 needs_check)人核对、改过的参数;pairs:认不出
|
||||
哪一列对哪个指标时人选的 [{ours: 这次的列, metric: 口径卡上的指标 id}](动作里写明要不要选)。"""
|
||||
|
||||
query: str = Field(min_length=1, max_length=64)
|
||||
workflow_id: str = Field(min_length=1, max_length=32)
|
||||
version: int = Field(ge=1)
|
||||
inputs: dict[str, Any] | None = None
|
||||
confirm: bool = False
|
||||
pairs: list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
@answers_router.post("/{run_id}/reconcile", status_code=201)
|
||||
async def reconcile_answer(run_id: str, payload: ReconcileIn) -> dict[str, Any]:
|
||||
"""口径对账(app/ledger/reconcile.py):按那一版口径确定性派生只读图,发起一次探索运行(来源 reconcile),差值在对账卡
|
||||
里算。参数是推断出来的、不全的要先核对(409,code ledger_reconcile_check_inputs);认不出列怎么配的要人选(409,
|
||||
ledger_reconcile_needs_pairs);多行时维度是遮罩列、键不唯一照实拒绝(409)。"""
|
||||
from app.api.coded import CodedHTTPException
|
||||
from app.api.deps import current_principal
|
||||
from app.ledger import reconcile as ledger_reconcile
|
||||
|
||||
try:
|
||||
run = await ledger_reconcile.reconcile(run_id, ledger_reconcile.Request(
|
||||
query=payload.query, workflow_id=payload.workflow_id, version=payload.version, inputs=payload.inputs,
|
||||
confirm=payload.confirm, pairs=payload.pairs), principal=current_principal())
|
||||
except ledger_reconcile.ReconcileRefused as e:
|
||||
raise CodedHTTPException(e.status_code, e.message, e.code) from e
|
||||
return {"run_id": run.id, "reconciled": ledger_reconcile.reconciled_view(run)}
|
||||
|
||||
@@ -718,6 +718,61 @@ async def apps_settings(session: AsyncSession) -> dict[str, Any]:
|
||||
return apps_values(row.value if row else None)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 口径账本:按口径自动正式出具的开关、每日上限,口径比对的时限(docs/design/next-round/02-口径账本.md 做法 5、2)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
#: 设置里 ledger 这一组。auto_issue:问数据的答案整题等价于受管口径(Agent 独立写的 SQL 被证明等价、版本受管、图里没有人工
|
||||
#: 节点和写入)时自动按口径发起一次正式运行(拍板 L1;不满足的只给一键)。issue_daily_limit:每天最多按口径正式出具几次
|
||||
#: (自动的、一键的合计,0 表示不再出具):正式运行含报告撰写的模型费用。match_timeout_s:一次运行的口径比对最多算几秒,
|
||||
#: 超时的照实记没比完(ledger/match.py)。召回的上限在第 4 波加。只有管理员能改(整个设置接口的改动都要管理员)
|
||||
LEDGER_GROUP = "ledger"
|
||||
LEDGER_DEFAULTS: dict[str, Any] = {"auto_issue": True, "issue_daily_limit": 20, "match_timeout_s": 8}
|
||||
LEDGER_SETTING_LABEL = {"auto_issue": "自动按口径正式出具", "issue_daily_limit": "按口径正式出具每日上限",
|
||||
"match_timeout_s": "口径比对时限(秒)"}
|
||||
#: 时限的范围:太短比不完一份口径,太长占着比对的线程
|
||||
LEDGER_TIMEOUT_RANGE = (1, 60)
|
||||
|
||||
|
||||
def _timeout_ok(value: Any) -> bool:
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool) \
|
||||
and LEDGER_TIMEOUT_RANGE[0] <= value <= LEDGER_TIMEOUT_RANGE[1]
|
||||
|
||||
|
||||
def ledger_problem(value: Any) -> str | None:
|
||||
"""设置页写进来的 ledger 这一组有什么问题,没问题返回 None。"""
|
||||
if not isinstance(value, dict):
|
||||
return f"「口径账本」设置格式有误,需要是一个对象,当前为「{value}」"
|
||||
for key, item in value.items():
|
||||
if key not in LEDGER_DEFAULTS:
|
||||
return (f"「口径账本」设置中不支持「{key}」,可设置的项:"
|
||||
+ "、".join(f"「{LEDGER_SETTING_LABEL[k]}」" for k in LEDGER_DEFAULTS))
|
||||
if key == "auto_issue" and not isinstance(item, bool):
|
||||
return f"「{LEDGER_SETTING_LABEL[key]}」只能是开或关,当前为「{item}」"
|
||||
if key == "issue_daily_limit" and not _daily_limit_ok(item):
|
||||
return (f"「{LEDGER_SETTING_LABEL[key]}」需要是 0 到 {APPS_DAILY_LIMIT_MAX:,} 之间的整数(0 表示不再按口径出具),"
|
||||
f"当前为「{item}」")
|
||||
if key == "match_timeout_s" and not _timeout_ok(item):
|
||||
return (f"「{LEDGER_SETTING_LABEL[key]}」需要是 {LEDGER_TIMEOUT_RANGE[0]} 到 {LEDGER_TIMEOUT_RANGE[1]} 之间的数,"
|
||||
f"当前为「{item}」")
|
||||
return None
|
||||
|
||||
|
||||
def ledger_values(stored: Any) -> dict[str, Any]:
|
||||
"""库里存的(或刚写进来的)ledger 一组 → 补齐默认;存坏了的项按默认(自动出具的开关存坏了按关,宁可少出具)。"""
|
||||
stored = stored if isinstance(stored, dict) else {}
|
||||
auto, limit, timeout = stored.get("auto_issue"), stored.get("issue_daily_limit"), stored.get("match_timeout_s")
|
||||
return {"auto_issue": auto if isinstance(auto, bool) else (LEDGER_DEFAULTS["auto_issue"] if auto is None else False),
|
||||
"issue_daily_limit": limit if _daily_limit_ok(limit) else LEDGER_DEFAULTS["issue_daily_limit"],
|
||||
"match_timeout_s": timeout if _timeout_ok(timeout) else LEDGER_DEFAULTS["match_timeout_s"]}
|
||||
|
||||
|
||||
async def ledger_settings(session: AsyncSession) -> dict[str, Any]:
|
||||
"""设置里的 ledger 一组,没存过的补默认。按口径出具、比对从这里读。"""
|
||||
row = await session.get(Setting, LEDGER_GROUP)
|
||||
return ledger_values(row.value if row else None)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 用户设置
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -763,6 +818,8 @@ DEFAULT_SETTINGS: dict[str, Any] = {
|
||||
CATALOG_DRAFT_GROUP: catalog_draft_values(None),
|
||||
# 应用:按需视图的每日上限、使用者能不能建个人应用(管理员在设置页改)
|
||||
APPS_GROUP: apps_values(None),
|
||||
# 口径账本:自动按口径正式出具的开关、每日上限,口径比对的时限
|
||||
LEDGER_GROUP: ledger_values(None),
|
||||
}
|
||||
|
||||
|
||||
@@ -825,6 +882,7 @@ async def get_settings(session: AsyncSession = Depends(get_session)) -> dict[str
|
||||
merged[PUBLIC_URL_GROUP] = public_url_values(stored.get(NOTIFY_GROUP))
|
||||
merged[CATALOG_DRAFT_GROUP] = catalog_draft_values(stored.get(CATALOG_DRAFT_GROUP))
|
||||
merged[APPS_GROUP] = apps_values(stored.get(APPS_GROUP))
|
||||
merged[LEDGER_GROUP] = ledger_values(stored.get(LEDGER_GROUP))
|
||||
for key, value in stored.items():
|
||||
merged.setdefault(key, value)
|
||||
return merged
|
||||
@@ -924,6 +982,10 @@ async def put_settings(
|
||||
if problem := apps_problem(payload.values[APPS_GROUP]):
|
||||
raise HTTPException(422, problem)
|
||||
payload.values[APPS_GROUP] = apps_values(payload.values[APPS_GROUP])
|
||||
if LEDGER_GROUP in payload.values:
|
||||
if problem := ledger_problem(payload.values[LEDGER_GROUP]):
|
||||
raise HTTPException(422, problem)
|
||||
payload.values[LEDGER_GROUP] = ledger_values(payload.values[LEDGER_GROUP])
|
||||
if found := await _provider_problem(session, payload.values):
|
||||
raise CodedHTTPException(422, found[1], PROVIDER_INVALID, field=found[0])
|
||||
for key, value in payload.values.items():
|
||||
|
||||
Reference in New Issue
Block a user