File size: 6,953 Bytes
ff7b177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""
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)