Coverage for collectra/tasks/canonicalisers.py: 100.00%
46 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Matching text to the canonical form of an entity, with BM25 and an LLM.
3Classes:
4 LLMCanonicaliser: finds the entities closest to the text, then asks the LLM
5 which one the text refers to.
6"""
8__all__ = ["LLMCanonicaliser"]
10import re
11from pathlib import Path
13from dotenv import load_dotenv
15from collectra.tasks.bm25_index import BM25Index
16from collectra.tasks.llms import LLM as CollectraLLM
17from collectra.types.texts import Text
19load_dotenv()
22class LLMCanonicaliser(CollectraLLM):
23 """Asks the LLM which known entity the input text refers to.
25 With an entity file, the ``count`` entities that best match the text (by
26 BM25 over words and their character trigrams, so misspellings still match)
27 are offered to the LLM. A list of entities is offered whole.
29 Attributes:
30 entities (list[str]|Path): The entities, or a file with one per line.
31 count (int): How many entities from a file to offer.
32 """
34 def __init__(self, name: str, model: str, **kwargs):
35 super().__init__(name, model, **kwargs)
36 self.threshold = kwargs.get("threshold", 0.8)
37 self.count = kwargs.get("count", 5)
38 self.entities = kwargs.get("entities", [])
39 entities_path = Path(self.entities)
40 if not entities_path.exists() and entities_path.suffix == "":
41 if isinstance(self.entities, str) or not isinstance(self.entities, list):
42 self.entities = [entity for entity in str(self.entities).split(",")]
43 else:
44 self.entities = entities_path
45 self._index: BM25Index | None = None
47 def _entity_index(self) -> BM25Index:
48 """The entity file's index, built the first time it is needed."""
49 if self._index is None:
50 with open(self.entities, "r") as f:
51 names = [line.strip() for line in f if line.strip()]
52 self._index = BM25Index([str(i) for i in range(len(names))], names)
53 return self._index
55 def retrieve_entities(self, query_data: str) -> dict[str, list[str]]:
56 """The best-matching entities, best first, each with its line numbers."""
57 entities: dict[str, list[str]] = {}
58 for document, _ in self._entity_index().search(query_data, k=self.count):
59 entities.setdefault(document.page_content, []).append(document.id)
60 return entities
62 def run(self, *args: Text) -> Text:
63 """Canonicalize the input text against known entities.
65 Args:
66 text (str): Input text to canonicalize.
68 Returns:
69 str: Canonicalized text if a match is found, otherwise original text.
70 """
71 prompt, pattern = self.pre_run()
73 entity_stem = re.sub("_.*", "", self.name)
74 task_inputs = list(args)
75 query_data: str = ", ".join(
76 [
77 str(task_input.data)
78 for task_input in task_inputs
79 if entity_stem in task_input.name
80 ]
81 )
82 entities = ""
84 if isinstance(self.entities, Path):
85 entities_dict = self.retrieve_entities(query_data)
86 entities = ", ".join(list(entities_dict.keys()))
87 else:
88 entities = ", ".join(self.entities)
90 messages = self.replace_inputs(pattern, prompt, *args, entities=entities)
92 self.messages.append(messages)
94 self.check_inputs(*args)
96 response = self.invoke()
98 return self.text_output(response)