|
|
@@ -174,6 +174,188 @@ Extract data from the text strictly based on the provided JSON Schema.
|
|
|
|
|
|
raise BizLogicError("LLM request failed")
|
|
|
|
|
|
+ @classmethod
|
|
|
+ async def parse_tutorial_async(
|
|
|
+ cls,
|
|
|
+ prompt: str,
|
|
|
+ system_prompt: Optional[str] = None,
|
|
|
+ model: Optional[str] = None,
|
|
|
+ max_retries: int = 1,
|
|
|
+ ) -> Dict[str, Any]:
|
|
|
+ """
|
|
|
+ 利用大模型 (如 DeepSeek) 根据用户的自然语言需求,自动生成商品用户使用教程与操作指引结构化配置
|
|
|
+ 支持前端传入自定义/微调后的 system_prompt
|
|
|
+ """
|
|
|
+ api_key = cls.get_api_key()
|
|
|
+ if not api_key:
|
|
|
+ logger.warning("[LlmService] No LLM API Key configured.")
|
|
|
+ raise BizLogicError("LLM API Key not configured")
|
|
|
+
|
|
|
+ url = cls.get_completions_url()
|
|
|
+ selected_model = (model or "").strip() or cls.get_default_model()
|
|
|
+ temperature = 0.3
|
|
|
+ timeout_seconds = settings.llm_timeout_seconds or 45
|
|
|
+
|
|
|
+ headers = {
|
|
|
+ "Authorization": f"Bearer {api_key}",
|
|
|
+ "Content-Type": "application/json",
|
|
|
+ }
|
|
|
+
|
|
|
+ default_instruction = (
|
|
|
+ "You are an expert e-commerce operations specialist for international visa, embassy, and appointment booking services.\n"
|
|
|
+ "Your primary mission is to generate a MANDATORY PRE-ORDER PREREQUISITE CHECKLIST (下单前置必备条件与门槛说明) for customers before they can purchase this service.\n\n"
|
|
|
+ "CORE EMPHASIS:\n"
|
|
|
+ "The single most important purpose of this guide is establishing the HARD PRE-CONDITIONS required BEFORE placing an order. Customers must satisfy these prerequisites first; otherwise, their automated booking order cannot proceed and will fail.\n\n"
|
|
|
+ "CORE WRITING STYLE:\n"
|
|
|
+ "1. PREREQUISITE-FIRST & ULTRA-CONCISE: Focus exclusively on what the buyer MUST have ready before paying. Avoid generic website tutorials or fluffy disclaimers. Every word must count.\n"
|
|
|
+ "2. ALL ENGLISH: Regardless of input language, generate crisp, authoritative, professional English.\n\n"
|
|
|
+ "JSON SCHEMA:\n"
|
|
|
+ "{\n"
|
|
|
+ ' "display_type": "both", // Allowed: "both", "modal", "link", "embedded"\n'
|
|
|
+ ' "button_text": "⚠️ Mandatory Pre-Order Checklist", // Short warning/checklist label (3-5 words with emoji)\n'
|
|
|
+ ' "modal_title": "Mandatory Prerequisites Before Placing Order", // Clear pre-order gate title (5-8 words)\n'
|
|
|
+ ' "link_url": "https://...", // Official portal URL if mentioned, else ""\n'
|
|
|
+ ' "link_text": "Official Portal ↗", // Short label (2-3 words)\n'
|
|
|
+ ' "badge_text": "Mandatory Prerequisite", // Badge indicating required pre-order gate (1-3 words)\n'
|
|
|
+ ' "summary": "...", // STRICTLY 1-2 punchy sentences warning the buyer what MUST be ready before ordering (under 30 words).\n'
|
|
|
+ ' "steps": [\n'
|
|
|
+ ' {\n'
|
|
|
+ ' "step_no": 1,\n'
|
|
|
+ ' "title": "Action Title", // 2-4 words (e.g. "Activated Portal Account", "Valid Passport Scan", "Cancel Prior Bookings")\n'
|
|
|
+ ' "desc": "One crisp sentence explaining the exact prerequisite required before order (strictly under 20 words)."\n'
|
|
|
+ ' }\n'
|
|
|
+ ' ],\n'
|
|
|
+ ' "content": "..." // Max 2 critical FAQs addressing pre-order blockers (e.g. can I order first without account? overlapping bookings?). Format: **Q: ...?**\\nA: One crisp sentence.\n'
|
|
|
+ "}\n\n"
|
|
|
+ "CRITICAL RULES:\n"
|
|
|
+ "1. FOCUS ON PRE-CONDITIONS: Every single step MUST be a prerequisite task completed BEFORE ordering.\n"
|
|
|
+ "2. MAX 3 STEPS: Each step's description MUST be strictly 1 single, compact sentence (< 20 words).\n"
|
|
|
+ "3. SUMMARY: Strictly 1 to 2 sentences max (< 35 words total).\n"
|
|
|
+ "4. FAQ: Strictly 2 questions maximum, with direct 1-sentence answers.\n"
|
|
|
+ "5. Output STRICT JSON only without Markdown wrappers or greetings."
|
|
|
+ )
|
|
|
+
|
|
|
+ effective_system_prompt = system_prompt.strip() if (system_prompt and system_prompt.strip()) else default_instruction
|
|
|
+
|
|
|
+ payload = {
|
|
|
+ "model": selected_model,
|
|
|
+ "messages": [
|
|
|
+ {"role": "system", "content": effective_system_prompt},
|
|
|
+ {"role": "user", "content": prompt}
|
|
|
+ ],
|
|
|
+ "temperature": temperature,
|
|
|
+ "response_format": {"type": "json_object"}
|
|
|
+ }
|
|
|
+
|
|
|
+ timeout = aiohttp.ClientTimeout(total=float(timeout_seconds))
|
|
|
+
|
|
|
+ for attempt in range(max_retries + 1):
|
|
|
+ try:
|
|
|
+ async with aiohttp.ClientSession(timeout=timeout) as session:
|
|
|
+ async with session.post(url, headers=headers, json=payload) as response:
|
|
|
+ if response.status != 200:
|
|
|
+ error_text = await response.text()
|
|
|
+ logger.error(f"[LlmService] HTTP {response.status} from {url}: {error_text}")
|
|
|
+ if attempt == max_retries:
|
|
|
+ raise BizLogicError(f"LLM request failed: HTTP {response.status}")
|
|
|
+ await asyncio.sleep(0.5)
|
|
|
+ continue
|
|
|
+
|
|
|
+ result = await response.json()
|
|
|
+ choices = result.get("choices", [])
|
|
|
+ if not choices:
|
|
|
+ raise BizLogicError("LLM response did not contain completion choices")
|
|
|
+
|
|
|
+ content_str = choices[0].get("message", {}).get("content", "")
|
|
|
+ parsed = cls.clean_json_response(content_str)
|
|
|
+ if not isinstance(parsed, dict):
|
|
|
+ raise BizLogicError("LLM returned non-dict JSON")
|
|
|
+
|
|
|
+ # 若模型在顶层嵌套了 tutorial_config / tutorial / config / data,先解包
|
|
|
+ if "tutorial_config" in parsed and isinstance(parsed["tutorial_config"], dict):
|
|
|
+ parsed = parsed["tutorial_config"]
|
|
|
+ elif "tutorial" in parsed and isinstance(parsed["tutorial"], dict):
|
|
|
+ parsed = parsed["tutorial"]
|
|
|
+ elif "config" in parsed and isinstance(parsed["config"], dict):
|
|
|
+ parsed = parsed["config"]
|
|
|
+ elif "data" in parsed and isinstance(parsed["data"], dict):
|
|
|
+ parsed = parsed["data"]
|
|
|
+
|
|
|
+ # 全量健壮字段对齐与多格式兼容,确保精准填充至表单各位置
|
|
|
+ btn_txt = parsed.get("button_text") or parsed.get("button_label") or parsed.get("btn_text") or "📖 Guide: Prepare Your Account"
|
|
|
+ m_title = parsed.get("modal_title") or parsed.get("title") or parsed.get("name") or "Official Portal Registration & Booking Guide"
|
|
|
+ l_url = parsed.get("link_url") or parsed.get("url") or parsed.get("link") or ""
|
|
|
+ l_txt = parsed.get("link_text") or parsed.get("url_text") or "Open Official Portal ↗"
|
|
|
+ summ = parsed.get("summary") or parsed.get("overview") or parsed.get("description") or ""
|
|
|
+ raw_faq = parsed.get("content") or parsed.get("faq") or parsed.get("faq_content") or parsed.get("details") or ""
|
|
|
+ if isinstance(raw_faq, list):
|
|
|
+ faq_lines = []
|
|
|
+ for i, item in enumerate(raw_faq):
|
|
|
+ if isinstance(item, dict):
|
|
|
+ q = item.get("q") or item.get("question") or item.get("title") or f"Question {i+1}"
|
|
|
+ a = item.get("a") or item.get("answer") or item.get("desc") or item.get("content") or ""
|
|
|
+ faq_lines.append(f"**Q{i+1}. {q}**\n{a}")
|
|
|
+ elif isinstance(item, str):
|
|
|
+ faq_lines.append(item)
|
|
|
+ faq_content = "\n\n".join(faq_lines)
|
|
|
+ else:
|
|
|
+ faq_content = str(raw_faq)
|
|
|
+
|
|
|
+ badge_txt = parsed.get("badge_text") or "Prerequisite Guide"
|
|
|
+
|
|
|
+ d_type = str(parsed.get("display_type", "both")).lower()
|
|
|
+ if "modal" in d_type:
|
|
|
+ d_type = "modal"
|
|
|
+ elif "link" in d_type:
|
|
|
+ d_type = "link"
|
|
|
+ elif "embed" in d_type:
|
|
|
+ d_type = "embedded"
|
|
|
+ else:
|
|
|
+ d_type = "both"
|
|
|
+
|
|
|
+ steps_raw = parsed.get("steps", [])
|
|
|
+ if not isinstance(steps_raw, list):
|
|
|
+ if isinstance(steps_raw, str):
|
|
|
+ steps_raw = [s.strip() for s in steps_raw.split("\n") if s.strip()]
|
|
|
+ else:
|
|
|
+ steps_raw = []
|
|
|
+ normalized_steps = []
|
|
|
+ for idx, step in enumerate(steps_raw):
|
|
|
+ if isinstance(step, dict):
|
|
|
+ normalized_steps.append({
|
|
|
+ "step_no": step.get("step_no", idx + 1),
|
|
|
+ "title": step.get("title") or step.get("step_title") or step.get("name") or f"Step {idx + 1}",
|
|
|
+ "desc": step.get("desc") or step.get("description") or step.get("content") or step.get("detail") or "",
|
|
|
+ })
|
|
|
+ elif isinstance(step, str) and step.strip():
|
|
|
+ normalized_steps.append({
|
|
|
+ "step_no": idx + 1,
|
|
|
+ "title": f"Step {idx + 1}",
|
|
|
+ "desc": step.strip(),
|
|
|
+ })
|
|
|
+
|
|
|
+ return {
|
|
|
+ "enabled": True,
|
|
|
+ "display_type": d_type,
|
|
|
+ "button_text": btn_txt,
|
|
|
+ "modal_title": m_title,
|
|
|
+ "link_url": l_url,
|
|
|
+ "link_text": l_txt,
|
|
|
+ "badge_text": badge_txt,
|
|
|
+ "summary": summ,
|
|
|
+ "steps": normalized_steps,
|
|
|
+ "content": faq_content,
|
|
|
+ }
|
|
|
+ except BizLogicError:
|
|
|
+ raise
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"[LlmService] parse_tutorial_async attempt {attempt} failed: {e}")
|
|
|
+ if attempt == max_retries:
|
|
|
+ raise BizLogicError(f"AI tutorial parsing failed: {str(e)}")
|
|
|
+ await asyncio.sleep(0.5)
|
|
|
+
|
|
|
+ raise BizLogicError("AI tutorial parsing failed")
|
|
|
+
|
|
|
@classmethod
|
|
|
async def chat_completion_with_tools_async(
|
|
|
cls,
|