Spaces:
Sleeping
Sleeping
Piers Lyon
Claude Opus 4.7 (1M context)
LGR (UK local-government reorganisation) as a tier-1 lead category
6e78cbc Download brain.py from mipwr-admin/curium-intel: direct link, hf CLI and curl.
- Browser
- Download file 32.2 kB
-
https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/brain.py
- Command line
-
hf download hf://spaces/mipwr-admin/curium-intel/brain.py
-
curl -L -o brain.py https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/brain.py
32.2 kB
| """ | |
| AI Analysis Module (brain.py) | |
| Uses Claude to analyze job postings and score leads for Curium Solutions. | |
| Enhanced with dual scoring for Transformation Delivery (TD) and Culture & Capability (CC). | |
| """ | |
| import os | |
| import json | |
| from pathlib import Path | |
| from dotenv import load_dotenv | |
| from anthropic import Anthropic | |
| # Load environment variables from .env file in project root | |
| env_path = Path(__file__).parent / '.env' | |
| load_dotenv(dotenv_path=env_path, override=True) | |
| # Initialize the Anthropic client | |
| client = None | |
| def get_client(): | |
| """Get or create the Anthropic client.""" | |
| global client | |
| if client is None: | |
| api_key = os.environ.get("ANTHROPIC_API_KEY") | |
| if not api_key: | |
| raise ValueError( | |
| "ANTHROPIC_API_KEY environment variable is not set. " | |
| "Please set it with: export ANTHROPIC_API_KEY='your-api-key'" | |
| ) | |
| client = Anthropic(api_key=api_key) | |
| return client | |
| # Valid service IDs that can appear in recommended_services | |
| VALID_SERVICE_IDS = [ | |
| # Transformation Delivery | |
| "project_programme_management", | |
| "change_management", | |
| "business_analysis", | |
| "tmo_pmo", | |
| "operating_models", | |
| "agile_lean", | |
| "ma_integration", | |
| "service_desk", | |
| # Culture & Capability | |
| "executive_coaching", | |
| "leadership_strategy", | |
| "culture_diagnostics", | |
| "team_profiling", | |
| "facilitation", | |
| "resilience", | |
| "one_to_one_coaching", | |
| "dysfunctional_teams", | |
| "mindset_behaviour", | |
| # Digital product | |
| "code_3i", | |
| ] | |
| VALID_SIGNAL_TYPES = [ | |
| "restructuring", | |
| "leadership_change", | |
| "merger_acquisition", | |
| "culture_crisis", | |
| "sentiment_poor", | |
| "pe_acquisition", | |
| "digital_transformation", | |
| "new_team", | |
| "hiring_surge", | |
| "ai_readiness_assessment", | |
| "ai_implementation_support", | |
| "hiring_transformation_roles", | |
| "programme_failure", | |
| "operating_model_change", | |
| "wellbeing_crisis", | |
| "general", | |
| ] | |
| SYSTEM_PROMPT = """You are a Business Development Director for **Curium Solutions**, a UK-based transformation consultancy. | |
| **Curium has TWO practice areas:** | |
| **1. Transformation Delivery (TD)** β Expert delivery capability for complex change: | |
| - Project & Programme Management: PMO setup, programme assurance, delivery | |
| - Change Management: Business change, adoption, stakeholder engagement | |
| - Business Analysis: Requirements, process improvement, solution design | |
| - TMO/PMO: Transformation office setup, portfolio governance | |
| - Operating Model Design: Target operating model, org design, restructuring | |
| - Agile & Lean: Agile transformation, ways of working, continuous improvement | |
| - M&A Integration: Post-merger integration, carve-outs, Day 1 readiness | |
| - Service Desk: ITSM transformation, service management improvement | |
| **2. Culture & Capability (CC)** β Unlocking the human side of transformation: | |
| - Executive Coaching: C-suite and senior leader coaching | |
| - Leadership Strategy: Leadership development programmes, capability building | |
| - Culture Diagnostics: Culture assessments, engagement surveys, values work | |
| - Team Profiling (TetraMap/CODE): Team dynamics, communication styles, CODE 3i assessment | |
| - Facilitation: Strategic offsites, leadership workshops, team sessions | |
| - Resilience & Wellbeing: Stress management, burnout prevention, wellbeing programmes | |
| - 1-to-1 Coaching: Personal development, performance coaching | |
| - Dysfunctional Team Intervention: Team reset, conflict resolution, team rebuild | |
| - Mindset & Behaviour Change: Values programmes, psychological safety, behavioural frameworks | |
| **3. CODE 3i** β Digital team assessment product: | |
| - 10-minute psychometric giving instant insight into team dynamics | |
| - Perfect for new teams, teams under pressure, hybrid working | |
| - Used by DAC Beachcroft, Canada Life, and 100+ organisations | |
| **4. Change Launchpad** β Entry point diagnostic: | |
| - Low-risk, low-cost 3-4 week diagnostic | |
| - Maps transformation readiness, identifies blockers, builds momentum from Day One | |
| - Used by Rolls-Royce, NASA, Bentley, Headlam and others | |
| - This is the recommended starting conversation for all new prospects | |
| **CRITICAL - UK & IRELAND:** | |
| - We work with UK-based companies OR Ireland-based companies (or their subsidiaries). | |
| - If the company is clearly US-only, EU-only (except Ireland), or has no UK/Ireland presence, score it 0. | |
| - UK/Ireland indicators: "UK", "London", "Dublin", "Cork", "Belfast", "British", "Irish", UK/Ireland city names, ".co.uk", ".ie", "Ltd", "PLC", pound sterling, Euro. | |
| - US indicators to REJECT: US-only cities, "$" salary, "Inc", ".com" with no UK/Ireland mention. | |
| **Scoring Bands:** | |
| - **80-100:** UK/Ireland + Direct hit for specific Curium services (leadership development, team transformation, PMO setup, M&A integration, culture change, AI readiness assessment, AI implementation support) | |
| - **50-79:** UK/Ireland + General change/transformation role or related trigger (including hiring for transformation roles) | |
| - **20-49:** Possibly UK/Ireland but unclear, or operational role with some relevance | |
| - **0-19:** Non-UK/Ireland company OR purely operational/admin role | |
| **Signal types** (pick the most relevant): restructuring, leadership_change, merger_acquisition, culture_crisis, sentiment_poor, pe_acquisition, digital_transformation, new_team, hiring_surge, ai_readiness_assessment, ai_implementation_support, hiring_transformation_roles, programme_failure, operating_model_change, wellbeing_crisis, general | |
| **Valid service IDs:** project_programme_management, change_management, business_analysis, tmo_pmo, operating_models, agile_lean, ma_integration, service_desk, executive_coaching, leadership_strategy, culture_diagnostics, team_profiling, facilitation, resilience, one_to_one_coaching, dysfunctional_teams, mindset_behaviour, code_3i | |
| **EXTRACTION (critical β this is what gives our outreach specificity):** | |
| Pull every quantified fact in the text into `quantified_facts`. Examples of what to lift: | |
| - Programme size / budget (Β£50m programme, $1.5bn JV) | |
| - Headcount changes (275 jobs at risk, 3,800 redundancies, 10% workforce cut) | |
| - Financial results (Q1 revenue $4,716m vs $3,688m, EBIT margin 11.7%, +13.6% growth) | |
| - Contract value (Β£40.4m four-year contract, Β£1.2bn framework) | |
| - Timelines (by end-2027, runs to March 2031, three-year initial term) | |
| - Investment amounts (Β£76.5m capital plan, $75m minority investment) | |
| Pull every direct quote (with attribution) into `exec_quotes`. If a CEO/CFO/Chair is named alongside a strategic statement, capture it β even paraphrased direction with attribution counts. | |
| Set `confidence` based on how the text frames the news: | |
| - "official" β RNS / company announcement / earnings release | |
| - "confirmed" β reported by FT/Reuters/Bloomberg/major outlet citing named source | |
| - "rumour" β "in talks", "considering", "exploring", "according to sources" | |
| - "unknown" β can't tell | |
| Set `impact_scope`: | |
| - "company_wide" β affects whole org (CEO change, group-wide restructure) | |
| - "divisional" β one business unit / region | |
| - "site_specific" β one plant / office / branch | |
| - "individual" β single appointment / single role | |
| **Output format:** | |
| You MUST respond with ONLY valid JSON in this exact format, no other text: | |
| { | |
| "score": <integer 0-100>, | |
| "transformation_delivery_score": <integer 0-100>, | |
| "culture_capability_score": <integer 0-100>, | |
| "reason": "<brief explanation in 1-2 sentences>", | |
| "recommended_services": ["<service_id_1>", "<service_id_2>"], | |
| "primary_service_line": "<transformation_delivery or culture_capability or both>", | |
| "signal_type": "<one of the valid signal types>", | |
| "quantified_facts": [ | |
| {"fact_type": "headcount|investment|revenue|margin|timeline|contract_value|other", | |
| "label": "<short human label>", | |
| "value": "<original textual value, e.g. 'Β£50m', '275', '11.7%'>", | |
| "currency": "GBP|USD|EUR|null", | |
| "unit": "m|bn|people|%|null", | |
| "confidence": "official|confirmed|rumour|unknown", | |
| "source_text": "<short quote of the sentence the fact came from>"} | |
| ], | |
| "exec_quotes": [ | |
| {"name": "<exec name>", | |
| "title": "<exec title>", | |
| "quote": "<the quote>", | |
| "confidence": "official|confirmed|rumour|unknown"} | |
| ], | |
| "confidence": "official|confirmed|rumour|unknown", | |
| "impact_scope": "company_wide|divisional|site_specific|individual" | |
| } | |
| If there are no facts or quotes, return empty arrays β do NOT invent.""" | |
| VALID_CONFIDENCE = {"official", "confirmed", "rumour", "rumor", "unknown"} | |
| VALID_IMPACT_SCOPE = {"company_wide", "divisional", "site_specific", "individual", "unknown"} | |
| VALID_FACT_TYPES = { | |
| "headcount", "investment", "revenue", "margin", "timeline", | |
| "contract_value", "growth", "valuation", "other" | |
| } | |
| def _sanitize_quantified_facts(raw) -> list[dict]: | |
| """Coerce raw LLM output into a clean list of fact dicts. Drop junk.""" | |
| if not isinstance(raw, list): | |
| return [] | |
| out = [] | |
| for f in raw: | |
| if not isinstance(f, dict): | |
| continue | |
| fact_type = str(f.get("fact_type") or "other").lower().strip() | |
| if fact_type not in VALID_FACT_TYPES: | |
| fact_type = "other" | |
| label = str(f.get("label") or "").strip()[:200] | |
| value = f.get("value") | |
| if value is None or (isinstance(value, str) and not value.strip()): | |
| continue | |
| confidence = str(f.get("confidence") or "unknown").lower().strip() | |
| if confidence == "rumor": | |
| confidence = "rumour" | |
| if confidence not in VALID_CONFIDENCE: | |
| confidence = "unknown" | |
| out.append({ | |
| "fact_type": fact_type, | |
| "label": label, | |
| "value": value if isinstance(value, (int, float)) else str(value)[:200], | |
| "currency": (str(f["currency"])[:8] if f.get("currency") else None), | |
| "unit": (str(f["unit"])[:16] if f.get("unit") else None), | |
| "confidence": confidence, | |
| "source_text": str(f.get("source_text") or "")[:500], | |
| }) | |
| return out[:20] # cap | |
| def _sanitize_exec_quotes(raw) -> list[dict]: | |
| if not isinstance(raw, list): | |
| return [] | |
| out = [] | |
| for q in raw: | |
| if not isinstance(q, dict): | |
| continue | |
| quote = str(q.get("quote") or "").strip() | |
| if not quote: | |
| continue | |
| confidence = str(q.get("confidence") or "unknown").lower().strip() | |
| if confidence == "rumor": | |
| confidence = "rumour" | |
| if confidence not in VALID_CONFIDENCE: | |
| confidence = "unknown" | |
| out.append({ | |
| "name": str(q.get("name") or "")[:120], | |
| "title": str(q.get("title") or "")[:200], | |
| "quote": quote[:1000], | |
| "confidence": confidence, | |
| }) | |
| return out[:10] | |
| def _sanitize_confidence(value) -> str: | |
| v = str(value or "unknown").lower().strip() | |
| if v == "rumor": | |
| v = "rumour" | |
| return v if v in VALID_CONFIDENCE else "unknown" | |
| def _sanitize_impact_scope(value) -> str: | |
| v = str(value or "unknown").lower().strip() | |
| return v if v in VALID_IMPACT_SCOPE else "unknown" | |
| def analyze_opportunity(text_content: str) -> dict: | |
| """ | |
| Analyze a job posting or lead text using Claude. | |
| Returns dict with keys: | |
| score, transformation_delivery_score, culture_capability_score, | |
| reason, recommended_product (backward compat), recommended_services, | |
| primary_service_line, signal_type | |
| """ | |
| if not text_content or not text_content.strip(): | |
| return { | |
| "score": 0, | |
| "transformation_delivery_score": 0, | |
| "culture_capability_score": 0, | |
| "reason": "No content to analyze", | |
| "recommended_product": "None", | |
| "recommended_services": [], | |
| "primary_service_line": "none", | |
| "signal_type": "general", | |
| "quantified_facts": [], | |
| "exec_quotes": [], | |
| "confidence": "unknown", | |
| "impact_scope": "unknown", | |
| } | |
| try: | |
| anthropic_client = get_client() | |
| message = anthropic_client.messages.create( | |
| model="claude-sonnet-4-20250514", | |
| max_tokens=1500, # extraction (facts/quotes) needs more headroom than score-only | |
| system=SYSTEM_PROMPT, | |
| messages=[ | |
| { | |
| "role": "user", | |
| "content": f"Analyze this job posting/lead:\n\n{text_content}" | |
| } | |
| ] | |
| ) | |
| response_text = message.content[0].text.strip() | |
| # Clean markdown code blocks if present | |
| if response_text.startswith("```"): | |
| lines = response_text.split('\n') | |
| if lines[0].startswith("```"): | |
| lines = lines[1:] | |
| if lines and lines[-1].strip() == "```": | |
| lines = lines[:-1] | |
| response_text = '\n'.join(lines).strip() | |
| try: | |
| result = json.loads(response_text) | |
| # Validate and sanitize | |
| score = max(0, min(100, int(result.get("score", 0)))) | |
| td_score = max(0, min(100, int(result.get("transformation_delivery_score", 0)))) | |
| cc_score = max(0, min(100, int(result.get("culture_capability_score", 0)))) | |
| reason = str(result.get("reason", "Analysis complete"))[:500] | |
| # Validate recommended_services | |
| raw_services = result.get("recommended_services", []) | |
| if not isinstance(raw_services, list): | |
| raw_services = [] | |
| recommended_services = [s for s in raw_services if s in VALID_SERVICE_IDS] | |
| # Validate primary_service_line | |
| primary = result.get("primary_service_line", "none") | |
| if primary not in ("transformation_delivery", "culture_capability", "both", "none"): | |
| primary = "both" if td_score > 30 and cc_score > 30 else ( | |
| "transformation_delivery" if td_score > cc_score else "culture_capability" | |
| ) | |
| # Validate signal_type | |
| signal_type = result.get("signal_type", "general") | |
| if signal_type not in VALID_SIGNAL_TYPES: | |
| signal_type = "general" | |
| # Backward-compatible recommended_product | |
| if primary == "culture_capability" and "code_3i" in recommended_services: | |
| recommended_product = "CODE" | |
| elif primary == "transformation_delivery": | |
| recommended_product = "Change Consulting" | |
| elif primary == "both": | |
| recommended_product = "Both" | |
| elif score < 20: | |
| recommended_product = "None" | |
| else: | |
| recommended_product = "Both" | |
| return { | |
| "score": score, | |
| "transformation_delivery_score": td_score, | |
| "culture_capability_score": cc_score, | |
| "reason": reason, | |
| "recommended_product": recommended_product, | |
| "recommended_services": recommended_services, | |
| "primary_service_line": primary, | |
| "signal_type": signal_type, | |
| "quantified_facts": _sanitize_quantified_facts(result.get("quantified_facts")), | |
| "exec_quotes": _sanitize_exec_quotes(result.get("exec_quotes")), | |
| "confidence": _sanitize_confidence(result.get("confidence")), | |
| "impact_scope": _sanitize_impact_scope(result.get("impact_scope")), | |
| } | |
| except json.JSONDecodeError: | |
| print(f"Warning: Claude returned non-JSON response: {response_text[:200]}") | |
| return { | |
| "score": 0, | |
| "transformation_delivery_score": 0, | |
| "culture_capability_score": 0, | |
| "reason": f"Analysis parsing error: {response_text[:100]}", | |
| "recommended_product": "None", | |
| "recommended_services": [], | |
| "primary_service_line": "none", | |
| "signal_type": "general", | |
| "quantified_facts": [], | |
| "exec_quotes": [], | |
| "confidence": "unknown", | |
| "impact_scope": "unknown", | |
| } | |
| except ValueError as e: | |
| raise e | |
| except Exception as e: | |
| print(f"Error analyzing opportunity: {e}") | |
| return { | |
| "score": 0, | |
| "transformation_delivery_score": 0, | |
| "culture_capability_score": 0, | |
| "reason": f"Analysis failed: {str(e)[:100]}", | |
| "recommended_product": "None", | |
| "recommended_services": [], | |
| "primary_service_line": "none", | |
| "signal_type": "general", | |
| "quantified_facts": [], | |
| "exec_quotes": [], | |
| "confidence": "unknown", | |
| "impact_scope": "unknown", | |
| } | |
| def _curium_context_block() -> str: | |
| """Build a one-off Curium context paragraph for contextual scoring. | |
| Pulls sectors + clients + recent signals so Claude can score in | |
| strategic context, not as a generic role-fit judge. Cheap (config | |
| file + small DB query). Returns empty string on any failure so the | |
| classic batch scoring still works.""" | |
| try: | |
| import sqlite3, yaml | |
| from pathlib import Path | |
| cfg_path = Path(__file__).parent / "config.yaml" | |
| with open(cfg_path, "r") as f: | |
| cfg = yaml.safe_load(f) | |
| sectors = [s.get("name") for s in (cfg.get("target_sectors") or []) if s.get("slug") and s.get("slug") != "ftse_250"] | |
| clients = [c.get("name") for c in (cfg.get("curium_clients") or [])] | |
| # Recent high-signal companies β anyone with score >= 40 in the | |
| # collated companies table. These are "warm" β a job at one of | |
| # them is much more interesting than a generic match. | |
| warm = [] | |
| try: | |
| conn = sqlite3.connect("leads.db") | |
| rows = conn.execute( | |
| "SELECT name FROM companies WHERE overall_score >= 40 ORDER BY overall_score DESC LIMIT 30" | |
| ).fetchall() | |
| warm = [r[0] for r in rows] | |
| conn.close() | |
| except Exception: | |
| pass | |
| bits = [] | |
| if sectors: | |
| bits.append("**Curium target sectors**: " + "; ".join(sectors)) | |
| if clients: | |
| bits.append("**Curium existing/recent clients (warm β flag in reason)**: " + ", ".join(clients)) | |
| if warm: | |
| bits.append("**Currently warm in the pipeline (scoreβ₯40)**: " + ", ".join(warm[:30])) | |
| return "\n".join(bits) | |
| except Exception: | |
| return "" | |
| def analyze_opportunities_batch(job_texts: list[str], context: str | None = None) -> list[dict]: | |
| """ | |
| Analyze multiple job postings in a single API call for efficiency. | |
| Sends up to 5 jobs per call. Returns list of analysis dicts matching input order. | |
| Falls back to individual analysis on error. | |
| `context` (optional): pre-built Curium-context block. If None, the | |
| function lazily builds one via _curium_context_block() so scoring | |
| reflects the live pipeline. Pass an empty string to disable. | |
| """ | |
| if not job_texts: | |
| return [] | |
| if context is None: | |
| context = _curium_context_block() | |
| # Build combined prompt | |
| batch_parts = [] | |
| for i, text in enumerate(job_texts): | |
| batch_parts.append(f"--- JOB {i+1} ---\n{text}") | |
| combined = "\n\n".join(batch_parts) | |
| context_section = ( | |
| "\n\n=== CURIUM CONTEXT (use this to score in context β a job at a" | |
| " warm/client company in a target sector is materially more valuable" | |
| " than the same job at a generic match) ===\n" + context + "\n" | |
| ) if context else "" | |
| batch_prompt = f"""Analyze each of the following {len(job_texts)} job postings/leads.{context_section} | |
| {combined} | |
| # Curium ICP for jobs β what we sell, what we don't | |
| Curium is a hands-on transformation + culture consultancy. We are brought in to DELIVER transformation programmes (not strategy advisory). The roles below are useful to us **only when they signal a company has a programme starting or in planning that needs a delivery partner**. | |
| ## Score 80-100 (HIGH β clear programme need) | |
| Curium is relevant at TWO timing windows: (a) programmes starting / mobilising, AND (b) programmes mid-flight showing signs of needing additional muscle. | |
| **(a) Pre-programme / mobilising β fresh roles**: | |
| - Head of / Director of / Chief **Transformation** (any flavour: digital, business, AI, operating model) | |
| - Head of / Director of / Chief **Change** (Change Director, Head of Business Change, Head of Organisational Change) | |
| - Programme Director / Portfolio Director / Head of PMO / Head of TMO | |
| - Chief People Officer / CHRO / People Director **with explicit transformation mandate** | |
| - Head of L&D / Head of Leadership Development / Head of Talent (at-scale capability uplift roles) | |
| - Head of Culture / Director of Culture / Chief Culture Officer | |
| - M&A Integration Director / Head of M&A Integration / Post-Merger Integration Lead | |
| - ERP Programme Director / SAP Implementation Lead / Workday Programme Lead | |
| - Operating Model Director / Head of Organisational Design | |
| **(b) Mid-flight β programme is already running and needs help**: | |
| - Interim / Acting Programme Director or Director of Change (someone left mid-flight) | |
| - Programme Recovery Director / Programme Assurance Lead | |
| - Multiple Change Managers / Senior Programme Managers posted in a short window (signal of ramp-up) | |
| - Delivery Assurance / Transformation Assurance roles | |
| - "Augment the team" / "scaling up the programme" language in the role description | |
| **(c) UK Local Government Reorganisation (LGR) β TIER-1 priority β score these 90+**: | |
| Curium is already engaged at Staffordshire CC and in active discussion with Oxfordshire CC. Every 2-tier county is being merged or considering merger. Anything that mentions LGR / unitary authority / "One [County]" / shadow authority / vesting day / council merger / district unification is a high-priority Curium opportunity. Add a bonus if the role is at a county council AND the description mentions LGR, transformation, ERP (Unit4/Oracle/SAP/Workday), operating model, or programme delivery. Examples: | |
| - LGR Programme Director / Transition Lead at any county council β 95 | |
| - Programme Director at any council with "LGR" / "unitary" / "reorganisation" in the description β 95 | |
| - Head of Transformation at a 2-tier county council β 90 | |
| - Director of Change at a district council in the LGR cohort β 85 | |
| ## Score 50-79 (MEDIUM β possible programme signal but unclear) | |
| - Senior CHRO / People Director WITHOUT explicit transformation language (might be steady-state HR, might be transformation β needs context) | |
| - Head of HR Business Partnering, Head of Talent Acquisition (people-function but not necessarily change-led) | |
| - Senior Programme Manager (mid-level, not Director) | |
| - Head of Operations (could be operational improvement = TD, or could be steady-state ops) | |
| - Strategy Director / Head of Strategy (Curium does NOT do strategy advisory β relevant only if it's strategy *implementation*) | |
| ## Score 0-49 (LOW β drop unless company has another strong signal) | |
| - Head of Sales / Sales Director / Head of Commercial β wrong function | |
| - Head of Marketing / Marketing Director / Brand Director β wrong function | |
| - Head of Customer / Customer Success Director β wrong function unless tied to a CX transformation programme | |
| - Head of Product / Product Director β wrong function | |
| - Head of Finance / Financial Controller (steady-state finance) β only relevant if CFO with mandate | |
| - Head of Legal / GC β wrong function | |
| - Head of IT / Technology Lead (steady-state) β only relevant if CIO/CTO with mandate | |
| - Head of Engineering / Tech Lead β wrong function | |
| - Specialist functions (Head of Tax, Head of Procurement, Head of Property) β wrong function | |
| ## Bias rules | |
| - Add **+15** if hiring company is on the warm/client list above (ready conversation) | |
| - Add **+10** if hiring company is in a Curium target sector | |
| - Subtract **-10** if no programme indicator in the title or description | |
| - A senior role at a target-sector company is NOT enough on its own β the role MUST point to a transformation/change/culture/leadership-development need | |
| In `reason`, be specific about the programme angle. NOT "senior hire at X" β instead "X is hiring a Programme Director, suggesting a TD-shaped programme is being kicked off". If hiring company is on the warm/client list, START reason with `[CLIENT]`. | |
| In ADDITION to scoring, extract every quantified fact (Β£/$, headcount, %, timelines, contract values) into `quantified_facts`, and every named exec direct quote into `exec_quotes` β the system prompt has the schema. Set `confidence` (official/confirmed/rumour/unknown) and `impact_scope` (company_wide/divisional/site_specific/individual). Empty arrays are fine β do NOT invent facts. | |
| You MUST respond with ONLY a valid JSON array containing one object per job, in order: | |
| [{{"score": <0-100>, "transformation_delivery_score": <0-100>, "culture_capability_score": <0-100>, "reason": "<brief explanation focused on programme angle>", "recommended_services": [<service_ids>], "primary_service_line": "<transformation_delivery|culture_capability|both|none>", "signal_type": "<signal_type>", "quantified_facts": [...], "exec_quotes": [...], "confidence": "<...>", "impact_scope": "<...>"}}, ...]""" | |
| try: | |
| anthropic_client = get_client() | |
| message = anthropic_client.messages.create( | |
| model="claude-sonnet-4-20250514", | |
| max_tokens=1500 * len(job_texts), # extraction needs more headroom | |
| system=SYSTEM_PROMPT, | |
| messages=[{"role": "user", "content": batch_prompt}] | |
| ) | |
| response_text = message.content[0].text.strip() | |
| if response_text.startswith("```"): | |
| lines = response_text.split('\n') | |
| if lines[0].startswith("```"): | |
| lines = lines[1:] | |
| if lines and lines[-1].strip() == "```": | |
| lines = lines[:-1] | |
| response_text = '\n'.join(lines).strip() | |
| results = json.loads(response_text) | |
| if not isinstance(results, list) or len(results) != len(job_texts): | |
| return [analyze_opportunity(t) for t in job_texts] | |
| validated = [] | |
| for r in results: | |
| score = max(0, min(100, int(r.get("score", 0)))) | |
| td_score = max(0, min(100, int(r.get("transformation_delivery_score", 0)))) | |
| cc_score = max(0, min(100, int(r.get("culture_capability_score", 0)))) | |
| reason = str(r.get("reason", ""))[:500] | |
| raw_services = r.get("recommended_services", []) | |
| if not isinstance(raw_services, list): | |
| raw_services = [] | |
| recommended_services = [s for s in raw_services if s in VALID_SERVICE_IDS] | |
| primary = r.get("primary_service_line", "none") | |
| if primary not in ("transformation_delivery", "culture_capability", "both", "none"): | |
| primary = "both" if td_score > 30 and cc_score > 30 else ( | |
| "transformation_delivery" if td_score > cc_score else "culture_capability" | |
| ) | |
| signal_type = r.get("signal_type", "general") | |
| if signal_type not in VALID_SIGNAL_TYPES: | |
| signal_type = "general" | |
| if primary == "culture_capability" and "code_3i" in recommended_services: | |
| recommended_product = "CODE" | |
| elif primary == "transformation_delivery": | |
| recommended_product = "Change Consulting" | |
| elif primary == "both": | |
| recommended_product = "Both" | |
| elif score < 20: | |
| recommended_product = "None" | |
| else: | |
| recommended_product = "Both" | |
| validated.append({ | |
| "score": score, | |
| "transformation_delivery_score": td_score, | |
| "culture_capability_score": cc_score, | |
| "reason": reason, | |
| "recommended_product": recommended_product, | |
| "recommended_services": recommended_services, | |
| "primary_service_line": primary, | |
| "signal_type": signal_type, | |
| "quantified_facts": _sanitize_quantified_facts(r.get("quantified_facts")), | |
| "exec_quotes": _sanitize_exec_quotes(r.get("exec_quotes")), | |
| "confidence": _sanitize_confidence(r.get("confidence")), | |
| "impact_scope": _sanitize_impact_scope(r.get("impact_scope")), | |
| }) | |
| return validated | |
| except Exception: | |
| # Fallback: analyze individually | |
| return [analyze_opportunity(t) for t in job_texts] | |
| def analyze_lead_batch(leads: list[dict]) -> list[dict]: | |
| """ | |
| Analyze multiple leads and return results. | |
| Args: | |
| leads: List of lead dictionaries with 'job_title', 'company', 'raw_text' keys | |
| Returns: | |
| List of analysis results corresponding to each lead | |
| """ | |
| # Build text for each lead, then use batch analysis | |
| texts = [] | |
| for lead in leads: | |
| text_parts = [] | |
| if lead.get("job_title"): | |
| text_parts.append(f"Job Title: {lead['job_title']}") | |
| if lead.get("company"): | |
| text_parts.append(f"Company: {lead['company']}") | |
| if lead.get("raw_text"): | |
| text_parts.append(f"Description: {lead['raw_text']}") | |
| texts.append("\n".join(text_parts)) | |
| return analyze_opportunities_batch(texts) | |
| # For testing | |
| if __name__ == "__main__": | |
| test_cases = [ | |
| { | |
| "name": "High TD Score - Programme Director", | |
| "text": """ | |
| Job Title: Programme Director - Transformation | |
| Company: Barclays UK | |
| Description: Leading a major transformation programme across the organisation. | |
| Responsible for PMO governance, stakeholder management, and delivery assurance | |
| across a Β£50m change portfolio. Experience with operating model design essential. | |
| """ | |
| }, | |
| { | |
| "name": "High CC Score - Head of Leadership Development", | |
| "text": """ | |
| Job Title: Head of Leadership Development | |
| Company: Lloyds Banking Group, London | |
| Description: We are looking for an experienced leader to build and transform our | |
| leadership capability. You will implement 360 feedback processes, design team | |
| effectiveness programmes, and drive cultural change initiatives. Experience with | |
| psychometric assessments and executive coaching required. | |
| """ | |
| }, | |
| { | |
| "name": "Both TD + CC - Director of Change", | |
| "text": """ | |
| Job Title: Director of Change & Culture | |
| Company: Marks & Spencer PLC | |
| Description: Leading both the delivery of our transformation programme and the | |
| cultural change required to make it stick. Responsible for change management, | |
| leadership alignment, and team effectiveness across all business units. | |
| """ | |
| }, | |
| { | |
| "name": "Low Score - Office Admin", | |
| "text": """ | |
| Job Title: Office Administrator | |
| Company: Small Tech Ltd | |
| Description: General administrative duties including filing, scheduling meetings, | |
| and managing office supplies. | |
| """ | |
| } | |
| ] | |
| print("Testing AI Analysis Module (Dual Scoring)") | |
| print("=" * 60) | |
| for test in test_cases: | |
| print(f"\n{test['name']}:") | |
| print("-" * 40) | |
| try: | |
| result = analyze_opportunity(test['text']) | |
| print(f" Overall Score: {result['score']}") | |
| print(f" TD Score: {result['transformation_delivery_score']}") | |
| print(f" CC Score: {result['culture_capability_score']}") | |
| print(f" Primary Line: {result['primary_service_line']}") | |
| print(f" Services: {result['recommended_services']}") | |
| print(f" Signal: {result['signal_type']}") | |
| print(f" Reason: {result['reason']}") | |
| print(f" Product (compat): {result['recommended_product']}") | |
| except ValueError as e: | |
| print(f" Error: {e}") | |