services.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. # # ==================== services.py (WITH USER VALUE REASONING) ====================
  2. # import json
  3. # import hashlib
  4. # import logging
  5. # import time
  6. # from functools import wraps
  7. # from typing import Dict, List, Optional, Tuple
  8. # import requests
  9. # from django.conf import settings
  10. # from .llm_load_balancer import call_llm_with_load_balancer
  11. # from .cache_config import (
  12. # is_caching_enabled,
  13. # ENABLE_ATTRIBUTE_EXTRACTION_CACHE,
  14. # ATTRIBUTE_CACHE_MAX_SIZE,
  15. # )
  16. # logger = logging.getLogger(__name__)
  17. # # --------------------------------------------------------------------------- #
  18. # # CACHES
  19. # # --------------------------------------------------------------------------- #
  20. # class SimpleCache:
  21. # _cache = {}
  22. # _max_size = ATTRIBUTE_CACHE_MAX_SIZE
  23. # @classmethod
  24. # def get(cls, key: str) -> Optional[Dict]:
  25. # if not ENABLE_ATTRIBUTE_EXTRACTION_CACHE: return None
  26. # return cls._cache.get(key)
  27. # @classmethod
  28. # def set(cls, key: str, value: Dict):
  29. # if not ENABLE_ATTRIBUTE_EXTRACTION_CACHE: return
  30. # if len(cls._cache) >= cls._max_size:
  31. # items = list(cls._cache.items())
  32. # cls._cache = dict(items[int(cls._max_size * 0.2):])
  33. # cls._cache[key] = value
  34. # @classmethod
  35. # def clear(cls): cls._cache.clear()
  36. # @classmethod
  37. # def get_stats(cls) -> Dict:
  38. # return {
  39. # "enabled": ENABLE_ATTRIBUTE_EXTRACTION_CACHE,
  40. # "size": len(cls._cache),
  41. # "max_size": cls._max_size,
  42. # "usage_percent": round(len(cls._cache)/cls._max_size*100, 2) if cls._max_size else 0
  43. # }
  44. # # --------------------------------------------------------------------------- #
  45. # # RETRY DECORATOR
  46. # # --------------------------------------------------------------------------- #
  47. # def retry(max_attempts=3, delay=1.0):
  48. # def decorator(f):
  49. # @wraps(f)
  50. # def wrapper(*args, **kwargs):
  51. # last_exc = None
  52. # for i in range(max_attempts):
  53. # try:
  54. # return f(*args, **kwargs)
  55. # except Exception as e:
  56. # last_exc = e
  57. # if i < max_attempts - 1:
  58. # wait = delay * (2 ** i)
  59. # logger.warning(f"Retry {i+1}/{max_attempts} after {wait}s: {e}")
  60. # time.sleep(wait)
  61. # raise last_exc or RuntimeError("Retry failed")
  62. # return wrapper
  63. # return decorator
  64. # # --------------------------------------------------------------------------- #
  65. # # MAIN SERVICE
  66. # # --------------------------------------------------------------------------- #
  67. # class ProductAttributeService:
  68. # @staticmethod
  69. # def combine_product_text(title=None, short_desc=None, long_desc=None, ocr_text=None) -> Tuple[str, Dict[str, str]]:
  70. # parts = []
  71. # source_map = {}
  72. # if title:
  73. # t = str(title).strip()
  74. # parts.append(f"Title: {t}")
  75. # source_map["title"] = t
  76. # if short_desc:
  77. # s = str(short_desc).strip()
  78. # parts.append(f"Description: {s}")
  79. # source_map["short_desc"] = s
  80. # if long_desc:
  81. # l = str(long_desc).strip()
  82. # parts.append(f"Details: {l}")
  83. # source_map["long_desc"] = l
  84. # if ocr_text:
  85. # parts.append(f"OCR Text: {ocr_text}")
  86. # source_map["ocr_text"] = ocr_text
  87. # combined = "\n".join(parts).strip()
  88. # return (combined or "No product information", source_map)
  89. # @staticmethod
  90. # def _cache_key(product_text: str, mandatory_attrs: Dict, extract_additional: bool, multiple: List[str], user_values: Dict = None) -> str:
  91. # payload = {
  92. # "text": product_text,
  93. # "attrs": mandatory_attrs,
  94. # "extra": extract_additional,
  95. # "multiple": sorted(multiple),
  96. # "user_values": user_values or {}
  97. # }
  98. # return f"attr_{hashlib.md5(json.dumps(payload, sort_keys=True).encode()).hexdigest()}"
  99. # @staticmethod
  100. # def _clean_json(text: str) -> str:
  101. # start = text.find("{")
  102. # end = text.rfind("}") + 1
  103. # if start != -1 and end > start:
  104. # text = text[start:end]
  105. # if "```json" in text:
  106. # text = text.split("```json", 1)[1].split("```", 1)[0]
  107. # elif "```" in text:
  108. # text = text.split("```", 1)[1].split("```", 1)[0]
  109. # if text.lstrip().startswith("json"): text = text[4:]
  110. # return text.strip()
  111. # @staticmethod
  112. # def format_visual_attributes(visual_attributes: Dict) -> Dict:
  113. # formatted = {}
  114. # for key, value in visual_attributes.items():
  115. # if isinstance(value, list):
  116. # formatted[key] = [{"value": str(item), "source": "image"} for item in value]
  117. # elif isinstance(value, dict):
  118. # nested = {}
  119. # for sub_key, sub_val in value.items():
  120. # if isinstance(sub_val, list):
  121. # nested[sub_key] = [{"value": str(v), "source": "image"} for v in sub_val]
  122. # else:
  123. # nested[sub_key] = [{"value": str(sub_val), "source": "image"}]
  124. # formatted[key] = nested
  125. # else:
  126. # formatted[key] = [{"value": str(value), "source": "image"}]
  127. # return formatted
  128. # # @staticmethod
  129. # # @retry(max_attempts=3, delay=1.0)
  130. # # def _call_llm(payload: dict) -> str:
  131. # # headers = {"Authorization": f"Bearer {settings.GROQ_API_KEY}", "Content-Type": "application/json"}
  132. # # resp = requests.post(settings.GROQ_API_URL, headers=headers, json=payload, timeout=30)
  133. # # resp.raise_for_status()
  134. # # return resp.json()["choices"][0]["message"]["content"]
  135. # # At the top of services.py, add this import
  136. # # from . import call_llm_with_load_balancer, get_load_balancer_stats
  137. # # Replace the existing _call_llm method with this:
  138. # @staticmethod
  139. # @retry(max_attempts=3, delay=3.0)
  140. # def _call_llm(payload: dict) -> str:
  141. # """
  142. # Call LLM using load balancer with multiple API keys
  143. # Automatically handles rate limiting and failover
  144. # """
  145. # return call_llm_with_load_balancer(payload)
  146. # @staticmethod
  147. # def extract_attributes(
  148. # product_text: str,
  149. # mandatory_attrs: Dict[str, List[str]],
  150. # source_map: Dict[str, str] = None,
  151. # model: str = None,
  152. # extract_additional: bool = True,
  153. # multiple: Optional[List[str]] = None,
  154. # use_cache: Optional[bool] = None,
  155. # user_entered_values: Optional[Dict[str, str]] = None, # NEW PARAMETER
  156. # ) -> dict:
  157. # if model is None: model = settings.SUPPORTED_MODELS[0]
  158. # if multiple is None: multiple = []
  159. # if source_map is None: source_map = {}
  160. # if user_entered_values is None: user_entered_values = {}
  161. # if use_cache is None: use_cache = ENABLE_ATTRIBUTE_EXTRACTION_CACHE
  162. # if not is_caching_enabled(): use_cache = False
  163. # cache_key = None
  164. # if use_cache:
  165. # cache_key = ProductAttributeService._cache_key(
  166. # product_text, mandatory_attrs, extract_additional, multiple, user_entered_values
  167. # )
  168. # cached = SimpleCache.get(cache_key)
  169. # if cached:
  170. # logger.info(f"CACHE HIT {cache_key[:16]}...")
  171. # return cached
  172. # # --------------------------- BUILD USER VALUES SECTION ---------------------------
  173. # user_values_section = ""
  174. # if user_entered_values:
  175. # user_lines = []
  176. # for attr, value in user_entered_values.items():
  177. # user_lines.append(f" - {attr}: {value}")
  178. # user_values_section = f"""
  179. # USER MANUALLY ENTERED VALUES:
  180. # {chr(10).join(user_lines)}
  181. # IMPORTANT INSTRUCTIONS FOR USER VALUES:
  182. # 1. Compare the user-entered value with what you find in the product text
  183. # 2. Evaluate if the user value is correct, partially correct, or incorrect for this product
  184. # 3. Choose the BEST value (could be user's value, or from allowed list, or inferred)
  185. # 4. Always provide a "reason" field explaining your decision
  186. # 5. DO NOT hallucinate - be honest if user's value seems wrong based on product evidence
  187. # 6. If user's value is not in the allowed list but seems correct, chose the most nearest value from the allowed list with proper reasoning.
  188. # """
  189. # # --------------------------- PROMPT ---------------------------
  190. # allowed_lines = [f"{attr}: {', '.join(vals)}" for attr, vals in mandatory_attrs.items()]
  191. # allowed_text = "\n".join(allowed_lines)
  192. # allowed_sources = list(source_map.keys()) + ["title", "description", "inferred"]
  193. # source_hint = "|".join(allowed_sources)
  194. # multiple_text = f"\nMULTIPLE ALLOWED FOR: {', '.join(multiple)}" if multiple else ""
  195. # print("Multiple text for attr: ")
  196. # print(multiple_text)
  197. # additional_instructions = """
  198. # For the 'additional' section, identify any other important product attributes and their values (e.g., 'Color', 'Material', 'Weight' etc) that are present in the PRODUCT TEXT but not in the Mandatory Attribute list.
  199. # For each additional attribute, use the best available value from the PRODUCT TEXT and specify the 'source'.
  200. # """ if extract_additional else ""
  201. # prompt = f"""
  202. # You are a product-attribute classifier and validator.
  203. # Understand the product text very deeply. If the same product is available somewhere online, use that knowledge to predict accurate attribute values.
  204. # Do not depend only on word-by-word matching from the product text - interpret the meaning and suggest attributes intelligently.
  205. # Pick the *closest meaning* value from the allowed list, even if not an exact word match.
  206. # I want values for all mandatory attributes.
  207. # If a value is not found anywhere, the source should be "inferred".
  208. # Note: Source means from where you have concluded the result. Choose one of these value <{source_hint}>
  209. # ALLOWED VALUES (MANDATORY):
  210. # {allowed_text}
  211. # Note: "Strictly" return multiple values for these attributes: {multiple_text}. These values must be most possible values from the list and should be max 2 values.
  212. # {user_values_section}
  213. # {additional_instructions}
  214. # PRODUCT TEXT:
  215. # {product_text}
  216. # OUTPUT (strict JSON only):
  217. # {{
  218. # "mandatory": {{
  219. # "<attr>": [{{
  220. # "value": "<chosen_value>",
  221. # "source": "<{source_hint}>",
  222. # "reason": "Explanation of why this value was chosen. If user provided a value, explain why you agreed/disagreed with it.",
  223. # "original_value": "<user_entered_value_if_provided>",
  224. # "decision": "accepted|rejected"
  225. # }}]
  226. # }},
  227. # "additional": {{
  228. # "Additional_Attr_1": [{{
  229. # "value": "Value 1",
  230. # "source": "<{source_hint}>",
  231. # "reason": "Why this attribute and value were identified"
  232. # }}]
  233. # }}
  234. # }}
  235. # RULES:
  236. # - For each mandatory attribute with a user-entered value, include "original_value" and "decision" fields
  237. # - "decision" values: "accepted" (used user's value), "rejected" (used different value), "not_provided" (no user value given)
  238. # - "reason" must explain your choice, especially when rejecting user input
  239. # - For 'additional' attributes: Strictly Extract other key attributes other than mandatory attributes from the text.
  240. # - For 'multiple' attributes, always give multiple value for those attribues, choose wisely and max 2 multiple attribute that are very close.
  241. # - Source must be one of: {source_hint}
  242. # - Be honest and specific in your reasoning.
  243. # - Return ONLY valid JSON
  244. # """
  245. # payload = {
  246. # "model": model,
  247. # "messages": [
  248. # {"role": "system", "content": "You are a JSON-only extractor and validator. Always provide clear reasoning for your decisions."},
  249. # {"role": "user", "content": prompt},
  250. # ],
  251. # "temperature": 0.3,
  252. # "max_tokens": 2000, # Increased for reasoning
  253. # }
  254. # try:
  255. # raw = ProductAttributeService._call_llm(payload)
  256. # logger.info("Raw LLM response received")
  257. # print(raw)
  258. # cleaned = ProductAttributeService._clean_json(raw)
  259. # parsed = json.loads(cleaned)
  260. # except Exception as exc:
  261. # logger.error(f"LLM failed: {exc}")
  262. # return {
  263. # "mandatory": {
  264. # a: [{
  265. # "value": "Not Specified",
  266. # "source": "llm_error",
  267. # "reason": f"LLM processing failed: {str(exc)}"
  268. # }] for a in mandatory_attrs
  269. # },
  270. # "additional": {} if not extract_additional else {},
  271. # "error": str(exc)
  272. # }
  273. # if use_cache and cache_key:
  274. # SimpleCache.set(cache_key, parsed)
  275. # logger.info(f"CACHE SET {cache_key[:16]}...")
  276. # return parsed
  277. # @staticmethod
  278. # def get_cache_stats() -> Dict:
  279. # return {
  280. # "global_enabled": is_caching_enabled(),
  281. # "result_cache": SimpleCache.get_stats(),
  282. # }
  283. # @staticmethod
  284. # def clear_all_caches():
  285. # SimpleCache.clear()
  286. # logger.info("All caches cleared")
  287. import json
  288. import hashlib
  289. import logging
  290. import time
  291. from functools import wraps
  292. from typing import Dict, List, Optional, Tuple
  293. import requests
  294. from django.conf import settings
  295. from .llm_load_balancer import call_llm_with_load_balancer
  296. from .cache_config import (
  297. is_caching_enabled,
  298. ENABLE_ATTRIBUTE_EXTRACTION_CACHE,
  299. ATTRIBUTE_CACHE_MAX_SIZE,
  300. )
  301. logger = logging.getLogger(__name__)
  302. # --------------------------------------------------------------------------- #
  303. # CACHES
  304. # --------------------------------------------------------------------------- #
  305. class SimpleCache:
  306. _cache = {}
  307. _max_size = ATTRIBUTE_CACHE_MAX_SIZE
  308. @classmethod
  309. def get(cls, key: str) -> Optional[Dict]:
  310. if not ENABLE_ATTRIBUTE_EXTRACTION_CACHE: return None
  311. return cls._cache.get(key)
  312. @classmethod
  313. def set(cls, key: str, value: Dict):
  314. if not ENABLE_ATTRIBUTE_EXTRACTION_CACHE: return
  315. if len(cls._cache) >= cls._max_size:
  316. items = list(cls._cache.items())
  317. cls._cache = dict(items[int(cls._max_size * 0.2):])
  318. cls._cache[key] = value
  319. @classmethod
  320. def clear(cls): cls._cache.clear()
  321. @classmethod
  322. def get_stats(cls) -> Dict:
  323. return {
  324. "enabled": ENABLE_ATTRIBUTE_EXTRACTION_CACHE,
  325. "size": len(cls._cache),
  326. "max_size": cls._max_size,
  327. "usage_percent": round(len(cls._cache)/cls._max_size*100, 2) if cls._max_size else 0
  328. }
  329. # --------------------------------------------------------------------------- #
  330. # RETRY DECORATOR
  331. # --------------------------------------------------------------------------- #
  332. def retry(max_attempts=3, delay=1.0):
  333. def decorator(f):
  334. @wraps(f)
  335. def wrapper(*args, **kwargs):
  336. last_exc = None
  337. for i in range(max_attempts):
  338. try:
  339. return f(*args, **kwargs)
  340. except Exception as e:
  341. last_exc = e
  342. if i < max_attempts - 1:
  343. wait = delay * (2 ** i)
  344. logger.warning(f"Retry {i+1}/{max_attempts} after {wait}s: {e}")
  345. time.sleep(wait)
  346. raise last_exc or RuntimeError("Retry failed")
  347. return wrapper
  348. return decorator
  349. # --------------------------------------------------------------------------- #
  350. # MAIN SERVICE
  351. # --------------------------------------------------------------------------- #
  352. class ProductAttributeService:
  353. @staticmethod
  354. def combine_product_text(title=None, short_desc=None, long_desc=None, ocr_text=None) -> Tuple[str, Dict[str, str]]:
  355. parts = []
  356. source_map = {}
  357. if title:
  358. t = str(title).strip()
  359. parts.append(f"Title: {t}")
  360. source_map["title"] = t
  361. if short_desc:
  362. s = str(short_desc).strip()
  363. parts.append(f"Description: {s}")
  364. source_map["short_desc"] = s
  365. if long_desc:
  366. l = str(long_desc).strip()
  367. parts.append(f"Details: {l}")
  368. source_map["long_desc"] = l
  369. if ocr_text:
  370. parts.append(f"OCR Text: {ocr_text}")
  371. source_map["ocr_text"] = ocr_text
  372. combined = "\n".join(parts).strip()
  373. return (combined or "No product information", source_map)
  374. @staticmethod
  375. def _cache_key(product_text: str, mandatory_attrs: Dict, extract_additional: bool, multiple: List[str], user_values: Dict = None) -> str:
  376. payload = {
  377. "text": product_text,
  378. "attrs": mandatory_attrs,
  379. "extra": extract_additional,
  380. "multiple": sorted(multiple),
  381. "user_values": user_values or {}
  382. }
  383. return f"attr_{hashlib.md5(json.dumps(payload, sort_keys=True).encode()).hexdigest()}"
  384. @staticmethod
  385. def _clean_json(text: str) -> str:
  386. start = text.find("{")
  387. end = text.rfind("}") + 1
  388. if start != -1 and end > start:
  389. text = text[start:end]
  390. if "```json" in text:
  391. text = text.split("```json", 1)[1].split("```", 1)[0]
  392. elif "```" in text:
  393. text = text.split("```", 1)[1].split("```", 1)[0]
  394. if text.lstrip().startswith("json"): text = text[4:]
  395. return text.strip()
  396. @staticmethod
  397. def format_visual_attributes(visual_attributes: Dict) -> Dict:
  398. formatted = {}
  399. for key, value in visual_attributes.items():
  400. if isinstance(value, list):
  401. formatted[key] = [{"value": str(item), "source": "image"} for item in value]
  402. elif isinstance(value, dict):
  403. nested = {}
  404. for sub_key, sub_val in value.items():
  405. if isinstance(sub_val, list):
  406. nested[sub_key] = [{"value": str(v), "source": "image"} for v in sub_val]
  407. else:
  408. nested[sub_key] = [{"value": str(sub_val), "source": "image"}]
  409. formatted[key] = nested
  410. else:
  411. formatted[key] = [{"value": str(value), "source": "image"}]
  412. return formatted
  413. # @staticmethod
  414. # @retry(max_attempts=3, delay=1.0)
  415. # def _call_llm(payload: dict) -> str:
  416. # headers = {"Authorization": f"Bearer {settings.GROQ_API_KEY}", "Content-Type": "application/json"}
  417. # resp = requests.post(settings.GROQ_API_URL, headers=headers, json=payload, timeout=30)
  418. # resp.raise_for_status()
  419. # return resp.json()["choices"][0]["message"]["content"]
  420. # At the top of services.py, add this import
  421. # from . import call_llm_with_load_balancer, get_load_balancer_stats
  422. # Replace the existing _call_llm method with this:
  423. @staticmethod
  424. @retry(max_attempts=3, delay=3.0)
  425. def _call_llm(payload: dict) -> str:
  426. """
  427. Call LLM using load balancer with multiple API keys
  428. Automatically handles rate limiting and failover
  429. """
  430. return call_llm_with_load_balancer(payload)
  431. @staticmethod
  432. def extract_attributes(
  433. product_text: str,
  434. mandatory_attrs: Dict[str, List[str]],
  435. source_map: Dict[str, str] = None,
  436. model: str = None,
  437. extract_additional: bool = True,
  438. multiple: Optional[List[str]] = None,
  439. use_cache: Optional[bool] = None,
  440. user_entered_values: Optional[Dict[str, str]] = None, # NEW PARAMETER
  441. ) -> dict:
  442. if model is None: model = settings.SUPPORTED_MODELS[0]
  443. if multiple is None: multiple = []
  444. if source_map is None: source_map = {}
  445. if user_entered_values is None: user_entered_values = {}
  446. if use_cache is None: use_cache = ENABLE_ATTRIBUTE_EXTRACTION_CACHE
  447. if not is_caching_enabled(): use_cache = False
  448. cache_key = None
  449. if use_cache:
  450. cache_key = ProductAttributeService._cache_key(
  451. product_text, mandatory_attrs, extract_additional, multiple, user_entered_values
  452. )
  453. cached = SimpleCache.get(cache_key)
  454. if cached:
  455. logger.info(f"CACHE HIT {cache_key[:16]}...")
  456. return cached
  457. # --------------------------- BUILD USER VALUES SECTION ---------------------------
  458. user_values_section = ""
  459. if user_entered_values:
  460. user_lines = []
  461. for attr, value in user_entered_values.items():
  462. user_lines.append(f" - {attr}: {value}")
  463. user_values_section = f"""
  464. USER MANUALLY ENTERED VALUES:
  465. {chr(10).join(user_lines)}
  466. IMPORTANT INSTRUCTIONS FOR USER VALUES:
  467. 1. Choose the BEST value (could be user's value, or from allowed list, or inferred)
  468. 2. Always provide a "reason" field explaining your decision. Your reason should be valid and from the product text. Not always exact word to be matched from the product text, you can infer understanding the product text.
  469. 3. DO NOT hallucinate - be honest if user's value seems wrong based on product evidence
  470. 4. If user's value is not in the allowed list but seems correct, chose the most nearest value from the allowed list with proper reasoning.
  471. """
  472. # --------------------------- PROMPT ---------------------------
  473. allowed_lines = [f"{attr}: {', '.join(vals)}" for attr, vals in mandatory_attrs.items()]
  474. allowed_text = "\n".join(allowed_lines)
  475. allowed_sources = list(source_map.keys()) + ["title", "description", "inferred"]
  476. source_hint = "|".join(allowed_sources)
  477. multiple_text = f"\nMULTIPLE ALLOWED FOR: {', '.join(multiple)}" if multiple else ""
  478. if extract_additional:
  479. additional_instructions = """
  480. For the 'additional' section, identify any other important product attributes and their values (e.g., 'Color', 'Material', 'Weight' etc according to the product text) that are present in the PRODUCT TEXT but not in the Mandatory Attribute list.
  481. For each additional attribute, use the best available value from the PRODUCT TEXT and specify the 'source'.
  482. Strictly Extract other key attributes other than mandatory attributes from the text.
  483. """
  484. output_example_additional = """
  485. "additional": {
  486. "Additional_Attr_1": [{
  487. "value": "Value 1",
  488. "source": "<{source_hint}>",
  489. "reason": "Why this attribute and value were identified"
  490. }]
  491. }
  492. """
  493. else:
  494. additional_instructions = """
  495. Do not identify or include any additional attributes. The 'additional' section must be an empty object {}.
  496. """
  497. output_example_additional = ' "additional": {}'
  498. prompt = f"""
  499. You are a product-attribute classifier and validator.
  500. Understand the product text very deeply. If the same product is available somewhere online, use that knowledge to predict accurate attribute values.
  501. Do not depend only on word-by-word matching from the product text - interpret the meaning and suggest attributes intelligently.
  502. Pick the *closest meaning* value from the allowed list, even if not an exact word match.
  503. I want values for all mandatory attributes.
  504. If a value is not found anywhere, the source should be "inferred".
  505. Note: Source means from where you have concluded the result. Choose one of these value <{source_hint}>
  506. ALLOWED VALUES (MANDATORY):
  507. {allowed_text}
  508. Note: "Strictly" return multiple values for these attributes: {multiple_text}. These values must be most possible values from the list and should be max 2 values.
  509. {user_values_section}
  510. {additional_instructions}
  511. PRODUCT TEXT:
  512. {product_text}
  513. OUTPUT (strict JSON only):
  514. {{
  515. "mandatory": {{
  516. "<attr>": [{{
  517. "value": "<chosen_value>",
  518. "source": "<{source_hint}>",
  519. "reason": "Explanation of why this value was chosen. If user provided a value, explain why you agreed/disagreed with it.",
  520. "original_value": "<user_entered_value_if_provided>",
  521. "decision": "accepted|rejected|not_provided"
  522. }}]
  523. }},
  524. {output_example_additional}
  525. }}
  526. RULES:
  527. - For each mandatory attribute with a user-entered value, include "original_value" and "decision" fields
  528. - "decision" values: "accepted" (used user's value), "rejected" (used different value), "not_provided" (no user value given)
  529. - "reason" must explain your choice, especially when rejecting user input
  530. - For 'multiple' attributes, always give multiple values for those attributes, choose wisely and max 2 values per attribute that are very close.
  531. - Source must be one of: {source_hint}
  532. - Be honest and specific in your reasoning.
  533. - Return ONLY valid JSON
  534. """
  535. payload = {
  536. "model": model,
  537. "messages": [
  538. {"role": "system", "content": "You are a JSON-only extractor and validator. Always provide clear reasoning for your decisions."},
  539. {"role": "user", "content": prompt},
  540. ],
  541. "temperature": 0.3,
  542. "max_tokens": 2000, # Increased for reasoning
  543. }
  544. try:
  545. raw = ProductAttributeService._call_llm(payload)
  546. logger.info("Raw LLM response received")
  547. cleaned = ProductAttributeService._clean_json(raw)
  548. parsed = json.loads(cleaned)
  549. except Exception as exc:
  550. logger.error(f"LLM failed: {exc}")
  551. return {
  552. "mandatory": {
  553. a: [{
  554. "value": "Not Specified",
  555. "source": "llm_error",
  556. "reason": f"LLM processing failed: {str(exc)}"
  557. }] for a in mandatory_attrs
  558. },
  559. "additional": {} if not extract_additional else {},
  560. "error": str(exc)
  561. }
  562. if use_cache and cache_key:
  563. SimpleCache.set(cache_key, parsed)
  564. logger.info(f"CACHE SET {cache_key[:16]}...")
  565. return parsed
  566. @staticmethod
  567. def get_cache_stats() -> Dict:
  568. return {
  569. "global_enabled": is_caching_enabled(),
  570. "result_cache": SimpleCache.get_stats(),
  571. }
  572. @staticmethod
  573. def clear_all_caches():
  574. SimpleCache.clear()
  575. logger.info("All caches cleared")
  576. # IMPORTANT INSTRUCTIONS FOR USER VALUES:
  577. # 1. Compare the user-entered value with what you find in the product text
  578. # 2. Evaluate if the user value is correct, partially correct, or incorrect for this product
  579. # 3. Choose the BEST value (could be user's value, or from allowed list, or inferred)
  580. # 4. Always provide a "reason" field explaining your decision
  581. # 5. DO NOT hallucinate - be honest if user's value seems wrong based on product evidence
  582. # 6. If user's value is not in the allowed list but seems correct, chose the most nearest value from the allowed list with proper reasoning.