This commit is contained in:
2026-04-27 18:02:26 +03:30
parent 7c2ec2144d
commit 190a668355
19 changed files with 193 additions and 825 deletions
+18 -228
View File
@@ -35,226 +35,24 @@ def _get_optimizer():
return apps.get_app_config("crop_simulation").get_recommendation_optimizer()
def _unique_items(items: list[str]) -> list[str]:
seen = set()
output = []
for item in items:
normalized = (item or "").strip()
if not normalized or normalized in seen:
continue
seen.add(normalized)
output.append(normalized)
return output
def _find_section(sections: list[dict], section_type: str) -> dict | None:
for section in sections:
if isinstance(section, dict) and section.get("type") == section_type:
return section
return None
def _field_sources(llm_section: dict, fallback_section: dict, merged_section: dict) -> dict[str, str]:
sources: dict[str, str] = {}
for key, value in merged_section.items():
if key == "provenance":
continue
llm_value = llm_section.get(key)
fallback_value = fallback_section.get(key)
if key in llm_section and value == llm_value and value != fallback_value:
sources[key] = "llm"
elif key in fallback_section and value == fallback_value and value != llm_value:
sources[key] = "fallback"
elif key in llm_section and key in fallback_section and llm_value == fallback_value == value:
sources[key] = "shared"
elif key in llm_section and key in fallback_section:
sources[key] = "merged"
else:
sources[key] = "fallback" if key in fallback_section else "llm"
return sources
def _attach_provenance(section_type: str, llm_section: dict, fallback_section: dict, merged_section: dict) -> dict:
merged = dict(merged_section)
field_sources = _field_sources(llm_section, fallback_section, merged)
merged["provenance"] = {
"sectionType": section_type,
"llmProvided": bool(llm_section),
"fallbackUsed": any(source != "llm" for source in field_sources.values()),
"fieldSources": field_sources,
}
return merged
def _fallback_with_provenance(fallback: dict, reason: str) -> dict:
sections = []
for section in fallback.get("sections", []):
section_with_provenance = dict(section)
section_with_provenance["provenance"] = {
"sectionType": section.get("type"),
"llmProvided": False,
"fallbackUsed": True,
"fieldSources": {
key: "fallback"
for key in section.keys()
if key != "provenance"
},
}
sections.append(section_with_provenance)
return {
"sections": sections,
"mergeMetadata": {
"source": "fallback_only",
"reason": reason,
},
}
def _build_fertilization_fallback(*, optimized_result: dict | None) -> dict:
if optimized_result:
recommended = optimized_result["recommended_strategy"]
list_items = [
f"دوز پیشنهادی: {recommended['amount_kg_per_ha']} کیلوگرم در هکتار",
f"روش مصرف: {recommended['application_method']}",
f"پنجره اجرا: {recommended['validity_period']}",
]
warning_text = "قبل از اختلاط یا محلول سازی، سازگاری کود با آب و شرایط مزرعه بررسی شود."
return {
"sections": [
{
"type": "recommendation",
"title": "برنامه کودهی بهینه",
"icon": "leaf",
"content": (
f"سناریوی {recommended['label']} برای این مزرعه مناسب تر ارزیابی شد."
),
"fertilizerType": recommended["fertilizer_type"],
"amount": f"{recommended['amount_kg_per_ha']} کیلوگرم در هکتار",
"applicationMethod": recommended["application_method"],
"timing": recommended["timing"],
"validityPeriod": recommended["validity_period"],
"expandableExplanation": " ".join(recommended.get("reasoning", [])),
},
{
"type": "list",
"title": "نکات اجرایی و اختلاط",
"icon": "list",
"items": _unique_items(list_items),
},
{
"type": "warning",
"title": "هشدار کودهی",
"icon": "alert-triangle",
"content": warning_text,
},
]
}
return {
"sections": [
{
"type": "recommendation",
"title": "برنامه کودهی پیشنهادی",
"icon": "leaf",
"content": "پیشنهاد کودهی بر اساس داده های فعلی با قطعیت متوسط آماده شده است.",
"fertilizerType": "کود کامل متعادل",
"amount": "پس از پایش دوباره عناصر اصلی تعیین شود",
"applicationMethod": "ترجیحا همراه آب آبیاری",
"timing": "صبح زود",
"validityPeriod": "معتبر برای 5 روز آینده",
"expandableExplanation": "به دلیل محدود بودن داده های تغذیه ای، تصمیم نهایی باید با پایش مجدد تکمیل شود.",
},
{
"type": "list",
"title": "نکات اجرایی و اختلاط",
"icon": "list",
"items": [
"قبل از مصرف، EC و pH محلول بررسی شود.",
"در صورت مشاهده بارش موثر، زمان مصرف بازبینی شود.",
],
},
{
"type": "warning",
"title": "هشدار کودهی",
"icon": "alert-triangle",
"content": "بدون بررسی دوباره مزرعه از مصرف سنگین کود خودداری شود.",
},
]
}
def _merge_fertilization_response(
*,
parsed_result: dict,
optimized_result: dict | None,
) -> dict:
fallback = _build_fertilization_fallback(optimized_result=optimized_result)
def _validate_fertilization_response(parsed_result: dict) -> dict:
if not isinstance(parsed_result, dict):
return _fallback_with_provenance(fallback, "invalid_llm_payload")
raise ValueError("Fertilization recommendation response is not a JSON object.")
sections = parsed_result.get("sections")
if not isinstance(sections, list):
return _fallback_with_provenance(fallback, "missing_sections")
if not isinstance(sections, list) or not sections:
raise ValueError("Fertilization recommendation response is missing sections.")
recommendation = _find_section(sections, "recommendation") or {}
list_section = _find_section(sections, "list") or {}
warning_section = _find_section(sections, "warning") or {}
for index, section in enumerate(sections):
if not isinstance(section, dict):
raise ValueError(f"Fertilization recommendation section {index} is invalid.")
missing = [key for key in ("type", "title", "icon") if key not in section]
if missing:
raise ValueError(
f"Fertilization recommendation section {index} is missing fields: {', '.join(missing)}"
)
fallback_recommendation = fallback["sections"][0]
fallback_list = fallback["sections"][1]
fallback_warning = fallback["sections"][2]
merged_recommendation = {**recommendation, **fallback_recommendation}
merged_recommendation["content"] = recommendation.get("content") or fallback_recommendation["content"]
merged_recommendation["title"] = recommendation.get("title") or fallback_recommendation["title"]
merged_recommendation["expandableExplanation"] = (
recommendation.get("expandableExplanation")
or fallback_recommendation["expandableExplanation"]
)
merged_list = {
**fallback_list,
**list_section,
"items": _unique_items(
list(list_section.get("items", [])) + list(fallback_list["items"])
)[:5],
}
merged_warning = {
**fallback_warning,
**warning_section,
"content": warning_section.get("content") or fallback_warning["content"],
}
merged_recommendation = _attach_provenance(
"recommendation",
recommendation,
fallback_recommendation,
merged_recommendation,
)
merged_list = _attach_provenance(
"list",
list_section,
fallback_list,
merged_list,
)
merged_warning = _attach_provenance(
"warning",
warning_section,
fallback_warning,
merged_warning,
)
return {
"sections": [merged_recommendation, merged_list, merged_warning],
"mergeMetadata": {
"source": "llm_with_fallback_merge",
"llmSectionsDetected": [section.get("type") for section in sections if isinstance(section, dict)],
"fallbackSectionsApplied": [
item["type"]
for item in (fallback_recommendation, fallback_list, fallback_warning)
],
},
}
return parsed_result
def get_fertilization_recommendation(
@@ -382,15 +180,10 @@ def get_fertilization_recommendation(
raw = response.choices[0].message.content.strip()
except Exception as exc:
logger.error("Fertilization recommendation error for %s: %s", resolved_farm_uuid, exc)
result = _build_fertilization_fallback(optimized_result=optimized_result)
result["error"] = f"خطا در دریافت توصیه: {exc}"
result["raw_response"] = None
_fail_audit_log(
audit_log,
str(exc),
response_text=json.dumps(result, ensure_ascii=False, default=str),
)
return result
_fail_audit_log(audit_log, str(exc))
raise RuntimeError(
f"Fertilization recommendation failed for farm {resolved_farm_uuid}."
) from exc
try:
cleaned = raw
@@ -400,10 +193,7 @@ def get_fertilization_recommendation(
except (json.JSONDecodeError, ValueError):
result = {}
result = _merge_fertilization_response(
parsed_result=result,
optimized_result=optimized_result,
)
result = _validate_fertilization_response(result)
result["raw_response"] = raw
result["simulation_optimizer"] = optimized_result
_complete_audit_log(