from typing import List, Dict, Any import json import re from openai import OpenAI # This class uses an LLM (OpenAI) to rerank candidate diseases based on their symptoms and scores class LLMReranker: """ Deterministic reranker: reorders existing candidates only. """ def __init__(self, client: OpenAI, model: str): self.client = client self.model = model # Rerank candidates using the LLM. Does not add new diseases. def rerank( self, user_symptoms: List[str], candidates: List[Dict[str, Any]], collapsed_df, top_k: int = 5, ) -> List[Dict[str, Any]]: """ Rerank candidates using the LLM. Does not add new diseases. """ # Build a compact description for each candidate enriched = [] for c in candidates: idx = c["index"] symptoms = collapsed_df.iloc[idx]["Symptoms"] enriched.append( { "disease": c["disease"], # Use various scoring metrics to improve accuracy "scores": { "hybrid_score": c["hybrid_score"], "jaccard": c["jaccard"], "coverage": c["coverage"], "tfidf_cosine": c["tfidf_cosine"], }, "symptoms": symptoms, } ) # Build the prompt for the LLM, including user symptoms and candidate details prompt = self._build_prompt(user_symptoms, enriched, top_k) # Call the LLM to get a new ranking of the candidates resp = self.client.chat.completions.create( model=self.model, messages=[ { "role": "system", "content": ( "You are a ranking engine. You take in a list of candidate conditions " "with scores and symptom lists. You must ONLY reorder the given candidates. " "Do not invent new conditions. Return a JSON array of objects with keys " "`disease` and `rank` (1 = highest)." ), }, {"role": "user", "content": prompt}, ], # Request a deterministic response so we get consistent ranking temperature=0.0, ) # Parse the LLM response to extract the new ranking order content = resp.choices[0].message.content or "" try: ranking = self._parse_ranking(content) except Exception: # Fallback: keep original order return candidates[:top_k] # Create a mapping of disease to its new rank from the LLM output rank_map = { item["disease"]: item["rank"] for item in ranking if isinstance(item, dict) and "disease" in item and "rank" in item } # Get all candidates in the map and sort them by their new rank. Candidates not in the map will be ranked lowest. reranked = [c for c in candidates if c["disease"] in rank_map] reranked.sort(key=lambda x: rank_map.get(x["disease"], 9999)) # Append any candidates that were not included in the LLM's ranking at the end of the list ranked_diseases = {item["disease"] for item in reranked} for candidate in candidates: if candidate["disease"] not in ranked_diseases: reranked.append(candidate) return reranked[:top_k] # Build the prompt for the LLM, including user symptoms and candidate details def _build_prompt(self, user_symptoms, candidates, top_k: int) -> str: return json.dumps( { "user_symptoms": user_symptoms, "candidates": candidates, "top_k": top_k, }, indent=2, ) # Parse the LLM response to extract the new ranking order def _parse_ranking(self, content: str) -> List[Dict[str, Any]]: text = content.strip() if text.startswith("```"): text = re.sub(r"^```(?:json)?\s*", "", text) text = re.sub(r"\s*```$", "", text) parsed = json.loads(text) if isinstance(parsed, dict) and "ranking" in parsed: parsed = parsed["ranking"] if not isinstance(parsed, list): raise ValueError("Expected list ranking output.") return parsed