""" Lazy explanation generation via Ollama cloud (gpt-oss:120b-cloud). Called only when a human explicitly requests a candidate detail view. Result cached in Redis/memory for 48h — subsequent requests return instantly. Fallback: if Ollama is unavailable, returns a template explanation. """ import json import logging from ollama import Client logger = logging.getLogger(__name__) _ollama_client = None def _get_client(): global _ollama_client if _ollama_client is None: from app.config import settings _ollama_client = Client( host=settings.ollama_host, headers={"Authorization": f"Bearer {settings.ollama_api_key}"}, ) return _ollama_client def _build_prompt(jd_data: dict, candidate_detail: dict) -> str: jd_title = jd_data.get("title", "the role") jd_type = jd_data.get("engineer_type", "") min_years = jd_data.get("min_years", 0) req_skills = jd_data.get("required_skills", []) if isinstance(req_skills, str): req_skills = json.loads(req_skills) req_skill_names = [s.get("name", s) if isinstance(s, dict) else s for s in req_skills[:10]] responsibilities = jd_data.get("responsibilities", []) if isinstance(responsibilities, str): responsibilities = json.loads(responsibilities) name = candidate_detail.get("candidate_name", "Candidate") position = candidate_detail.get("current_position", "") years = candidate_detail.get("years_of_experience", 0) skills_text = candidate_detail.get("parsed_skills", "")[:400] summary_text = candidate_detail.get("parsed_summary", "")[:300] work_text = candidate_detail.get("parsed_work_experience_text", "")[:600] breakdown = candidate_detail.get("score_breakdown", {}) if isinstance(breakdown, str): breakdown = json.loads(breakdown) skill_score = breakdown.get("skill_score", 0) semantic_score = breakdown.get("semantic_score", 0) final_score = candidate_detail.get("final_score", 0) tier = candidate_detail.get("tier", "") matched = breakdown.get("matched_skills", []) if isinstance(matched, str): matched = json.loads(matched) matched_names = [s.get("skill", s) if isinstance(s, dict) else s for s in matched[:6]] below = breakdown.get("below_level_skills", []) if isinstance(below, str): below = json.loads(below) below_details = [] for s in below[:4]: if isinstance(s, dict): below_details.append( f"{s.get('skill','?')}: has level {s.get('candidate_level','?')}, " f"needs level {s.get('required_level','?')}" ) missing = breakdown.get("missing_skills", []) if isinstance(missing, str): missing = json.loads(missing) flags = candidate_detail.get("flags", []) if isinstance(flags, str): flags = json.loads(flags) return f"""You are an expert technical recruiter. Analyze this candidate match and write a concise, specific assessment. JOB REQUIREMENTS: - Role: {jd_title} ({jd_type}) - Minimum Experience: {min_years} years - Key Required Skills: {', '.join(req_skill_names)} - Responsibilities (sample): {'; '.join(responsibilities[:3])} CANDIDATE PROFILE: - Name: {name} - Current Role: {position} - Years of Experience: {years} - Skills: {skills_text} - Summary: {summary_text} - Work History: {work_text} MATCH ANALYSIS: - Overall Score: {final_score:.0%} — {tier} - Skills Match Score: {skill_score:.0%} - Experience Relevance: {semantic_score:.0%} - Matched Skills: {', '.join(matched_names) or 'None identified'} - Below-Level Skills: {'; '.join(below_details) or 'None'} - Missing Skills: {', '.join(missing[:5]) or 'None'} - Flags: {', '.join(flags) or 'None'} Write a structured assessment with EXACTLY these sections: **Overall Fit** (2 sentences): Reference specific companies and technologies from work history. Be direct and factual. **Strengths** (2–3 bullets): Each bullet must cite actual data — company names, specific technologies, durations, measurable impacts if available. **Gaps** (1–3 bullets, skip if none): Use format: "Has [qualifier] [skill]; role requires [qualifier] [skill]". Be precise. **Flags** (only if flags list is non-empty): Briefly explain recruiter concern for each flag. **Recommendation**: {tier} Be specific. No generic statements. Reference the actual data provided.""" def _fallback_explanation(candidate_detail: dict, tier: str) -> str: name = candidate_detail.get("candidate_name", "Candidate") position = candidate_detail.get("current_position", "") years = candidate_detail.get("years_of_experience", 0) score = candidate_detail.get("final_score", 0) breakdown = candidate_detail.get("score_breakdown", {}) if isinstance(breakdown, str): try: breakdown = json.loads(breakdown) except Exception: breakdown = {} matched = breakdown.get("matched_skills", []) if isinstance(matched, str): try: matched = json.loads(matched) except Exception: matched = [] matched_names = [s.get("skill", s) if isinstance(s, dict) else s for s in matched[:5]] missing = breakdown.get("missing_skills", []) if isinstance(missing, str): try: missing = json.loads(missing) except Exception: missing = [] strengths = ", ".join(matched_names[:3]) if matched_names else "relevant technical skills" gaps_text = f"- Missing or below-level: {', '.join(missing[:3])}" if missing else "- No critical gaps identified" return f"""**Overall Fit** {name} is a {tier.lower()} for this role with a {score:.0%} match score. Currently working as {position} with {years if years != -1 else 'unknown'} years of experience. **Strengths** - Strong in: {strengths} - {years if years != -1 else 'Experience'} years of relevant background - Current role aligns with core requirements **Gaps** {gaps_text} **Recommendation**: {tier} *Note: Detailed AI explanation unavailable — Ollama not running. Start Ollama and pull the model to enable.*""" def generate_explanation(jd_data: dict, candidate_detail: dict) -> str: """ Generate a human-readable explanation via Ollama cloud. Falls back to template if Ollama is unavailable. """ from app.config import settings tier = candidate_detail.get("tier", "Partial Match") try: prompt = _build_prompt(jd_data, candidate_detail) client = _get_client() response = client.chat( model=settings.ollama_model, messages=[{"role": "user", "content": prompt}], options={"temperature": 0.2, "num_predict": 1500}, ) text = response.message.content return text.strip() except Exception as e: logger.warning(f"Ollama call failed: {e}, using fallback") return _fallback_explanation(candidate_detail, tier)