This commit is contained in:
2026-04-24 22:20:15 +03:30
parent f7dc05dc9e
commit 569d520a5c
24 changed files with 687 additions and 152 deletions
+13 -8
View File
@@ -173,19 +173,20 @@ def _merge_fertilization_response(
def get_fertilization_recommendation(
sensor_uuid: str,
farm_uuid: str | None = None,
plant_name: str | None = None,
growth_stage: str | None = None,
query: str | None = None,
config: RAGConfig | None = None,
limit: int = 8,
sensor_uuid: str | None = None,
) -> dict:
"""
توصیه کودهی برای یک سنسور (کاربر).
توصیه کودهی برای یک مزرعه.
از RAG با پایگاه دانش fertilization استفاده می‌کند.
Args:
sensor_uuid: شناسه سنسور کاربر
farm_uuid: شناسه مزرعه
plant_name: نام گیاه (برای بارگذاری مشخصات از جدول Plant)
growth_stage: مرحله رشد گیاه
query: سوال اختیاری
@@ -193,7 +194,7 @@ def get_fertilization_recommendation(
limit: تعداد چانک‌های بازیابی‌شده
Returns:
dict با کلیدهای fertilizer_needed, fertilizer_type, amount_kg_per_hectare, reason, npk_status, raw_response
dict ساختاریافته برای توصیه کودهی
"""
cfg = config or load_rag_config()
service = get_service_config(SERVICE_ID, cfg)
@@ -209,12 +210,16 @@ def get_fertilization_recommendation(
client = get_chat_client(service_cfg)
model = service.llm.model
resolved_farm_uuid = str(farm_uuid or sensor_uuid or "").strip()
if not resolved_farm_uuid:
raise ValueError("farm_uuid is required.")
user_query = query or "توصیه کودهی برای مزرعه من چیست؟"
sensor = (
SensorData.objects.select_related("center_location")
.prefetch_related("plants")
.filter(farm_uuid=sensor_uuid)
.filter(farm_uuid=resolved_farm_uuid)
.first()
)
resolved_plant_name = plant_name
@@ -246,7 +251,7 @@ def get_fertilization_recommendation(
)
context = build_rag_context(
user_query, sensor_uuid, config=cfg, limit=limit, kb_name=KB_NAME, service_id=SERVICE_ID,
user_query, resolved_farm_uuid, config=cfg, limit=limit, kb_name=KB_NAME, service_id=SERVICE_ID,
)
extra_parts: list[str] = []
@@ -276,7 +281,7 @@ def get_fertilization_recommendation(
{"role": "user", "content": user_query},
]
audit_log = _create_audit_log(
farm_uuid=sensor_uuid,
farm_uuid=resolved_farm_uuid,
service_id=SERVICE_ID,
model=model,
query=user_query,
@@ -291,7 +296,7 @@ def get_fertilization_recommendation(
)
raw = response.choices[0].message.content.strip()
except Exception as exc:
logger.error("Fertilization recommendation error for %s: %s", sensor_uuid, 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