|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from collections.abc import Callable, Mapping, Sequence |
| 4 | +from dataclasses import replace |
| 5 | +from importlib import import_module |
| 6 | +from pathlib import Path |
| 7 | +from typing import Any, Protocol, cast |
| 8 | + |
| 9 | +from core.memory.vector_store import MemorySearchResult |
| 10 | + |
| 11 | +DEFAULT_FLASHRANK_MODEL = "ms-marco-MultiBERT-L-12" |
| 12 | +DEFAULT_FLASHRANK_CACHE_DIR = Path.home() / ".mini-code-agent" / "models" / "flashrank" |
| 13 | + |
| 14 | + |
| 15 | +class FlashRankBackend(Protocol): |
| 16 | + def __call__( |
| 17 | + self, |
| 18 | + *, |
| 19 | + query: str, |
| 20 | + passages: list[dict[str, object]], |
| 21 | + ) -> Sequence[Mapping[str, object]]: ... |
| 22 | + |
| 23 | + |
| 24 | +def _load_flashrank_backend( |
| 25 | + model_name: str, |
| 26 | + cache_dir: Path, |
| 27 | +) -> FlashRankBackend: |
| 28 | + flashrank = import_module("flashrank") |
| 29 | + ranker = flashrank.Ranker(model_name=model_name, cache_dir=str(cache_dir)) |
| 30 | + |
| 31 | + def rerank( |
| 32 | + *, |
| 33 | + query: str, |
| 34 | + passages: list[dict[str, object]], |
| 35 | + ) -> Sequence[Mapping[str, object]]: |
| 36 | + request = flashrank.RerankRequest(query=query, passages=passages) |
| 37 | + return cast(Sequence[Mapping[str, object]], ranker.rerank(request)) |
| 38 | + |
| 39 | + return rerank |
| 40 | + |
| 41 | + |
| 42 | +class FlashRankReranker: |
| 43 | + """Lazily load FlashRank and rerank Memory retrieval candidates.""" |
| 44 | + |
| 45 | + def __init__( |
| 46 | + self, |
| 47 | + model_name: str = DEFAULT_FLASHRANK_MODEL, |
| 48 | + *, |
| 49 | + cache_dir: Path = DEFAULT_FLASHRANK_CACHE_DIR, |
| 50 | + backend_factory: Callable[[str, Path], FlashRankBackend] = ( |
| 51 | + _load_flashrank_backend |
| 52 | + ), |
| 53 | + ) -> None: |
| 54 | + self.model_name = model_name |
| 55 | + self.cache_dir = cache_dir |
| 56 | + self._backend_factory = backend_factory |
| 57 | + self._backend: FlashRankBackend | None = None |
| 58 | + |
| 59 | + def rerank( |
| 60 | + self, |
| 61 | + *, |
| 62 | + query: str, |
| 63 | + candidates: Sequence[MemorySearchResult], |
| 64 | + limit: int, |
| 65 | + ) -> list[MemorySearchResult]: |
| 66 | + if limit <= 0 or not candidates: |
| 67 | + return [] |
| 68 | + |
| 69 | + raw_results = self._get_backend()( |
| 70 | + query=query, |
| 71 | + passages=[ |
| 72 | + {"id": index, "text": candidate.data} |
| 73 | + for index, candidate in enumerate(candidates) |
| 74 | + ], |
| 75 | + ) |
| 76 | + if len(raw_results) != len(candidates): |
| 77 | + raise RuntimeError( |
| 78 | + "FlashRank returned a result count that does not match candidates" |
| 79 | + ) |
| 80 | + |
| 81 | + try: |
| 82 | + ranked = [ |
| 83 | + replace( |
| 84 | + candidates[int(cast(Any, result["id"]))], |
| 85 | + score=float(cast(Any, result["score"])), |
| 86 | + ) |
| 87 | + for result in raw_results |
| 88 | + ] |
| 89 | + except (KeyError, TypeError, ValueError, IndexError) as error: |
| 90 | + raise RuntimeError("FlashRank returned an invalid result") from error |
| 91 | + return ranked[:limit] |
| 92 | + |
| 93 | + def _get_backend(self) -> FlashRankBackend: |
| 94 | + if self._backend is None: |
| 95 | + self._backend = self._backend_factory( |
| 96 | + self.model_name, |
| 97 | + self.cache_dir, |
| 98 | + ) |
| 99 | + return self._backend |
0 commit comments