Files
2026-11-18 18:06:22 +05:30

720 lines
28 KiB
Python

"""
AI Narrative generation, strict grounding validation, fallback, and caching.
All numbers originate exclusively from the deterministic Python metrics engine.
Any LLM output is strictly validated for:
1. JSON schema shape (headline + up to 6 bullets with metric_ids)
2. Every metric_id exists in the evidence list
3. Every number in headline/bullets matches a raw or formatted evidence value within 0.5%
4. Zero banned words/phrases (approve, approved, guarantee, safe to use, unsafe,
purchase immediately, must buy)
If AI is disabled, unavailable, times out, or fails validation after one retry,
a deterministic rule-based narrative is returned cleanly.
"""
from __future__ import annotations
import hashlib
import json
import re
from typing import Any, Optional
from sqlalchemy.orm import Session
from ..core.time_utils import utc_now
from ..models import AISummary
from .ai_metrics import _slug, format_inr
from .ai_provider import AIProvider, NoneProvider, ProviderUnavailable, get_ai_provider
from .audit import log_audit
from .settings_service import get_setting_value
BANNED_PHRASES: tuple[str, ...] = (
"approve",
"approved",
"guarantee",
"safe to use",
"unsafe",
"purchase immediately",
"must buy",
)
ALLOWED_METRIC_KEYS = ("id", "label", "value", "unit", "formatted")
ALLOWED_SUGGESTION_KEYS = ("id", "rule", "severity", "asset_codes", "evidence_metric_ids", "action_for_human")
_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
_ASSET_CODE_RE = re.compile(r"\b[A-Z]{2,10}-[A-Z0-9]{1,10}-\d{2,6}\b")
_METRIC_ID_RE = re.compile(r"\bm_[a-zA-Z0-9_]+\b")
_RULE_CODE_RE = re.compile(r"\bS[1-8]\b")
_NUMBER_RE = re.compile(r"\d+(?:\.\d+)?")
SYSTEM_PROMPT_TEMPLATE = (
"You are writing a short, factual executive note for hospital managers based strictly on "
"pre-calculated biomedical equipment metrics.\n"
"Rules you MUST follow:\n"
"1. Use ONLY the numbers present in the provided JSON evidence. Never calculate new numbers "
"or invent figures.\n"
"2. Every bullet MUST list the exact `metric_ids` from the JSON that support its numbers.\n"
"3. Do NOT recommend purchases, approvals, or clinical safety decisions. Never use the words "
"or phrases: approve, approved, guarantee, safe to use, unsafe, purchase immediately, must buy.\n"
"4. Do NOT add suggestions beyond the ones provided in the JSON.\n"
"5. Answer strictly as a single JSON object matching:\n"
'{"headline": "concise 1-sentence summary", "bullets": [{"text": "factual sentence", "metric_ids": ["m_..."]}]}\n'
"6. Include between 1 and 6 bullets."
)
def _scrub_emails(text: Any) -> str:
return _EMAIL_RE.sub("[redacted]", str(text or ""))
def _sanitize_metrics(metrics: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Whitelist strictly allowed evidence keys so PII/free text can never leak."""
clean: list[dict[str, Any]] = []
for m in metrics or []:
if not isinstance(m, dict) or not m.get("id"):
continue
clean.append(
{
"id": str(m["id"]),
"label": _scrub_emails(m.get("label", "")),
"value": m.get("value"),
"unit": str(m.get("unit", "")),
"formatted": _scrub_emails(m.get("formatted", "")),
}
)
return clean
def _sanitize_suggestions(suggestions: Optional[list[dict[str, Any]]]) -> list[dict[str, Any]]:
"""Whitelist strictly structured fields of suggestions (never free-text user input)."""
clean: list[dict[str, Any]] = []
for s in suggestions or []:
if not isinstance(s, dict) or not s.get("id"):
continue
codes = [str(c) for c in (s.get("asset_codes") or []) if isinstance(c, str)]
ev_ids = [str(eid) for eid in (s.get("evidence_metric_ids") or []) if isinstance(eid, str)]
clean.append(
{
"id": str(s["id"]),
"rule": str(s.get("rule", "")),
"severity": str(s.get("severity", "info")),
"asset_codes": codes,
"evidence_metric_ids": ev_ids,
"action_for_human": _scrub_emails(s.get("action_for_human", "")),
}
)
return clean
def build_prompt(
section: str,
metrics: list[dict[str, Any]],
suggestions: Optional[list[dict[str, Any]]] = None,
) -> tuple[str, dict[str, Any]]:
"""Build (system_prompt, privacy-safe user_json) for an AI provider."""
user_payload = {
"section": str(section),
"metrics": _sanitize_metrics(metrics),
"suggestions": _sanitize_suggestions(suggestions),
}
return SYSTEM_PROMPT_TEMPLATE, user_payload
def _extract_numbers_from_text(text: str, known_asset_codes: Optional[set[str]] = None) -> list[float]:
"""Extract numeric values from text after removing asset codes, metric IDs, ₹, and commas."""
s = str(text or "")
if known_asset_codes:
for code in sorted(known_asset_codes, key=len, reverse=True):
if code:
s = s.replace(code, " ")
s = _ASSET_CODE_RE.sub(" ", s)
s = _METRIC_ID_RE.sub(" ", s)
s = _RULE_CODE_RE.sub(" ", s)
s = s.replace("₹", " ").replace("Rs.", " ").replace("INR", " ")
s = re.sub(r"(?<=\d),(?=\d)", "", s)
numbers: list[float] = []
for tok in _NUMBER_RE.findall(s):
try:
numbers.append(float(tok))
except ValueError:
continue
return numbers
def _collect_known_numbers(
metrics: list[dict[str, Any]],
section_data: Optional[dict[str, Any]] = None,
) -> list[float]:
known: list[float] = []
for m in metrics or []:
val = m.get("value")
if isinstance(val, (int, float)) and not isinstance(val, bool):
fval = abs(float(val))
known.append(fval)
if m.get("unit") == "ratio":
known.append(abs(fval * 100.0))
fmt = m.get("formatted")
if isinstance(fmt, str) and fmt:
known.extend(_extract_numbers_from_text(fmt))
label = m.get("label")
if isinstance(label, str) and label:
known.extend(_extract_numbers_from_text(label))
if isinstance(section_data, dict):
settings_used = section_data.get("how_calculated", {}).get("settings_used") or {}
for sval in settings_used.values():
if isinstance(sval, (int, float)) and not isinstance(sval, bool):
known.append(abs(float(sval)))
return known
def _number_matches(val: float, known_numbers: list[float], rel_tol: float = 0.005) -> bool:
for ref in known_numbers:
if ref == 0.0:
if abs(val) < 1e-6:
return True
else:
if abs(val - ref) <= max(abs(ref) * rel_tol, 1e-6):
return True
return False
def _find_banned_phrase(text: str) -> Optional[str]:
lower = (text or "").lower()
for phrase in BANNED_PHRASES:
if re.search(rf"\b{re.escape(phrase)}\b", lower):
return phrase
return None
def validate_narrative(
result: Any,
metrics: list[dict[str, Any]],
known_asset_codes: Optional[set[str]] = None,
section_data: Optional[dict[str, Any]] = None,
) -> tuple[bool, Optional[str]]:
"""Validate an AI model's JSON response against shape, evidence, numbers, and banned words."""
if not isinstance(result, dict):
return False, "Model response is not a JSON object."
headline = result.get("headline")
if not isinstance(headline, str) or not headline.strip():
return False, "Missing or empty 'headline' field."
bullets = result.get("bullets")
if not isinstance(bullets, list) or len(bullets) == 0 or len(bullets) > 6:
return False, "Field 'bullets' must be a list of 1 to 6 items."
valid_metric_ids = {str(m["id"]) for m in (metrics or []) if isinstance(m, dict) and m.get("id")}
known_numbers = _collect_known_numbers(metrics, section_data=section_data)
# Check banned phrases in headline
banned = _find_banned_phrase(headline)
if banned:
return False, f"Banned phrase found in headline: '{banned}'."
# Check numbers in headline
for num in _extract_numbers_from_text(headline, known_asset_codes):
if not _number_matches(num, known_numbers):
return False, f"Unverified number in headline: {num:g}."
for idx, item in enumerate(bullets):
if not isinstance(item, dict):
return False, f"Bullet {idx + 1} is not an object."
text = item.get("text")
if not isinstance(text, str) or not text.strip():
return False, f"Bullet {idx + 1} has empty 'text'."
mids = item.get("metric_ids")
if not isinstance(mids, list) or len(mids) == 0 or not all(isinstance(x, str) and x.strip() for x in mids):
return False, f"Bullet {idx + 1} must include a non-empty list of 'metric_ids'."
for mid in mids:
if mid not in valid_metric_ids:
return False, f"Unknown metric_id referenced: '{mid}'."
banned = _find_banned_phrase(text)
if banned:
return False, f"Banned phrase found in bullet {idx + 1}: '{banned}'."
for num in _extract_numbers_from_text(text, known_asset_codes):
if not _number_matches(num, known_numbers):
return False, f"Unverified number in bullet {idx + 1}: {num:g}."
return True, None
def rule_based_narrative(
section: str,
metrics: list[dict[str, Any]],
suggestions: Optional[list[dict[str, Any]]] = None,
section_data: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
"""Build deterministic narrative headline and bullets strictly from computed evidence."""
by_id = {m["id"]: m for m in (metrics or []) if isinstance(m, dict) and m.get("id")}
bullets: list[dict[str, Any]] = []
def _has(*ids: str) -> bool:
return all(i in by_id for i in ids)
def _fmt(mid: str) -> str:
return str(by_id[mid]["formatted"])
sec = (section or "summary").strip().lower()
if sec == "comparison":
horizon_m = by_id.get("m_cmp_horizon_years")
count_m = by_id.get("m_cmp_latest_count")
horizon_val = horizon_m["value"] if horizon_m else 5
count_val = count_m["value"] if count_m else 0
headline = (
f"Evaluated {count_val} latest equipment items over a {horizon_val}-year horizon "
f"across in-house, outsourced, and rent scenarios."
)
if _has("m_cmp_inhouse_wins", "m_cmp_outsourced_wins", "m_cmp_rent_wins"):
bullets.append(
{
"text": (
f"Lowest-cost scenario split across evaluated equipment: "
f"{_fmt('m_cmp_inhouse_wins')} in-house, "
f"{_fmt('m_cmp_outsourced_wins')} outsourced (AMC/CMC), and "
f"{_fmt('m_cmp_rent_wins')} rent."
),
"metric_ids": ["m_cmp_inhouse_wins", "m_cmp_outsourced_wins", "m_cmp_rent_wins"],
}
)
rows = (section_data or {}).get("rows") or []
for row in rows:
if len(bullets) >= 6:
break
code = row.get("asset_code")
lowest_label = row.get("lowest_scenario_label")
lowest_cost = row.get("lowest_cost")
diff = row.get("savings_vs_next")
if not code or lowest_cost is None:
continue
slug = _slug(code)
low_id = f"m_cmp_lowest_{slug}"
diff_id = f"m_cmp_diff_{slug}"
if _has(low_id, diff_id) and diff is not None:
mids = [low_id, diff_id]
if "m_cmp_horizon_years" in by_id:
mids.insert(0, "m_cmp_horizon_years")
bullets.append(
{
"text": (
f"Lowest estimated {horizon_val}-year cost for {code} is "
f"{lowest_label} at {_fmt(low_id)}, {_fmt(diff_id)} below the next option."
),
"metric_ids": mids,
}
)
elif _has(low_id):
mids = [low_id]
if "m_cmp_horizon_years" in by_id:
mids.insert(0, "m_cmp_horizon_years")
bullets.append(
{
"text": (
f"Estimated {horizon_val}-year cost for {code} under {lowest_label} is "
f"{_fmt(low_id)} (other scenarios lack complete inputs)."
),
"metric_ids": mids,
}
)
elif sec == "depreciation":
headline = "Depreciated book value and cumulative maintenance cost summary for assets in scope."
if _has("m_dep_total_purchase_value", "m_dep_total_book_value"):
headline = (
f"Owned assets hold a current book value of {_fmt('m_dep_total_book_value')} "
f"against {_fmt('m_dep_total_purchase_value')} in purchase value."
)
bullets.append(
{
"text": (
f"Total purchase value is {_fmt('m_dep_total_purchase_value')}, with "
f"{_fmt('m_dep_total_book_value')} remaining book value and "
f"{_fmt('m_dep_total_accumulated')} accumulated depreciation."
if "m_dep_total_accumulated" in by_id
else f"Total purchase value is {_fmt('m_dep_total_purchase_value')} with {_fmt('m_dep_total_book_value')} current book value."
),
"metric_ids": [
mid
for mid in ("m_dep_total_purchase_value", "m_dep_total_book_value", "m_dep_total_accumulated")
if mid in by_id
],
}
)
if _has("m_dep_total_maintenance"):
bullets.append(
{
"text": f"Cumulative maintenance expenditure to date totals {_fmt('m_dep_total_maintenance')}.",
"metric_ids": ["m_dep_total_maintenance"],
}
)
if _has("m_dep_review_flag_count", "m_dep_fully_depreciated_count"):
bullets.append(
{
"text": (
f"{_fmt('m_dep_review_flag_count')} asset(s) meet or exceed the replacement review "
f"maintenance ratio, and {_fmt('m_dep_fully_depreciated_count')} asset(s) are fully depreciated."
),
"metric_ids": ["m_dep_review_flag_count", "m_dep_fully_depreciated_count"],
}
)
if _has("m_dep_excluded_count") and by_id["m_dep_excluded_count"]["value"]:
bullets.append(
{
"text": (
f"{_fmt('m_dep_excluded_count')} asset(s) were excluded from depreciation totals "
f"(rented equipment or missing valuation/date inputs)."
),
"metric_ids": ["m_dep_excluded_count"],
}
)
elif sec == "efficiency":
headline = "Equipment efficiency combines uptime, PM compliance, SLA response, and repeat-free reliability."
if _has("m_eff_score_overall", "m_eff_avg_uptime"):
headline = (
f"Overall efficiency score is {_fmt('m_eff_score_overall')} with "
f"{_fmt('m_eff_avg_uptime')} average uptime."
)
bullets.append(
{
"text": (
f"Weighted efficiency score is {_fmt('m_eff_score_overall')} across operational assets, "
f"driven by {_fmt('m_eff_avg_uptime')} average uptime."
),
"metric_ids": ["m_eff_score_overall", "m_eff_avg_uptime"],
}
)
if _has("m_eff_pm_compliance"):
bullets.append(
{
"text": f"On-time preventive maintenance compliance stands at {_fmt('m_eff_pm_compliance')}.",
"metric_ids": ["m_eff_pm_compliance"],
}
)
if _has("m_eff_mttr") and by_id["m_eff_mttr"]["value"] is not None:
mids = ["m_eff_mttr"]
extra = ""
if _has("m_eff_mtbf") and by_id["m_eff_mtbf"]["value"] is not None:
mids.append("m_eff_mtbf")
extra = f" and mean time between failures (MTBF) is {_fmt('m_eff_mtbf')}"
bullets.append(
{
"text": f"Mean time to repair (MTTR) is {_fmt('m_eff_mttr')}{extra}.",
"metric_ids": mids,
}
)
elif _has("m_eff_mtbf"):
bullets.append(
{
"text": f"Mean time between failures (MTBF) status: {_fmt('m_eff_mtbf')}.",
"metric_ids": ["m_eff_mtbf"],
}
)
elif sec in ("breakdown_frequency", "breakdown-frequency"):
headline = "Breakdown frequency and repeat-failure summary across equipment in scope."
if _has("m_bf_total_breakdowns", "m_bf_assets_in_scope", "m_bf_avg_per_equipment"):
headline = (
f"{_fmt('m_bf_total_breakdowns')} breakdowns logged across {_fmt('m_bf_assets_in_scope')} "
f"assets (average {_fmt('m_bf_avg_per_equipment')} per equipment)."
)
bullets.append(
{
"text": (
f"A total of {_fmt('m_bf_total_breakdowns')} breakdown complaints were recorded across "
f"{_fmt('m_bf_assets_in_scope')} assets, averaging {_fmt('m_bf_avg_per_equipment')} per equipment."
),
"metric_ids": ["m_bf_total_breakdowns", "m_bf_assets_in_scope", "m_bf_avg_per_equipment"],
}
)
if _has("m_bf_repeat_failure_assets"):
bullets.append(
{
"text": f"{_fmt('m_bf_repeat_failure_assets')} asset(s) are currently flagged for repeat failures.",
"metric_ids": ["m_bf_repeat_failure_assets"],
}
)
rows = (section_data or {}).get("rows") or []
if rows and rows[0].get("breakdown_count", 0) > 0:
top = rows[0]
mid = f"m_bf_count_{_slug(top['asset_code'])}"
if mid in by_id:
bullets.append(
{
"text": (
f"Highest breakdown volume in the period was on {top['asset_code']} "
f"({top.get('asset_name', '')}) with {_fmt(mid)} complaint(s)."
),
"metric_ids": [mid],
}
)
else:
# Whole-report executive summary ("summary")
headline = "Executive summary of equipment cost comparison, depreciation, efficiency, and breakdown frequency."
if _has("m_cmp_latest_count", "m_cmp_horizon_years"):
bullets.append(
{
"text": (
f"Cost comparison evaluated {_fmt('m_cmp_latest_count')} latest assets over "
f"{_fmt('m_cmp_horizon_years')}."
),
"metric_ids": ["m_cmp_latest_count", "m_cmp_horizon_years"],
}
)
if _has("m_dep_total_book_value", "m_dep_total_maintenance"):
bullets.append(
{
"text": (
f"Owned equipment book value is {_fmt('m_dep_total_book_value')} with "
f"{_fmt('m_dep_total_maintenance')} in cumulative maintenance costs."
),
"metric_ids": ["m_dep_total_book_value", "m_dep_total_maintenance"],
}
)
if _has("m_eff_score_overall", "m_eff_avg_uptime"):
bullets.append(
{
"text": (
f"Overall operational efficiency score is {_fmt('m_eff_score_overall')} "
f"with {_fmt('m_eff_avg_uptime')} average uptime."
),
"metric_ids": ["m_eff_score_overall", "m_eff_avg_uptime"],
}
)
if _has("m_bf_total_breakdowns", "m_bf_repeat_failure_assets"):
bullets.append(
{
"text": (
f"{_fmt('m_bf_total_breakdowns')} breakdowns recorded in period, with "
f"{_fmt('m_bf_repeat_failure_assets')} repeat-failure asset(s)."
),
"metric_ids": ["m_bf_total_breakdowns", "m_bf_repeat_failure_assets"],
}
)
if _has("m_sug_total_count"):
bullets.append(
{
"text": (
f"{_fmt('m_sug_total_count')} advisory suggestion(s) generated for human review."
),
"metric_ids": ["m_sug_total_count"],
}
)
# Fallback bullet if metrics were minimal or custom
if not bullets:
for m in (metrics or [])[:4]:
bullets.append(
{
"text": f"{m['label']}: {m['formatted']}.",
"metric_ids": [m["id"]],
}
)
if not bullets:
bullets.append(
{
"text": "Add cost and operational details on asset records to generate metrics for this section.",
"metric_ids": [],
}
)
return {
"headline": headline,
"bullets": bullets[:6],
}
def _sha256_canonical(obj: Any) -> str:
encoded = json.dumps(obj, sort_keys=True, default=str, ensure_ascii=False).encode("utf-8")
return hashlib.sha256(encoded).hexdigest()
def get_or_generate_narrative(
db: Session,
section: str,
filters_dict: dict[str, Any],
metrics: list[dict[str, Any]],
suggestions: Optional[list[dict[str, Any]]] = None,
*,
section_data: Optional[dict[str, Any]] = None,
user_id: Optional[int] = None,
force_regenerate: bool = False,
provider_override: Optional[AIProvider] = None,
ai_enabled_override: Optional[bool] = None,
) -> dict[str, Any]:
"""
Return a cached or freshly generated narrative for `section`.
Never raises on provider errors; always returns a complete narrative dict.
"""
provider = provider_override or get_ai_provider()
ai_enabled = (
bool(ai_enabled_override)
if ai_enabled_override is not None
else bool(get_setting_value(db, "ai_enabled", True))
)
use_ai = ai_enabled and not isinstance(provider, NoneProvider)
clean_metrics = _sanitize_metrics(metrics)
clean_suggestions = _sanitize_suggestions(suggestions)
cache_filters = {
**(filters_dict or {}),
"_use_ai": use_ai,
"_provider": provider.provider_name if use_ai else "none",
"_model": provider.model_name if use_ai else "",
}
filters_hash = _sha256_canonical(cache_filters)
data_hash = _sha256_canonical({"metrics": clean_metrics, "suggestions": clean_suggestions})
if not force_regenerate:
cached = (
db.query(AISummary)
.filter(
AISummary.section == section,
AISummary.filters_hash == filters_hash,
AISummary.data_hash == data_hash,
AISummary.validated == True,
)
.order_by(AISummary.id.desc())
.first()
)
if cached is not None:
try:
cached_data = json.loads(cached.payload_json)
if not cached_data.get("failure_reason"):
return cached_data
except ValueError:
pass
known_codes: set[str] = set()
for s in clean_suggestions:
known_codes.update(s.get("asset_codes") or [])
for r in (section_data or {}).get("rows") or []:
if isinstance(r, dict) and r.get("asset_code"):
known_codes.add(str(r["asset_code"]))
source = "rule_based"
model_used: Optional[str] = None
validated = True
failure_reason: Optional[str] = None
narrative_body: Optional[dict[str, Any]] = None
if use_ai:
model_used = provider.model_name or provider.provider_name
sys_prompt, user_payload = build_prompt(section, clean_metrics, clean_suggestions)
last_error: Optional[str] = None
for attempt in range(2):
prompt_for_attempt = sys_prompt
if attempt == 1 and last_error:
prompt_for_attempt = (
f"{sys_prompt}\n\n"
f"Your previous answer was rejected for this reason: {last_error}\n"
"Fix this issue and return strictly valid JSON."
)
try:
raw_resp = provider.generate_json(prompt_for_attempt, user_payload)
except ProviderUnavailable as exc:
last_error = str(exc)
break
except Exception as exc:
last_error = f"Invalid model output: {exc}"
if attempt == 0:
continue
break
ok, reason = validate_narrative(
raw_resp,
clean_metrics,
known_asset_codes=known_codes,
section_data=section_data,
)
if ok:
narrative_body = {
"headline": raw_resp["headline"].strip(),
"bullets": [
{
"text": b["text"].strip(),
"metric_ids": list(b["metric_ids"]),
}
for b in raw_resp["bullets"]
],
}
source = "ai"
validated = True
failure_reason = None
break
else:
last_error = reason or "Narrative failed validation."
if narrative_body is None:
narrative_body = rule_based_narrative(
section,
clean_metrics,
clean_suggestions,
section_data=section_data,
)
source = "rule_based"
validated = False
failure_reason = last_error or "AI provider fallback triggered."
else:
narrative_body = rule_based_narrative(
section,
clean_metrics,
clean_suggestions,
section_data=section_data,
)
source = "rule_based"
model_used = None
validated = True
failure_reason = None
generated_at = utc_now().isoformat()
payload = {
"source": source,
"model": model_used,
"validated": validated,
"failure_reason": failure_reason,
"generated_at": generated_at,
"headline": narrative_body["headline"],
"bullets": narrative_body["bullets"],
}
row = AISummary(
section=section,
filters_hash=filters_hash,
data_hash=data_hash,
source=source,
model=model_used,
validated=validated,
payload_json=json.dumps(payload, ensure_ascii=False),
created_at=utc_now(),
created_by_id=user_id,
)
db.add(row)
db.flush()
log_audit(
db,
entity_type="ai_summary",
entity_id=row.id,
action="regenerated" if force_regenerate else "generated",
changes={
"section": section,
"source": source,
"model": model_used,
"validated": validated,
"failure_reason": failure_reason,
},
user_id=user_id,
)
db.commit()
return payload