Files
syops/backend/app/services/procurement_contract/llm_enhancer.py
T
sophie 0503ff76a6 feat(contract): 采购合同对比agent
Signed-off-by: sophie <sophie>

Signed-off-by: sophie <sophie>
2026-07-27 14:47:09 +08:00

513 lines
22 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/procurement_contract/llm_enhancer.py
Purpose: Dify Chatflow/Workflow-based comprehensive legal review for cleaned procurement contracts.
Dependencies: Config, DifyService, Agent model.
Flow: review_service passes cleaned text, structured clauses and deterministic findings; Dify Chatflow or Workflow enhances existing findings
and independently returns new legal risks, then this module validates and merges them without lowering deterministic risk.
"""
from __future__ import annotations
import json
import re
from typing import Any
from flask import current_app
from app import db
from app.core.config.settings import Config
from app.models import Agent
from app.services.dify import DifyService
MAX_FINDINGS = 20
MAX_TEXT_CHARS = 900
VALID_RISK_LEVELS = {"high", "medium", "low", "ok"}
RISK_RANK = {"ok": 0, "low": 1, "medium": 2, "high": 3}
def is_enabled() -> bool:
"""Return whether procurement-contract LLM enhancement is enabled by configuration."""
return bool(getattr(Config, "PROCUREMENT_CONTRACT_LLM_ENABLED", False))
def enhance_review_result(
result: dict[str, Any],
*,
review_no: str,
review_mode: str,
contract_type: str | None,
template_name: str | None = None,
clean_text: str = "",
structured_clauses: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
Ask Dify to enhance deterministic findings and independently scan the cleaned contract.
AI trigger timing: call after HXOPS has cleaned and structured the contract and completed Diff/rule checks.
The LLM must return JSON only; it may add risks and may challenge deterministic findings only with verified evidence.
Args:
result: HXOPS deterministic review result.
review_no/review_mode/contract_type/template_name: Review context passed to Dify.
clean_text: Cleaned contract Markdown text; never pass a server-local path.
structured_clauses: Full ordered clause list generated by HXOPS.
Returns:
Result with enhanced existing findings, validated new_items and Dify audit metadata.
"""
if not is_enabled():
return result
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
clean_text = str(clean_text or "").strip()
structured_clauses = structured_clauses or []
if not clean_text or not structured_clauses:
return _with_llm_meta(result, enabled=True, status="skipped", message="cleaned contract is unavailable")
agent = _resolve_agent()
if not agent:
return _with_llm_meta(result, enabled=True, status="skipped", message="LLM agent is not configured")
findings = _build_findings_payload(clauses)
max_text_chars = max(int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS", 120000) or 120000), 10000)
max_clauses = max(int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES", 160) or 160), 20)
sent_text = clean_text[:max_text_chars]
sent_clauses = structured_clauses[:max_clauses]
input_truncated = len(clean_text) > len(sent_text) or len(structured_clauses) > len(sent_clauses)
inputs = {
"review_no": review_no,
"review_mode": review_mode,
"contract_type": contract_type or "general_procurement",
"template_name": template_name or "",
"findings_json": json.dumps(findings, ensure_ascii=False),
"clauses_json": json.dumps(sent_clauses, ensure_ascii=False),
"clean_text": sent_text,
"scan_enabled": "true",
"scan_scope": "bounded_contract" if input_truncated else "full_contract",
"instruction": _review_instruction(),
}
try:
timeout = (
int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS", 5) or 5),
int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS", 120) or 120),
)
provider = _review_provider(agent)
if provider == "chatflow":
response = DifyService.run_chatflow_once(
agent=agent,
query=_chatflow_review_query(),
inputs=inputs,
user=f"contract-review:{review_no}",
timeout=timeout,
)
enhancements, new_items = _extract_review_output({"answer": response.get("answer")})
workflow_run_id = str(response.get("message_id") or "") or None
else:
response = DifyService.run_workflow_streaming(
agent=agent,
inputs=inputs,
user=f"contract-review:{review_no}",
timeout=timeout,
)
enhancements, new_items = _extract_review_output(response)
workflow_run_id = _workflow_run_id(response)
except Exception as exc: # noqa: BLE001 - enhancement must not fail deterministic review
if current_app:
current_app.logger.warning("[contract-llm] enhance failed review_no=%s err=%s", review_no, exc)
return _with_llm_meta(result, enabled=True, status="failed", message=str(exc)[:500])
if not enhancements and not new_items:
return _with_llm_meta(result, enabled=True, status="empty", message="LLM returned no usable review items")
merged = _merge_review_output(
result,
enhancements,
new_items,
clean_text=clean_text,
structured_clauses=structured_clauses,
)
summary = merged.get("summary_json") if isinstance(merged.get("summary_json"), dict) else {}
summary["llm_input"] = {
"text_characters": len(clean_text),
"sent_text_characters": len(sent_text),
"clause_count": len(structured_clauses),
"sent_clause_count": len(sent_clauses),
"truncated": input_truncated,
}
merged["summary_json"] = summary
return _with_llm_meta(
merged,
enabled=True,
status="success",
message="Dify comprehensive review applied",
provider=provider,
workflow_run_id=workflow_run_id,
)
def _resolve_agent() -> Agent | None:
"""Resolve the configured Dify Chatflow or Workflow agent used for contract review."""
agent_id = int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_AGENT_ID", 0) or 0)
if agent_id:
row = db.session.get(Agent, agent_id)
if row and row.is_active and row.dify_api_key:
return row
app_id = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID", "") or "").strip()
if app_id:
row = db.session.query(Agent).filter(Agent.dify_app_id == app_id, Agent.is_active.is_(True)).first()
if row and row.dify_api_key:
return row
api_key = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY", "") or "").strip()
if api_key:
return Agent(
id=0,
name="Procurement Contract LLM Enhancer",
dify_api_key=api_key,
api_base_url=str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_BASE", "") or "").strip() or Config.DIFY_API_BASE,
dify_app_type="workflow",
)
return None
def _review_provider(agent: Agent) -> str:
"""Return the configured Dify provider; env override supports reusing a Chatflow during rollout."""
configured = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_PROVIDER", "agent") or "agent").strip().lower()
if configured in {"chatflow", "workflow"}:
return configured
app_type = str(getattr(agent, "dify_app_type", "") or "").strip().lower()
return "chatflow" if app_type == "chatflow" else "workflow"
def _chatflow_review_query() -> str:
"""
提供给 Chatflow 的一次性任务提示;正式合同内容均通过 Start inputs 传入。
Chatflow 可以沿用普通会话应用,但必须在画布中识别该指令并只输出 JSON,
否则后端会把非 JSON 回答标为无可用审核项。
"""
return "执行合同全面审核任务。请严格根据 Start 输入变量返回 instruction 要求的 JSON,不要输出解释性文字。"
def _build_findings_payload(clauses: list[Any]) -> list[dict[str, Any]]:
"""Build compact findings for LLM consumption without sending the whole contract."""
findings: list[dict[str, Any]] = []
for idx, raw in enumerate(clauses[:MAX_FINDINGS], start=1):
if not isinstance(raw, dict):
continue
findings.append(
{
"id": str(raw.get("clause_no") or idx),
"title": str(raw.get("title") or raw.get("clause_category") or f"finding-{idx}")[:120],
"change_type": str(raw.get("change_type") or ""),
"rule_risk_level": str(raw.get("risk_level") or ""),
"category": str(raw.get("clause_category") or ""),
"rule_detail": _clip(raw.get("detail")),
"rule_risk_hint": _clip(raw.get("risk_hint")),
"rule_suggestion": _clip(raw.get("suggestion")),
"template_excerpt": _clip(raw.get("old_text"), 450),
"contract_excerpt": _clip(raw.get("new_text"), 450),
}
)
return findings
def _review_instruction() -> str:
"""Build the versioned instruction consumed by the Chatflow review branch's LLM node."""
# [PROMPT_UPDATE] 2026-07-21: 增加带原文证据和置信度门槛的 confirm/reject/uncertain 纠错协议。
return (
"你是企业采购方合同审核助手。输入包含 clean_text、clauses_json、findings_json。"
"必须逐条覆盖 clauses_json,并结合全文检查付款、交付、验收、质保、违约赔偿、免责、"
"责任上限、知识产权、保密数据、解除续期、不可抗力、争议解决以及跨条款冲突。"
"items 用于增强 findings_json 已有项;new_items 用于返回后端未发现的新风险。"
"每个 new_item 必须引用真实 clause_id/clause_no,并给出合同原文 evidence;禁止编造法条编号。"
"返回严格 JSON:{\"items\":[{\"id\":\"1\",\"decision\":\"confirm|reject|uncertain\",\"evidence\":\"合同原文\",\"professional_reason\":\"...\","
"\"professional_suggestion\":\"...\",\"negotiation_text\":\"...\","
"\"model_risk_level\":\"high|medium|low|ok\",\"confidence\":0.0}],"
"\"new_items\":[{\"id\":\"llm-1\",\"clause_id\":\"clause-0001\","
"\"clause_no\":\"第八条\",\"title\":\"...\",\"clause_category\":\"liability\","
"\"risk_level\":\"high|medium|low\",\"professional_reason\":\"...\","
"\"business_impact\":\"...\",\"professional_suggestion\":\"...\","
"\"negotiation_text\":\"...\",\"evidence\":\"合同原文\",\"confidence\":0.0}]}."
"已有项若规则结论正确返回 confirm;若原文明确证明规则误报可返回 reject;OCR 无法确认返回 uncertain。"
"reject 必须引用能直接反驳规则结论的真实合同原文,且 confidence 不低于0.8;confidence 必须为 0 到 1。"
)
def _clip(value: Any, limit: int = MAX_TEXT_CHARS) -> str:
"""Normalize and clip text sent to or returned from the LLM."""
text = re.sub(r"\s+", " ", str(value or "")).strip()
if len(text) <= limit:
return text
return text[:limit] + "..."
def _extract_review_output(
workflow_result: dict[str, Any] | None,
) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
"""Parse Dify outputs into existing-finding enhancements and independent new risks."""
data = workflow_result if isinstance(workflow_result, dict) else {}
outputs = data.get("outputs") if isinstance(data.get("outputs"), dict) else {}
direct_output = None
if outputs.get("items") is not None or outputs.get("new_items") is not None:
direct_output = {
"items": _parse_json_candidate(outputs.get("items")) or outputs.get("items") or [],
"new_items": _parse_json_candidate(outputs.get("new_items")) or outputs.get("new_items") or [],
}
candidates = [
direct_output,
outputs.get("items"),
outputs.get("enhancements"),
outputs.get("result"),
outputs.get("text"),
outputs.get("output"),
data.get("answer"),
]
parsed: Any = None
for candidate in candidates:
parsed = _parse_json_candidate(candidate)
if parsed:
break
raw_new_items: list[Any] = []
if isinstance(parsed, dict):
raw_items = parsed.get("items") or parsed.get("enhancements") or []
raw_new_items = parsed.get("new_items") or parsed.get("newItems") or []
elif isinstance(parsed, list):
raw_items = parsed
else:
raw_items = []
out: dict[str, dict[str, Any]] = {}
for item in raw_items:
if not isinstance(item, dict):
continue
item_id = str(item.get("id") or item.get("clause_no") or "").strip()
if not item_id:
continue
confidence = _normalize_confidence(item.get("confidence"))
level = str(item.get("model_risk_level") or item.get("risk_level") or "").strip().lower()
if level not in VALID_RISK_LEVELS:
level = ""
decision = str(item.get("decision") or "confirm").strip().lower()
if decision not in {"confirm", "reject", "uncertain"}:
decision = "confirm"
out[item_id] = {
"llm_reason": _clip(item.get("professional_reason") or item.get("reason") or item.get("detail")),
"llm_suggestion": _clip(item.get("professional_suggestion") or item.get("suggestion")),
"llm_negotiation_text": _clip(item.get("negotiation_text")),
"llm_model_risk_level": level,
"llm_confidence": confidence,
"llm_decision": decision,
"llm_evidence": _clip(item.get("evidence"), 1200),
}
new_items = [item for item in raw_new_items if isinstance(item, dict)]
return out, new_items
def _parse_json_candidate(value: Any) -> Any:
"""Parse a Dify output value that may already be JSON or may be JSON text."""
if isinstance(value, (dict, list)):
return value
if not isinstance(value, str) or not value.strip():
return None
text = value.strip()
try:
return json.loads(text)
except json.JSONDecodeError:
pass
match = re.search(r"```(?:json)?\s*(.*?)```", text, flags=re.S)
if match:
try:
return json.loads(match.group(1).strip())
except json.JSONDecodeError:
return None
start = min([i for i in [text.find("{"), text.find("[")] if i >= 0], default=-1)
end = max(text.rfind("}"), text.rfind("]"))
if start >= 0 and end > start:
try:
return json.loads(text[start : end + 1])
except json.JSONDecodeError:
return None
return None
def _normalize_confidence(value: Any) -> float | None:
"""Normalize confidence to 0..1."""
try:
num = float(value)
except (TypeError, ValueError):
return None
if num > 1:
num = num / 100
return max(0.0, min(1.0, round(num, 2)))
def _normalize_evidence(value: Any) -> str:
"""归一化证据文本,供原文包含校验和结果展示。"""
return re.sub(r"\s+", "", str(value or "")).strip()
def _merge_review_output(
result: dict[str, Any],
enhancements: dict[str, dict[str, Any]],
new_items: list[dict[str, Any]],
*,
clean_text: str,
structured_clauses: list[dict[str, Any]],
) -> dict[str, Any]:
"""
合并 Dify 对已有发现的增强及其独立发现,并执行证据、去重和风险等级治理。
Args:
result: HXOPS 确定性结果。
enhancements: finding id 对应的解释增强。
new_items: Dify 独立发现的候选风险。
clean_text/structured_clauses: 用于验证 clause_id 与 evidence 是否真实存在。
Returns:
合并后的结果;证据不足项保留但标记 needs_review,便于采购人员识别不确定结论。
"""
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
for idx, clause in enumerate(clauses, start=1):
if not isinstance(clause, dict):
continue
item_id = str(clause.get("clause_no") or idx)
extra = enhancements.get(item_id)
if not extra:
continue
clause["llm_enabled"] = True
clause.update({k: v for k, v in extra.items() if v not in ("", None)})
if extra.get("llm_reason"):
clause["detail"] = extra["llm_reason"]
if extra.get("llm_suggestion"):
clause["suggestion"] = extra["llm_suggestion"]
if extra.get("llm_negotiation_text"):
clause["negotiation_text"] = extra["llm_negotiation_text"]
deterministic_level = str(clause.get("risk_level") or "ok").lower()
model_level = str(extra.get("llm_model_risk_level") or "").lower()
decision = str(extra.get("llm_decision") or "confirm")
evidence = str(extra.get("llm_evidence") or "").strip()
evidence_valid = bool(_normalize_evidence(evidence) and _normalize_evidence(evidence) in _normalize_evidence(clean_text))
confidence = extra.get("llm_confidence")
if decision == "reject" and evidence_valid and isinstance(confidence, float) and confidence >= 0.8:
clause["risk_level"] = "ok"
clause["change_type"] = "pass"
clause["validation_status"] = "confirmed"
clause["evidence"] = evidence
clause["detail"] = extra.get("llm_reason") or "原文证据表明该确定性风险未命中。"
elif decision == "uncertain":
clause["validation_status"] = "needs_review"
if evidence_valid:
clause["evidence"] = evidence
elif RISK_RANK.get(model_level, -1) > RISK_RANK.get(deterministic_level, 0):
clause["risk_level"] = model_level
clause_map = {
str(item.get("clause_id") or ""): item
for item in structured_clauses
if isinstance(item, dict) and item.get("clause_id")
}
clause_no_map = {
str(item.get("clause_no") or "").strip(): item
for item in structured_clauses
if isinstance(item, dict) and str(item.get("clause_no") or "").strip()
}
normalized_contract = _normalize_evidence(clean_text)
fingerprints = {
_normalize_evidence(
f"{item.get('clause_no') or ''}|{item.get('title') or ''}|{item.get('detail') or ''}"
)[:240]
for item in clauses
if isinstance(item, dict)
}
accepted = 0
needs_review = 0
for idx, raw in enumerate(new_items, start=1):
clause_id = str(raw.get("clause_id") or "").strip()
requested_clause_no = str(raw.get("clause_no") or "").strip()
linked_clause = clause_map.get(clause_id) or clause_no_map.get(requested_clause_no)
evidence = _clip(raw.get("evidence"), 1200)
evidence_key = _normalize_evidence(evidence)
evidence_valid = bool(evidence_key and evidence_key in normalized_contract)
clause_valid = bool(linked_clause)
title = _clip(raw.get("title") or "AI 新发现风险", 120)
reason = _clip(raw.get("professional_reason") or raw.get("legal_reason") or raw.get("reason"))
fingerprint = _normalize_evidence(
f"{raw.get('clause_no') or (linked_clause or {}).get('clause_no') or ''}|{title}|{reason}"
)[:240]
if not fingerprint or fingerprint in fingerprints:
continue
level = str(raw.get("risk_level") or raw.get("model_risk_level") or "medium").lower()
if level not in {"high", "medium", "low"}:
level = "medium"
confidence = _normalize_confidence(raw.get("confidence"))
validation_status = "confirmed" if clause_valid and evidence_valid else "needs_review"
item = {
"clause_no": str(
requested_clause_no or (linked_clause or {}).get("clause_no") or f"AI-{idx}"
),
"clause_id": clause_id or None,
"title": title,
"clause_category": str(
raw.get("clause_category") or raw.get("category") or (linked_clause or {}).get("category") or "other"
),
"change_type": "llm_scan",
"risk_level": level,
"detail": reason or "大模型识别到潜在合同风险。",
"risk_hint": reason,
"business_impact": _clip(raw.get("business_impact")),
"suggestion": _clip(raw.get("professional_suggestion") or raw.get("suggestion")),
"negotiation_text": _clip(raw.get("negotiation_text")),
"evidence": evidence,
"source": "llm",
"llm_enabled": True,
"llm_confidence": confidence,
"llm_reason": reason,
"llm_model_risk_level": level,
"validation_status": validation_status,
}
clauses.append(item)
fingerprints.add(fingerprint)
accepted += 1
if validation_status == "needs_review":
needs_review += 1
result["clauses_json"] = clauses
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_new_findings"] = {"accepted": accepted, "needs_review": needs_review}
result["summary_json"] = summary
return result
def _with_llm_meta(
result: dict[str, Any],
*,
enabled: bool,
status: str,
message: str,
provider: str | None = None,
workflow_run_id: str | None = None,
) -> dict[str, Any]:
"""Attach LLM enhancement metadata to summary_json."""
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_enhancement"] = {
"enabled": enabled,
"status": status,
"message": message,
"provider": provider,
"workflow_run_id": workflow_run_id,
}
result["summary_json"] = summary
return result
def _workflow_run_id(workflow_result: dict[str, Any] | None) -> str | None:
"""Read Dify workflow run id from gateway metadata."""
if not isinstance(workflow_result, dict):
return None
value = workflow_result.get("workflow_run_id") or workflow_result.get("id")
return str(value) if value else None