feat(срез 4.3): контракт EstimateDraft→движок(strict)→verify→результат
estimate_contract.py: LLM выдаёт EstimateDraft (код+объём), движок считает числа (strict, НР/СП из resolve_nr_sp), estimate_verify проверяет. ok=False → не отдавать. Golden known-answer до копейки (итог 4380.0) + metamorphic + fail-loud. 4 теста. xlsx-выгрузка (generate_excel) — в 4.4 при подключении в чат. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
"""estimate_contract — контракт «LLM структурирует, код считает» (срез 4.3).
|
||||
|
||||
LLM выдаёт EstimateDraft (список позиций: код+объём) → детерминированный движок
|
||||
(strict) считает числа → estimate_verify проверяет → результат. LLM НИКОГДА не
|
||||
называет числа: они из движка. Не прошёл strict/verify → ok=False (не отдавать как
|
||||
готовую смету). НР/СП — из reserve_nr_sp (реальные), не хардкод.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# smeta_railway на пути (как в main.py/claude_bridge_glm)
|
||||
_SR = Path(__file__).resolve().parent.parent / "smeta-railway" / "src"
|
||||
if _SR.exists() and str(_SR) not in sys.path:
|
||||
sys.path.insert(0, str(_SR))
|
||||
|
||||
import estimate_verify # noqa: E402
|
||||
|
||||
|
||||
class DraftPosition(BaseModel):
|
||||
code: str
|
||||
qty: float
|
||||
unit: str = ""
|
||||
name: str = ""
|
||||
|
||||
|
||||
class DraftMeta(BaseModel):
|
||||
region: str = ""
|
||||
price_level: str = ""
|
||||
norm_base: str = "ФСНБ-2022"
|
||||
vat_pct: float = 22.0
|
||||
|
||||
|
||||
class EstimateDraft(BaseModel):
|
||||
meta: DraftMeta = Field(default_factory=DraftMeta)
|
||||
positions: list[DraftPosition] = Field(default_factory=list)
|
||||
|
||||
|
||||
def build_and_calc(draft: EstimateDraft, resources: dict, fgis) -> dict:
|
||||
"""EstimateDraft → расчёт движком (strict) → verify. Возвращает
|
||||
{ok, grand_total, grand_total_with_limits, missing, verify, positions_count}.
|
||||
ok=False → в смете нерассчитанные позиции или несходимость: НЕ отдавать файл."""
|
||||
from smeta_railway.calc.estimate import EstimateCalculator
|
||||
from smeta_railway.config import Section, Subsection, WorkItem
|
||||
|
||||
items = [WorkItem(code=p.code, name=p.name or p.code, unit=p.unit, qty=p.qty)
|
||||
for p in draft.positions]
|
||||
section = Section(name="Смета", subsections=[Subsection(name="", items=items)])
|
||||
calc = EstimateCalculator(fgis=fgis, resources=resources, strict=True)
|
||||
result = calc.calculate([section])
|
||||
|
||||
vp = draft.meta.vat_pct
|
||||
gt = result.grand_total
|
||||
vat = round(gt * vp / 100, 2)
|
||||
norm = {
|
||||
"positions": [{"code": p.gesn_code, "name": p.name, "unit": p.unit,
|
||||
"qty": p.qty, "total": p.total, "norm_base": draft.meta.norm_base}
|
||||
for p in result.positions if not p.unresolved],
|
||||
"totals": {"grand_total": gt, "vat_pct": vp, "vat": vat,
|
||||
"total_with_vat": round(gt + vat, 2)},
|
||||
}
|
||||
v = estimate_verify.verify(norm)
|
||||
return {
|
||||
"ok": result.ok and v["ok"],
|
||||
"grand_total": gt,
|
||||
"grand_total_with_limits": result.grand_total_with_limits,
|
||||
"missing": result.missing,
|
||||
"verify": v,
|
||||
"positions_count": len(result.positions),
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Срез 4.3: контракт EstimateDraft → движок(strict) → verify.
|
||||
|
||||
Синтетические ресурсы (golden known-answer: числа контролируем) + metamorphic + fail-loud.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent / "smeta-railway" / "src"))
|
||||
import estimate_contract as ec # noqa: E402
|
||||
from smeta_railway.data.fgis import FGISLookup # noqa: E402
|
||||
from smeta_railway.models import NormResources, MaterialResource, LaborResource # noqa: E402
|
||||
|
||||
|
||||
def _resources():
|
||||
return {"01-01-001-01": NormResources(
|
||||
norm_code="01-01-001-01", unit="м3",
|
||||
ozp=LaborResource(razryad=3.0, chel_hours=1.0),
|
||||
materials=[MaterialResource(code="M1", name="Мат", unit="кг", qty=10.0, cost_base=100.0)])}
|
||||
|
||||
|
||||
def _fgis():
|
||||
f = FGISLookup()
|
||||
f.labor_price_map["1-100-30"] = 500.0 # цена труда р.3.0 (иначе strict → missing)
|
||||
return f
|
||||
|
||||
|
||||
def _draft(qty):
|
||||
return ec.EstimateDraft(positions=[ec.DraftPosition(code="ГЭСН 01-01-001-01", unit="м3", qty=qty)])
|
||||
|
||||
|
||||
def test_resolved_draft_ok_and_computed():
|
||||
r = ec.build_and_calc(_draft(2), _resources(), _fgis())
|
||||
assert r["ok"] is True, r["missing"]
|
||||
# ОТ=1×2×500=1000; мат=10×2×100=2000; ПЗ=3000; ФОТ=1000; НР=92%→920; СП=46%→460; итог=4380
|
||||
assert r["grand_total"] == 4380.0
|
||||
assert not r["missing"]
|
||||
|
||||
|
||||
def test_metamorphic_qty_double():
|
||||
r2 = ec.build_and_calc(_draft(2), _resources(), _fgis())
|
||||
r4 = ec.build_and_calc(_draft(4), _resources(), _fgis())
|
||||
assert abs(r4["grand_total"] - 2 * r2["grand_total"]) < 0.02
|
||||
|
||||
|
||||
def test_nonexistent_code_fails_loud():
|
||||
d = ec.EstimateDraft(positions=[ec.DraftPosition(code="ГЭСН 99-01-001-01", unit="м3", qty=1)])
|
||||
r = ec.build_and_calc(d, {}, _fgis())
|
||||
assert r["ok"] is False
|
||||
assert any("99-01-001-01" in m["code"] for m in r["missing"])
|
||||
|
||||
|
||||
def test_missing_labor_price_fails_loud():
|
||||
# цена труда не задана в fgis → strict → ok=False
|
||||
r = ec.build_and_calc(_draft(2), _resources(), FGISLookup())
|
||||
assert r["ok"] is False
|
||||
assert any("труд" in m["code"] for m in r["missing"])
|
||||
Reference in New Issue
Block a user