"""Decides which of your recorded answers fits what the caller said. Step 1: fast keyword / fuzzy match (free, instant). Step 2: if nothing matches clearly, ask a small LLM (Claude Haiku) to pick one of your intents or "none". Costs a fraction of a cent per question. """ from __future__ import annotations import logging import re from dataclasses import dataclass import httpx from rapidfuzz import fuzz from .config import Intent log = logging.getLogger("intent") @dataclass class Match: intent: Intent | None score: float method: str # "keyword" | "fuzzy" | "llm" | "none" def _norm(text: str) -> str: text = text.lower() text = re.sub(r"[^\w\sऀ-ॿ]", " ", text) # keep Devanagari return re.sub(r"\s+", " ", text).strip() class IntentMatcher: def __init__(self, intents: list[Intent], anthropic_api_key: str = "", llm_enabled: bool = True, llm_model: str = "claude-haiku-4-5", fuzzy_threshold: int = 86, groq_api_key: str = "", groq_model: str = "openai/gpt-oss-20b", fal_key: str = "", fal_model: str = "google/gemini-2.5-flash"): self.intents = intents self.by_name = {i.name: i for i in intents} self.api_key = anthropic_api_key self.groq_api_key = groq_api_key self.groq_model = groq_model self.fal_key = fal_key self.fal_model = fal_model # Claude if you have a key, else fal, else Groq's free tier self.llm_enabled = llm_enabled and bool(anthropic_api_key or fal_key or groq_api_key) self.llm_model = llm_model self.fuzzy_threshold = fuzzy_threshold self.client = httpx.AsyncClient(timeout=10) def keyword_match(self, text: str) -> Match: t = _norm(text) if not t: return Match(None, 0, "none") padded = f" {t} " best: tuple[float, Intent | None, str] = (0, None, "none") for intent in self.intents: for kw in intent.keywords: k = _norm(kw) if not k: continue if f" {k} " in padded: score, method = 100 + len(k) / 100, "keyword" # longer phrase wins ties else: score, method = fuzz.partial_ratio(k, t) if len(k) >= 4 else 0, "fuzzy" if score > best[0]: best = (score, intent, method) if best[0] >= self.fuzzy_threshold: return Match(best[1], best[0], best[2]) return Match(None, best[0], "none") async def llm_match(self, text: str, recent: list[str]) -> Match: options = "\n".join( f"- {i.name}: {i.description or ''} (example phrases: {', '.join(i.keywords[:6])})" for i in self.intents ) context = "\n".join(recent[-4:]) or "(none)" prompt = ( "You route phone calls. The caller speaks Hindi, English or Hinglish. " "Pick the ONE answer category that best fits the caller's latest line, " "or 'none' if it is noise, filler, or matches nothing.\n\n" f"Categories:\n{options}\n\nEarlier caller lines:\n{context}\n\n" f"Latest caller line: \"{text}\"\n\n" "Reply with only the category name or none." ) try: if not self.api_key: answer = await (self._fal(prompt) if self.fal_key else self._groq(prompt)) return self._to_match(answer) r = await self.client.post( "https://api.anthropic.com/v1/messages", headers={"x-api-key": self.api_key, "anthropic-version": "2023-06-01", "content-type": "application/json"}, json={"model": self.llm_model, "max_tokens": 10, "messages": [{"role": "user", "content": prompt}]}, ) r.raise_for_status() answer = r.json()["content"][0]["text"].strip().strip(".").strip() except Exception as e: log.error("LLM intent failed: %s", e) return Match(None, 0, "none") return self._to_match(answer) def _to_match(self, answer: str) -> Match: answer = (answer or "").strip().strip(".").strip("`'\"").strip() intent = self.by_name.get(answer) or next( (i for n, i in self.by_name.items() if n.lower() == answer.lower()), None) return Match(intent, 90 if intent else 0, "llm" if intent else "none") async def _fal(self, prompt: str) -> str: r = await self.client.post( "https://fal.run/openrouter/router", headers={"Authorization": f"Key {self.fal_key}"}, json={"model": self.fal_model, "prompt": prompt, "temperature": 0, "max_tokens": 20}, ) r.raise_for_status() return r.json().get("output") or "" async def _groq(self, prompt: str) -> str: r = await self.client.post( "https://api.groq.com/openai/v1/chat/completions", headers={"Authorization": f"Bearer {self.groq_api_key}", "content-type": "application/json"}, json={"model": self.groq_model, "temperature": 0, "max_completion_tokens": 300, "reasoning_effort": "low", "messages": [{"role": "user", "content": prompt}]}, ) r.raise_for_status() return r.json()["choices"][0]["message"].get("content") or "" async def match(self, text: str, recent: list[str] | None = None) -> Match: m = self.keyword_match(text) if m.intent or not self.llm_enabled or len(_norm(text)) < 2: return m return await self.llm_match(text, recent or [])