Files
Ai/rag/services/irrigation.py
T
2026-03-21 23:50:36 +03:30

124 lines
4.3 KiB
Python

"""
سرویس توصیه آبیاری — بدون API، قابل فراخوانی از سایر سرویس‌ها
از RAG با پایگاه دانش irrigation و لحن مخصوص آبیاری استفاده می‌کند.
"""
import json
import logging
from rag.api_provider import get_chat_client
from rag.chat import build_rag_context, _load_kb_tone
from rag.config import load_rag_config, RAGConfig
from rag.user_data import build_plant_text, build_irrigation_method_text
logger = logging.getLogger(__name__)
KB_NAME = "irrigation"
DEFAULT_IRRIGATION_PROMPT = (
"بر اساس داده‌های خاک، هواشناسی، مشخصات گیاه، روش آبیاری و پایگاه دانش آبیاری، "
"یک توصیه آبیاری دقیق بده. "
"پاسخ حتماً به فرمت JSON با ساختار زیر باشد:\n"
'{\n'
' "plan": {\n'
' "frequencyPerWeek": <int>,\n'
' "durationMinutes": <int>,\n'
' "bestTimeOfDay": "<str>",\n'
' "moistureLevel": <int>,\n'
' "warning": "<str>"\n'
' }\n'
'}\n'
"فقط JSON خروجی بده، بدون توضیح اضافی. "
"مقادیر عددی را بر اساس شرایط واقعی محاسبه کن."
)
def get_irrigation_recommendation(
sensor_uuid: str,
plant_name: str | None = None,
growth_stage: str | None = None,
irrigation_method_name: str | None = None,
query: str | None = None,
config: RAGConfig | None = None,
limit: int = 8,
) -> dict:
"""
توصیه آبیاری برای یک سنسور (کاربر).
از RAG با پایگاه دانش irrigation استفاده می‌کند.
Args:
sensor_uuid: شناسه سنسور کاربر
plant_name: نام گیاه (برای بارگذاری مشخصات از جدول Plant)
growth_stage: مرحله رشد گیاه
irrigation_method_name: نام روش آبیاری (برای بارگذاری از جدول IrrigationMethod)
query: سوال اختیاری
config: تنظیمات RAG
limit: تعداد چانک‌های بازیابی‌شده
Returns:
dict با کلیدهای irrigation_needed, amount_mm, reason, next_check_date, raw_response
"""
cfg = config or load_rag_config()
client = get_chat_client(cfg)
model = cfg.llm.model
user_query = query or "توصیه آبیاری برای مزرعه من چیست؟"
context = build_rag_context(
user_query, sensor_uuid, config=cfg, limit=limit, kb_name=KB_NAME,
)
extra_parts: list[str] = []
if plant_name and growth_stage:
plant_text = build_plant_text(plant_name, growth_stage)
if plant_text:
extra_parts.append("[اطلاعات گیاه]\n" + plant_text)
if irrigation_method_name:
method_text = build_irrigation_method_text(irrigation_method_name)
if method_text:
extra_parts.append("[روش آبیاری انتخابی]\n" + method_text)
if extra_parts:
context = "\n\n---\n\n".join(extra_parts) + ("\n\n---\n\n" + context if context else "")
tone = _load_kb_tone(KB_NAME, cfg)
system_parts = [tone] if tone else []
system_parts.append(DEFAULT_IRRIGATION_PROMPT)
if context:
system_parts.append("\n\n" + context)
system_content = "\n".join(system_parts)
messages = [
{"role": "system", "content": system_content},
{"role": "user", "content": user_query},
]
try:
response = client.chat.completions.create(
model=model,
messages=messages,
)
raw = response.choices[0].message.content.strip()
except Exception as exc:
logger.error("Irrigation recommendation error for %s: %s", sensor_uuid, exc)
return {
"irrigation_needed": None,
"amount_mm": None,
"reason": f"خطا در دریافت توصیه: {exc}",
"next_check_date": None,
"raw_response": None,
}
try:
cleaned = raw
if cleaned.startswith("```"):
cleaned = cleaned.strip("`").removeprefix("json").strip()
result = json.loads(cleaned)
except (json.JSONDecodeError, ValueError):
result = {
"plan": {
"warning": raw,
},
}
result["raw_response"] = raw
return result