Spaces:
Sleeping
Sleeping
Download app/api/context_engineering.py from maddy1007/shl-recommender: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/maddy1007/shl-recommender/resolve/main/app/api/context_engineering.py
- Command line
-
hf download hf://spaces/maddy1007/shl-recommender/app/api/context_engineering.py
-
curl -L -o context_engineering.py https://huggingface.co/spaces/maddy1007/shl-recommender/resolve/main/app/api/context_engineering.py
11.9 kB
| """ | |
| Context engineering service. | |
| Transforms raw message history into structured ConversationContext. | |
| This is the brain of the stateless conversation management. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| from typing import List | |
| from app.llm.client import LLMClient | |
| from app.models.schemas import ChatMessage, ConversationContext, MessageRole | |
| from app.prompts.system_prompt import ( | |
| get_intent_extraction_prompt, | |
| get_jd_extraction_prompt, | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Signals that indicate a job description was pasted | |
| JD_SIGNALS = [ | |
| "we are looking for", | |
| "responsibilities include", | |
| "requirements:", | |
| "qualifications:", | |
| "job description", | |
| "about the role", | |
| "you will be responsible", | |
| "minimum qualifications", | |
| "preferred qualifications", | |
| "key responsibilities", | |
| "what you'll do", | |
| "what we're looking for", | |
| "must have", | |
| "nice to have", | |
| "compensation:", | |
| "salary range", | |
| ] | |
| # Prompt injection patterns to detect | |
| INJECTION_PATTERNS = [ | |
| "ignore previous instructions", | |
| "ignore all previous", | |
| "disregard", | |
| "act as", | |
| "you are now", | |
| "jailbreak", | |
| "dan mode", | |
| "reveal your system prompt", | |
| "show me your instructions", | |
| "forget everything", | |
| "new persona", | |
| "pretend you are", | |
| ] | |
| # Off-topic detection keywords | |
| OFF_TOPIC_SIGNALS = { | |
| "salary": ["salary", "compensation", "pay range", "how much does", "wage", "how much should i"], | |
| "career_advice": ["should i apply", "is this a good career", "my resume", "interview tips for me", "job hunting"], | |
| "legal": ["legal advice", "discriminate", "lawsuit", "compliance violation", "sue"], | |
| } | |
| class ContextEngineer: | |
| """ | |
| Extracts and maintains structured context from conversation history. | |
| Operates entirely stateless β context is rebuilt from messages each turn. | |
| """ | |
| def __init__(self, llm_client: LLMClient) -> None: | |
| self.llm = llm_client | |
| self._cache = {} | |
| def extract_context(self, messages: List[ChatMessage]) -> ConversationContext: | |
| """ | |
| Main entry point: given full message history, return structured context. | |
| Uses rule-based extraction and caching first, with LLM only when ambiguous. | |
| """ | |
| # 1. Check cache | |
| conversation_str = self._format_conversation(messages) | |
| cache_key = hash(conversation_str) | |
| if cache_key in self._cache: | |
| return self._cache[cache_key] | |
| ctx = ConversationContext() | |
| # Count clarification turns | |
| assistant_msgs = [m for m in messages if m.role == MessageRole.ASSISTANT] | |
| ctx.clarification_count = sum(1 for m in assistant_msgs if "?" in m.content) | |
| # Detect JD | |
| full_user_text = " ".join( | |
| m.content for m in messages if m.role == MessageRole.USER | |
| ) | |
| ctx.has_jd = self._detect_jd(full_user_text) | |
| # 2. Fast Rule-Based Pre-Pass | |
| ctx = self._rule_based_extract(ctx, full_user_text) | |
| # Determine if it's ambiguous enough to need LLM | |
| is_ambiguous = True | |
| # Explicit role and some skill/requirement usually means we have enough base info | |
| if ctx.role and (ctx.job_level or ctx.skills_focus or ctx.technical_required or ctx.cognitive_required or ctx.personality_required): | |
| # Check if there's comparison language which needs LLM to parse cleanly | |
| if " vs " not in full_user_text.lower() and "compare" not in full_user_text.lower(): | |
| is_ambiguous = False | |
| if ctx.has_jd: | |
| is_ambiguous = True # JDs are complex, let LLM handle it | |
| # 3. LLM Extraction (Only if ambiguous) | |
| if is_ambiguous: | |
| try: | |
| extracted = self._llm_extract(conversation_str) | |
| ctx = self._merge_extracted(ctx, extracted) | |
| except Exception as e: | |
| logger.warning("LLM extraction failed (%s), falling back to rule-based", e) | |
| # Calculate confidence | |
| ctx.confidence_level = self._calculate_confidence(ctx) | |
| # Determine what's still missing | |
| ctx.missing_critical_info = self._find_missing_info(ctx) | |
| # Save to cache | |
| self._cache[cache_key] = ctx | |
| return ctx | |
| def is_off_topic(self, message: str) -> str | None: | |
| """ | |
| Returns the violation type if the message is off-topic, else None. | |
| """ | |
| msg_lower = message.lower() | |
| # Check for prompt injection | |
| if any(p in msg_lower for p in INJECTION_PATTERNS): | |
| return "prompt_injection" | |
| # Check for off-topic categories | |
| for category, signals in OFF_TOPIC_SIGNALS.items(): | |
| if any(s in msg_lower for s in signals): | |
| return category | |
| return None | |
| def extract_jd_requirements(self, jd_text: str) -> dict: | |
| """Extract structured requirements from a job description.""" | |
| prompt = get_jd_extraction_prompt(jd_text) | |
| messages = [{"role": "user", "content": prompt}] | |
| try: | |
| return self.llm.json_chat( | |
| messages, | |
| system_prompt="You are an expert at parsing job descriptions. Return only JSON.", | |
| temperature=0.1, | |
| ) | |
| except Exception as e: | |
| logger.error("JD extraction failed: %s", e) | |
| return {} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Internal helpers | |
| # ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _llm_extract(self, conversation: str) -> dict: | |
| prompt = get_intent_extraction_prompt(conversation) | |
| messages = [{"role": "user", "content": prompt}] | |
| return self.llm.json_chat( | |
| messages, | |
| system_prompt="You extract structured information from conversations. Return only JSON.", | |
| temperature=0.1, | |
| max_tokens=600, | |
| ) | |
| def _merge_extracted(self, ctx: ConversationContext, data: dict) -> ConversationContext: | |
| """Merge LLM-extracted data into the context object.""" | |
| if data.get("role"): | |
| ctx.role = str(data["role"]) | |
| if data.get("industry"): | |
| ctx.industry = str(data["industry"]) | |
| if data.get("job_level"): | |
| level = str(data["job_level"]).lower() | |
| if level in {"graduate", "entry", "professional", "manager", "executive"}: | |
| ctx.job_level = level | |
| if data.get("years_experience"): | |
| try: | |
| ctx.years_experience = int(data["years_experience"]) | |
| except (TypeError, ValueError): | |
| pass | |
| if data.get("skills_focus"): | |
| ctx.skills_focus = [str(s) for s in data["skills_focus"][:10]] | |
| ctx.personality_required = bool(data.get("personality_required", False)) | |
| ctx.cognitive_required = bool(data.get("cognitive_required", False)) | |
| ctx.technical_required = bool(data.get("technical_required", False)) | |
| ctx.behavioral_required = bool(data.get("behavioral_required", False)) | |
| if data.get("assessment_purpose"): | |
| ctx.assessment_purpose = str(data["assessment_purpose"]) | |
| if data.get("has_job_description"): | |
| ctx.has_jd = bool(data["has_job_description"]) | |
| ctx.is_comparison_mode = bool(data.get("is_comparison_mode", False)) | |
| if data.get("comparison_targets"): | |
| ctx.comparison_targets = [str(t) for t in data["comparison_targets"]] | |
| if data.get("excluded_types"): | |
| ctx.excluded_types = [str(t) for t in data["excluded_types"]] | |
| if data.get("most_important_missing_info"): | |
| ctx.missing_critical_info = [str(data["most_important_missing_info"])] | |
| # Store the recommended search query | |
| if data.get("key_search_query"): | |
| ctx.known_facts["search_query"] = str(data["key_search_query"]) | |
| return ctx | |
| def _rule_based_extract(self, ctx: ConversationContext, text: str) -> ConversationContext: | |
| """Enhanced keyword-based extraction as fallback or fast-pass.""" | |
| text_lower = text.lower() | |
| # Cognitive signals | |
| cognitive_words = ["reasoning", "numerical", "verbal", "cognitive", "aptitude", "IQ", "ability test", "spatial"] | |
| if any(w in text_lower for w in cognitive_words): | |
| ctx.cognitive_required = True | |
| # Personality signals | |
| if any(w in text_lower for w in ["personality", "behavioral", "OPQ", "traits", "character", "motivation"]): | |
| ctx.personality_required = True | |
| # Technical signals | |
| if any(w in text_lower for w in ["coding", "technical", "programming", "scripting"]): | |
| ctx.technical_required = True | |
| # Level detection | |
| for level in ["graduate", "entry level", "professional", "manager", "director", "executive", "VP"]: | |
| if level in text_lower: | |
| ctx.job_level = level.split()[0] | |
| break | |
| # Role extraction | |
| import re | |
| role_match = re.search(r"(?:for a|hiring a|looking for a|need a|assess a|role of|position of)\s+([a-z\s]+?(?:engineer|developer|manager|director|analyst|assistant|representative|specialist|consultant|architect|scientist|designer))", text_lower) | |
| if role_match and not ctx.role: | |
| ctx.role = role_match.group(1).strip() | |
| # Skill extraction | |
| known_skills = ["python", "java", "sql", "excel", "c#", "javascript", "react", "power bi", "c++", "leadership", "communication"] | |
| for skill in known_skills: | |
| if skill in text_lower and skill not in [s.lower() for s in ctx.skills_focus]: | |
| ctx.skills_focus.append(skill) | |
| if skill in ["python", "java", "sql", "c#", "javascript", "react", "c++"]: | |
| ctx.technical_required = True | |
| return ctx | |
| def _detect_jd(self, text: str) -> bool: | |
| """Detect if the text contains a job description.""" | |
| text_lower = text.lower() | |
| matches = sum(1 for signal in JD_SIGNALS if signal in text_lower) | |
| return matches >= 2 or len(text) > 500 | |
| def _calculate_confidence(self, ctx: ConversationContext) -> float: | |
| """Calculate confidence that we have enough info to recommend.""" | |
| score = 0.0 | |
| if ctx.role: | |
| score += 0.30 | |
| if ctx.job_level: | |
| score += 0.20 | |
| if ctx.industry: | |
| score += 0.10 | |
| if ctx.skills_focus or ctx.competencies_focus: | |
| score += 0.15 | |
| if ctx.personality_required or ctx.cognitive_required or ctx.technical_required: | |
| score += 0.20 | |
| if ctx.has_jd: | |
| score += 0.20 | |
| return min(score, 1.0) | |
| def _find_missing_info(self, ctx: ConversationContext) -> list[str]: | |
| """Return list of missing critical information items.""" | |
| missing = [] | |
| if not ctx.role and not ctx.has_jd: | |
| missing.append("job role or position being assessed") | |
| if not ctx.job_level: | |
| missing.append("seniority/experience level (graduate, professional, manager, executive)") | |
| if not ctx.assessment_purpose: | |
| missing.append("purpose of assessment (hiring, development, succession)") | |
| return missing | |
| def _format_conversation(messages: List[ChatMessage]) -> str: | |
| lines = [] | |
| for m in messages: | |
| role = "HR Professional" if m.role == MessageRole.USER else "SHL Assistant" | |
| # Truncate very long messages (e.g., full JDs) | |
| content = m.content[:500] + "..." if len(m.content) > 500 else m.content | |
| lines.append(f"{role}: {content}") | |
| return "\n".join(lines) | |