From 805f41a97f82031e43d1fb699703ab857ae2401a Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Thu, 5 Nov 2026 09:05:19 +0000 Subject: [PATCH 01/23] Separate out one inference call for abstract LLMComponent --- .../src/medcat_llm_components/base.py | 48 +++++++++++-------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py index 787d86ad6..5e1a3a85d 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py @@ -79,6 +79,32 @@ def get_init_attrs(cls) -> list[str]: return ['base_url', 'model'] +def _one_call( + cnf: LLMConnectionConfig, + client: OpenAI, + prompt: str, + schema: dict[str, Any] | None, +) -> str: + kwargs: dict[str, Any] = { + "model": cnf.model, + "messages": [{"role": "user", "content": prompt}], + "temperature": cnf.temperature, + "timeout": cnf.timeout, + } + if schema is not None: + kwargs["response_format"] = { + "type": "json_schema", + "json_schema": {"name": "response", "schema": schema, "strict": True}, + } + print(" - C w prompt len", len(prompt)) + try: + resp = client.chat.completions.create(**kwargs) + except APIError as exc: + if schema is not None and _looks_like_unsupported_response_format(exc): + raise _StructuredOutputUnsupported from exc + raise + return resp.choices[0].message.content or "" + class AbstractLLMEntityComponent(AbstractEntityProvidingComponent, ABC): """Shared connection / chat / cleanup plumbing for LLM-based components. @@ -104,7 +130,7 @@ def _chat(self, prompt: str, schema: dict[str, Any] | None = None) -> str: last_exc: Exception | None = None for attempt in range(self.cnf.retries + 1): try: - return self._one_call(prompt, use_schema) + return _one_call(self.cnf, self._client, prompt, use_schema) except _StructuredOutputUnsupported: logger.warning( "%s: backend rejected structured output, falling " @@ -123,26 +149,6 @@ def _chat(self, prompt: str, schema: dict[str, Any] | None = None) -> str: assert last_exc is not None raise last_exc - def _one_call(self, prompt: str, schema: dict[str, Any] | None) -> str: - kwargs: dict[str, Any] = { - "model": self.cnf.model, - "messages": [{"role": "user", "content": prompt}], - "temperature": self.cnf.temperature, - "timeout": self.cnf.timeout, - } - if schema is not None: - kwargs["response_format"] = { - "type": "json_schema", - "json_schema": {"name": "response", "schema": schema, "strict": True}, - } - try: - resp = self._client.chat.completions.create(**kwargs) - except APIError as exc: - if schema is not None and _looks_like_unsupported_response_format(exc): - raise _StructuredOutputUnsupported from exc - raise - return resp.choices[0].message.content or "" - _FENCE_RE = re.compile(r"^```[a-zA-Z]*\n|\n```$") _TABLE_ROW_RE = re.compile(r"^\|.*\|$") _TABLE_SEP_RE = re.compile(r"^[\s|:-]+$") From 4ea3f534b2a1c723e5974174b1578cf35111137a Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Thu, 5 Nov 2026 09:16:15 +0000 Subject: [PATCH 02/23] Move one chat to its separate method in preparation for multiprocessing --- .../src/medcat_llm_components/base.py | 64 ++++++++++--------- .../src/medcat_llm_components/linker.py | 6 +- .../src/medcat_llm_components/ner.py | 5 +- 3 files changed, 44 insertions(+), 31 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py index 5e1a3a85d..e3863d48b 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py @@ -78,6 +78,41 @@ class LLMConnectionConfig(ComponentConfig): def get_init_attrs(cls) -> list[str]: return ['base_url', 'model'] +def one_chat( + cnf: LLMConnectionConfig, + client: OpenAI, + prompt: str, + schema: dict[str, Any] | None = None, +) -> str: + """Send `prompt` as a single user message, return the raw text + response. `schema`, if given, requests structured output for + this call specifically (falls back to freeform if the backend + rejects it). Retries transient connection/timeout failures.""" + structured_output_supported = cnf.use_structured_output + use_schema = schema if structured_output_supported else None + + last_exc: Exception | None = None + for attempt in range(cnf.retries + 1): + try: + return _one_call(cnf, client, prompt, use_schema) + except _StructuredOutputUnsupported: + logger.warning( + "%s: backend rejected structured output, falling " + "back to freeform for the rest of this session", + cnf.comp_name) + structured_output_supported = False + use_schema = None + continue # retry immediately, don't burn a retry slot on this + except (APIConnectionError, APITimeoutError, APIError) as exc: + last_exc = exc + logger.warning( + "%s: LLM call failed (attempt %d/%d): %s", + cnf.comp_name, attempt + 1, cnf.retries + 1, exc) + if attempt < cnf.retries: + time.sleep(cnf.retry_backoff_seconds) + assert last_exc is not None + raise last_exc + def _one_call( cnf: LLMConnectionConfig, @@ -120,35 +155,6 @@ def __init__(self, cnf: LLMConnectionConfig) -> None: # don't keep paying a failed round-trip to rediscover that self._structured_output_supported = cnf.use_structured_output - def _chat(self, prompt: str, schema: dict[str, Any] | None = None) -> str: - """Send `prompt` as a single user message, return the raw text - response. `schema`, if given, requests structured output for - this call specifically (falls back to freeform if the backend - rejects it). Retries transient connection/timeout failures.""" - use_schema = schema if self._structured_output_supported else None - - last_exc: Exception | None = None - for attempt in range(self.cnf.retries + 1): - try: - return _one_call(self.cnf, self._client, prompt, use_schema) - except _StructuredOutputUnsupported: - logger.warning( - "%s: backend rejected structured output, falling " - "back to freeform for the rest of this session", - self.cnf.comp_name) - self._structured_output_supported = False - use_schema = None - continue # retry immediately, don't burn a retry slot on this - except (APIConnectionError, APITimeoutError, APIError) as exc: - last_exc = exc - logger.warning( - "%s: LLM call failed (attempt %d/%d): %s", - self.cnf.comp_name, attempt + 1, self.cnf.retries + 1, exc) - if attempt < self.cnf.retries: - time.sleep(self.cnf.retry_backoff_seconds) - assert last_exc is not None - raise last_exc - _FENCE_RE = re.compile(r"^```[a-zA-Z]*\n|\n```$") _TABLE_ROW_RE = re.compile(r"^\|.*\|$") _TABLE_SEP_RE = re.compile(r"^[\s|:-]+$") diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index 9d0176703..a11c5e6ed 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -16,6 +16,7 @@ AbstractLLMEntityComponent, LLMConnectionConfig, MisconfiguredComponentException, + one_chat, ) logger = logging.getLogger(__name__) @@ -67,7 +68,10 @@ def _pick_cui( ) -> str | None: cand_str = "\n".join(f"{cui}: {pretty}" for cui, pretty in candidates) prompt = self.cnf.prompt % (context, name, cand_str) - raw = self._chat(prompt, schema=self._candidate_schema(candidates)) + raw = one_chat( + self.cnf, self._client, + prompt, schema=self._candidate_schema(candidates) + ) answer = self._extract_cui(raw) valid = {cui for cui, _ in candidates} return answer if answer in valid else None diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py b/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py index a48fa5bd3..546d0827a 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py @@ -19,6 +19,7 @@ LLMConnectionConfig, MisconfiguredComponentException, UnknownSpanException, + one_chat, ) logger = logging.getLogger(__name__) @@ -78,7 +79,9 @@ def _parse_csv(self, raw: str) -> list[tuple[str, int, int]]: return out def _call_api_raw(self, text: str) -> list[tuple[str, int, int]]: - raw = self._chat(self.cnf.prompt % text) + raw = one_chat( + self.cnf, self._client, + self.cnf.prompt % text) return self._parse_csv(raw) def _get_real_start_end( From 91e88435c295974cbc2f64ed1fdd3adca90b1395 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Thu, 5 Nov 2026 09:23:44 +0000 Subject: [PATCH 03/23] Create greater separation for LLM-interactions for future multiprocessing --- .../src/medcat_llm_components/base.py | 74 ++++++++++--------- .../src/medcat_llm_components/linker.py | 43 +++++------ .../src/medcat_llm_components/ner.py | 3 +- 3 files changed, 62 insertions(+), 58 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py index e3863d48b..bd0c70501 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py @@ -155,42 +155,44 @@ def __init__(self, cnf: LLMConnectionConfig) -> None: # don't keep paying a failed round-trip to rediscover that self._structured_output_supported = cnf.use_structured_output - _FENCE_RE = re.compile(r"^```[a-zA-Z]*\n|\n```$") - _TABLE_ROW_RE = re.compile(r"^\|.*\|$") - _TABLE_SEP_RE = re.compile(r"^[\s|:-]+$") - - def _clean_response(self, raw: str) -> str: - text = raw.strip() - # models wrap output in ```csv/```json fences despite instructions not to - text = self._FENCE_RE.sub("", text).strip() - return self._strip_markdown_table(text) - - def _strip_markdown_table(self, text: str) -> str: - r"""Small/instruction-weak models sometimes wrap the requested - CSV/plain output in a markdown table instead - either one field - per cell (`| entity | start | end |`) or, just as often, the - whole line squished into a single cell (`| entity,start,end |`). - Detected structurally (every non-empty line is pipe-wrapped) so - it doesn't depend on the exact header text; both variants above - collapse to the same comma-joined output. - - Only triggers when the *entire* response looks like a table. - Prose mixed with a table (e.g. "Here are the entities:\n| ... |") - isn't handled - that needs pulling the table out of surrounding - text, a step up in complexity from a plain cleanup pass. - """ - non_empty = [ln.strip() for ln in text.splitlines() if ln.strip()] - if not non_empty or not all( - self._TABLE_ROW_RE.match(ln) for ln in non_empty): - return text - - out_lines = [] - for ln in non_empty: - if self._TABLE_SEP_RE.match(ln): - continue # header-separator row - cells = [c.strip() for c in ln.strip("|").split("|")] - out_lines.append(",".join(cells) if len(cells) > 1 else cells[0]) - return "\n".join(out_lines) + +_FENCE_RE = re.compile(r"^```[a-zA-Z]*\n|\n```$") +_TABLE_ROW_RE = re.compile(r"^\|.*\|$") +_TABLE_SEP_RE = re.compile(r"^[\s|:-]+$") + + +def clean_response(raw: str) -> str: + text = raw.strip() + # models wrap output in ```csv/```json fences despite instructions not to + text = _FENCE_RE.sub("", text).strip() + return _strip_markdown_table(text) + +def _strip_markdown_table(text: str) -> str: + r"""Small/instruction-weak models sometimes wrap the requested + CSV/plain output in a markdown table instead - either one field + per cell (`| entity | start | end |`) or, just as often, the + whole line squished into a single cell (`| entity,start,end |`). + Detected structurally (every non-empty line is pipe-wrapped) so + it doesn't depend on the exact header text; both variants above + collapse to the same comma-joined output. + + Only triggers when the *entire* response looks like a table. + Prose mixed with a table (e.g. "Here are the entities:\n| ... |") + isn't handled - that needs pulling the table out of surrounding + text, a step up in complexity from a plain cleanup pass. + """ + non_empty = [ln.strip() for ln in text.splitlines() if ln.strip()] + if not non_empty or not all( + _TABLE_ROW_RE.match(ln) for ln in non_empty): + return text + + out_lines = [] + for ln in non_empty: + if _TABLE_SEP_RE.match(ln): + continue # header-separator row + cells = [c.strip() for c in ln.strip("|").split("|")] + out_lines.append(",".join(cells) if len(cells) > 1 else cells[0]) + return "\n".join(out_lines) class MisconfiguredComponentException(ValueError): diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index a11c5e6ed..f36be0518 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -17,6 +17,7 @@ LLMConnectionConfig, MisconfiguredComponentException, one_chat, + clean_response, ) logger = logging.getLogger(__name__) @@ -35,6 +36,19 @@ class LLMLinkConfig(LLMConnectionConfig): "(cui: name):\n%s" ) +def _extract_cui(raw: str) -> str: + text = clean_response(raw) + try: + return json.loads(text)["cui"].strip() + except (json.JSONDecodeError, KeyError, TypeError): + return text # freeform fallback: model just replied with the CUI/NONE + + +def _pick_cui(raw: str, candidates: list[tuple[str, str]]): + answer = _extract_cui(raw) + valid = {cui for cui, _ in candidates} + return answer if answer in valid else None + class LLMLinker(AbstractLLMEntityComponent): name = "llm_linker" @@ -56,26 +70,6 @@ def _candidate_schema(self, candidates: list[tuple[str, str]]) -> dict[str, Any] "required": ["cui"], } - def _extract_cui(self, raw: str) -> str: - text = self._clean_response(raw) - try: - return json.loads(text)["cui"] - except (json.JSONDecodeError, KeyError, TypeError): - return text # freeform fallback: model just replied with the CUI/NONE - - def _pick_cui( - self, context: str, name: str, candidates: list[tuple[str, str]] - ) -> str | None: - cand_str = "\n".join(f"{cui}: {pretty}" for cui, pretty in candidates) - prompt = self.cnf.prompt % (context, name, cand_str) - raw = one_chat( - self.cnf, self._client, - prompt, schema=self._candidate_schema(candidates) - ) - answer = self._extract_cui(raw) - valid = {cui for cui, _ in candidates} - return answer if answer in valid else None - def predict_entities( self, doc: MutableDocument, ents: list[MutableEntity] | None = None ) -> list[MutableEntity]: @@ -91,7 +85,14 @@ def predict_entities( continue start = max(0, ent.base.start_char_index - self.cnf.context_window) end = min(len(text), ent.base.end_char_index + self.cnf.context_window) - cui = self._pick_cui(text[start:end], ent.base.text, candidates) + cand_str = "\n".join(f"{cui}: {pretty}" for cui, pretty in candidates) + context = text[start:end] + prompt = self.cnf.prompt % (context, ent.base.text, cand_str) + raw = one_chat( + self.cnf, self._client, + prompt, schema=self._candidate_schema(candidates) + ) + cui = _pick_cui(raw, candidates) if cui is not None: ent.cui = cui # NOTE: attribute name is a guess - adjust to MutableEntity's real API # we did not do that, really - but for downstream filtering diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py b/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py index 546d0827a..8b9bb310e 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py @@ -20,6 +20,7 @@ MisconfiguredComponentException, UnknownSpanException, one_chat, + clean_response, ) logger = logging.getLogger(__name__) @@ -62,7 +63,7 @@ def get_type(self) -> CoreComponentType: return CoreComponentType.ner def _parse_csv(self, raw: str) -> list[tuple[str, int, int]]: - text = self._clean_response(raw) + text = clean_response(raw) if not text: return [] reader = csv.DictReader(io.StringIO(text)) From cbc318afed1790683f3866064f3a8523e4efcce8 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Thu, 5 Nov 2026 09:25:23 +0000 Subject: [PATCH 04/23] Minot linting fix --- medcat-plugins/llm-comps/src/medcat_llm_components/linker.py | 2 +- medcat-plugins/llm-comps/src/medcat_llm_components/ner.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index f36be0518..bdf0b675a 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -16,8 +16,8 @@ AbstractLLMEntityComponent, LLMConnectionConfig, MisconfiguredComponentException, - one_chat, clean_response, + one_chat, ) logger = logging.getLogger(__name__) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py b/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py index 8b9bb310e..c1b9f56a0 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/ner.py @@ -19,8 +19,8 @@ LLMConnectionConfig, MisconfiguredComponentException, UnknownSpanException, - one_chat, clean_response, + one_chat, ) logger = logging.getLogger(__name__) From e53483499a7e37c63282bf79594b1e40e0b56435 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Thu, 5 Nov 2026 09:30:10 +0000 Subject: [PATCH 05/23] Move stuff around in prep for multiprocessing --- .../src/medcat_llm_components/linker.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index bdf0b675a..0e59b0d38 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -70,6 +70,19 @@ def _candidate_schema(self, candidates: list[tuple[str, str]]) -> dict[str, Any] "required": ["cui"], } + def _prep_prompt( + self, + text: str, + ent: MutableEntity, + candidates: list[tuple[str, str]], + ) -> str: + start = max(0, ent.base.start_char_index - self.cnf.context_window) + end = min(len(text), ent.base.end_char_index + self.cnf.context_window) + cand_str = "\n".join(f"{cui}: {pretty}" for cui, pretty in candidates) + context = text[start:end] + prompt = self.cnf.prompt % (context, ent.base.text, cand_str) + return prompt + def predict_entities( self, doc: MutableDocument, ents: list[MutableEntity] | None = None ) -> list[MutableEntity]: @@ -83,11 +96,7 @@ def predict_entities( candidates = self.candidate_fn(ent.detected_name) if not candidates: continue - start = max(0, ent.base.start_char_index - self.cnf.context_window) - end = min(len(text), ent.base.end_char_index + self.cnf.context_window) - cand_str = "\n".join(f"{cui}: {pretty}" for cui, pretty in candidates) - context = text[start:end] - prompt = self.cnf.prompt % (context, ent.base.text, cand_str) + prompt = self._prep_prompt(text, ent, candidates) raw = one_chat( self.cnf, self._client, prompt, schema=self._candidate_schema(candidates) From 23442de49542ad8c7c1a05d88459c8bb8d3b3d95 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Thu, 5 Nov 2026 09:35:17 +0000 Subject: [PATCH 06/23] Do linker context preparation once --- .../src/medcat_llm_components/linker.py | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index 0e59b0d38..f04c4882c 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -3,7 +3,7 @@ import json import logging from collections.abc import Callable -from typing import Any +from typing import Any, Iterable from medcat.cdb import CDB from medcat.components.types import CoreComponentType @@ -83,6 +83,19 @@ def _prep_prompt( prompt = self.cnf.prompt % (context, ent.base.text, cand_str) return prompt + def _prepare_contexts( + self, + doc: MutableDocument, + ents: list[MutableEntity], + ) -> Iterable[tuple[int, str, list[tuple[str, str]]]]: + text = doc.base.text + for idx, ent in enumerate(ents): + candidates = self.candidate_fn(ent.detected_name) + if not candidates: + continue + prompt = self._prep_prompt(text, ent, candidates) + yield idx, prompt, candidates + def predict_entities( self, doc: MutableDocument, ents: list[MutableEntity] | None = None ) -> list[MutableEntity]: @@ -91,17 +104,14 @@ def predict_entities( raise NotImplementedError( "MyLLMLinker only implements the linking step (ents " "required); use MyLLMNER for the NER step.") - text = doc.base.text - for ent in ents: - candidates = self.candidate_fn(ent.detected_name) - if not candidates: - continue - prompt = self._prep_prompt(text, ent, candidates) + all_contexts = self._prepare_contexts(doc, ents) + for ent_idx, prompt, candidates in all_contexts: raw = one_chat( self.cnf, self._client, prompt, schema=self._candidate_schema(candidates) ) cui = _pick_cui(raw, candidates) + ent = ents[ent_idx] if cui is not None: ent.cui = cui # NOTE: attribute name is a guess - adjust to MutableEntity's real API # we did not do that, really - but for downstream filtering From e982ae919822651bbc9a88e15eddb30527501a79 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Thu, 5 Nov 2026 10:38:53 +0000 Subject: [PATCH 07/23] Allow multiprocessing for linker --- .../src/medcat_llm_components/linker.py | 71 +++++++++++++++---- 1 file changed, 59 insertions(+), 12 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index f04c4882c..27c71c03b 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -2,8 +2,8 @@ import json import logging -from collections.abc import Callable -from typing import Any, Iterable +from collections.abc import Callable, Iterable +from typing import Any from medcat.cdb import CDB from medcat.components.types import CoreComponentType @@ -35,6 +35,7 @@ class LLMLinkConfig(LLMConnectionConfig): "'NONE' if none fit.\n\nCONTEXT:\n%s\n\nTERM: %s\n\nCANDIDATES " "(cui: name):\n%s" ) + prompt_multiprocess_threads: int = 4 def _extract_cui(raw: str) -> str: text = clean_response(raw) @@ -96,15 +97,12 @@ def _prepare_contexts( prompt = self._prep_prompt(text, ent, candidates) yield idx, prompt, candidates - def predict_entities( - self, doc: MutableDocument, ents: list[MutableEntity] | None = None + def _predict_entities_with_context_sequential( + self, + ents: list[MutableEntity], + all_contexts: Iterable[tuple[int, str, list[tuple[str ,str]]]], ) -> list[MutableEntity]: linked_ents: list[MutableEntity] = [] - if ents is None: - raise NotImplementedError( - "MyLLMLinker only implements the linking step (ents " - "required); use MyLLMNER for the NER step.") - all_contexts = self._prepare_contexts(doc, ents) for ent_idx, prompt, candidates in all_contexts: raw = one_chat( self.cnf, self._client, @@ -113,12 +111,61 @@ def predict_entities( cui = _pick_cui(raw, candidates) ent = ents[ent_idx] if cui is not None: - ent.cui = cui # NOTE: attribute name is a guess - adjust to MutableEntity's real API - # we did not do that, really - but for downstream filtering - ent.context_similarity = ent.confidence = 1.0 + self._update_entity(ent, cui) linked_ents.append(ent) return linked_ents + def _update_entity(self, ent: MutableEntity, cui: str) -> None: + ent.cui = cui + # we did not do that, really - but for downstream filtering + ent.context_similarity = ent.confidence = 1.0 + + def _predict_entities_with_context_mp( + self, + ents: list[MutableEntity], + all_contexts: Iterable[tuple[int, str, list[tuple[str ,str]]]], + ) -> list[MutableEntity]: + from concurrent.futures import ThreadPoolExecutor, as_completed + max_workers = self.cnf.prompt_multiprocess_threads + linked_ents: list[MutableEntity | None] = [None for _ in all_contexts] + with ThreadPoolExecutor(max_workers=max_workers) as executor: + # Submit all tasks + future_to_id_cands = { + executor.submit( + one_chat, + self.cnf, + self._client, + prompt, + self._candidate_schema(cands)): (idx, cands) + for idx, prompt, cands in all_contexts} + + # Collect results as they complete + for future in as_completed(future_to_id_cands): + raw_result = future.result() + ent_idx, cands = future_to_id_cands[future] + cui = _pick_cui(raw_result, cands) + ent = ents[ent_idx] + if cui is not None: + self._update_entity(ent, cui) + linked_ents.append(ent) + return [e for e in linked_ents if e is not None] + + def predict_entities( + self, doc: MutableDocument, ents: list[MutableEntity] | None = None + ) -> list[MutableEntity]: + if ents is None: + raise NotImplementedError( + "MyLLMLinker only implements the linking step (ents " + "required); use MyLLMNER for the NER step.") + all_contexts = self._prepare_contexts(doc, ents) + if self.cnf.prompt_multiprocess_threads <= 1: + return self._predict_entities_with_context_sequential( + ents, all_contexts + ) + return self._predict_entities_with_context_mp( + ents, all_contexts + ) + @classmethod def create_new_component( cls, From 52f764d41350f703e8024178327b7f12ac7ac708 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 9 Nov 2026 11:33:50 +0000 Subject: [PATCH 08/23] Fix minor issue with linking --- medcat-plugins/llm-comps/src/medcat_llm_components/linker.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index 27c71c03b..8a1fb5668 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -127,7 +127,7 @@ def _predict_entities_with_context_mp( ) -> list[MutableEntity]: from concurrent.futures import ThreadPoolExecutor, as_completed max_workers = self.cnf.prompt_multiprocess_threads - linked_ents: list[MutableEntity | None] = [None for _ in all_contexts] + linked_ents: list[MutableEntity] = [] with ThreadPoolExecutor(max_workers=max_workers) as executor: # Submit all tasks future_to_id_cands = { @@ -148,7 +148,7 @@ def _predict_entities_with_context_mp( if cui is not None: self._update_entity(ent, cui) linked_ents.append(ent) - return [e for e in linked_ents if e is not None] + return linked_ents def predict_entities( self, doc: MutableDocument, ents: list[MutableEntity] | None = None From d963226beaf67919bc3c969d67217bf6358b6908 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 9 Nov 2026 12:20:21 +0000 Subject: [PATCH 09/23] Include status in candidates --- .../src/medcat_llm_components/linker.py | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index 8a1fb5668..350d3ecc0 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -23,7 +23,7 @@ logger = logging.getLogger(__name__) -CandidateFn = Callable[[str], list[tuple[str, str]]] +CandidateFn = Callable[[str], list[tuple[str, str, str]]] class LLMLinkConfig(LLMConnectionConfig): @@ -45,9 +45,9 @@ def _extract_cui(raw: str) -> str: return text # freeform fallback: model just replied with the CUI/NONE -def _pick_cui(raw: str, candidates: list[tuple[str, str]]): +def _pick_cui(raw: str, candidates: list[tuple[str, str, str]]): answer = _extract_cui(raw) - valid = {cui for cui, _ in candidates} + valid = {cui for cui, _, _ in candidates} return answer if answer in valid else None @@ -62,11 +62,11 @@ def __init__(self, cnf: LLMLinkConfig, candidate_fn: CandidateFn) -> None: def get_type(self) -> CoreComponentType: return CoreComponentType.linking - def _candidate_schema(self, candidates: list[tuple[str, str]]) -> dict[str, Any]: + def _candidate_schema(self, candidates: list[tuple[str, str, str]]) -> dict[str, Any]: return { "type": "object", "properties": { - "cui": {"type": "string", "enum": [c for c, _ in candidates] + ["NONE"]}, + "cui": {"type": "string", "enum": [c for c, _, _ in candidates] + ["NONE"]}, }, "required": ["cui"], } @@ -75,11 +75,11 @@ def _prep_prompt( self, text: str, ent: MutableEntity, - candidates: list[tuple[str, str]], + candidates: list[tuple[str, str, str]], ) -> str: start = max(0, ent.base.start_char_index - self.cnf.context_window) end = min(len(text), ent.base.end_char_index + self.cnf.context_window) - cand_str = "\n".join(f"{cui}: {pretty}" for cui, pretty in candidates) + cand_str = "\n".join(f"{cui}: {pretty}" for cui, pretty, status in candidates) context = text[start:end] prompt = self.cnf.prompt % (context, ent.base.text, cand_str) return prompt @@ -88,7 +88,7 @@ def _prepare_contexts( self, doc: MutableDocument, ents: list[MutableEntity], - ) -> Iterable[tuple[int, str, list[tuple[str, str]]]]: + ) -> Iterable[tuple[int, str, list[tuple[str, str, str]]]]: text = doc.base.text for idx, ent in enumerate(ents): candidates = self.candidate_fn(ent.detected_name) @@ -100,7 +100,7 @@ def _prepare_contexts( def _predict_entities_with_context_sequential( self, ents: list[MutableEntity], - all_contexts: Iterable[tuple[int, str, list[tuple[str ,str]]]], + all_contexts: Iterable[tuple[int, str, list[tuple[str, str ,str]]]], ) -> list[MutableEntity]: linked_ents: list[MutableEntity] = [] for ent_idx, prompt, candidates in all_contexts: @@ -123,7 +123,7 @@ def _update_entity(self, ent: MutableEntity, cui: str) -> None: def _predict_entities_with_context_mp( self, ents: list[MutableEntity], - all_contexts: Iterable[tuple[int, str, list[tuple[str ,str]]]], + all_contexts: Iterable[tuple[int, str, list[tuple[str, str ,str]]]], ) -> list[MutableEntity]: from concurrent.futures import ThreadPoolExecutor, as_completed max_workers = self.cnf.prompt_multiprocess_threads @@ -176,11 +176,11 @@ def create_new_component( model_load_path: str | None, ) -> LLMLinker: - def get_candidates(name: str) -> list[tuple[str, str]]: + def get_candidates(name: str) -> list[tuple[str, str, str]]: if name not in cdb.name2info: return [] - return [(cui, cdb.get_name(cui)) for - cui in cdb.name2info[name]['per_cui_status']] + return [(cui, cdb.get_name(cui), status) for + cui, status in cdb.name2info[name]['per_cui_status'].items()] if not isinstance(cnf, Linking): raise MisconfiguredComponentException( "Wrong type of config on config.linking - " From 77268a9e7b220302511e23325e37f2814e74a845 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 9 Nov 2026 12:30:06 +0000 Subject: [PATCH 10/23] Allow skipping clear-match concept queries --- .../src/medcat_llm_components/linker.py | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index 350d3ecc0..8d9326948 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -5,12 +5,15 @@ from collections.abc import Callable, Iterable from typing import Any +from openai import OpenAI + from medcat.cdb import CDB from medcat.components.types import CoreComponentType from medcat.config.config import ComponentConfig, Linking from medcat.tokenizing.tokenizers import BaseTokenizer from medcat.tokenizing.tokens import MutableDocument, MutableEntity from medcat.vocab import Vocab +from medcat.utils.defaults import StatusTypes from .base import ( AbstractLLMEntityComponent, @@ -51,6 +54,20 @@ def _pick_cui(raw: str, candidates: list[tuple[str, str, str]]): return answer if answer in valid else None +def _one_chat( + cnf: LLMLinkConfig, + client: OpenAI, + prompt: str, + schema: dict[str, Any] | None, + candidates: list[tuple[str, str, str]], +) -> str: + if len(candidates) == 1 and candidates[0][2] not in StatusTypes.DO_DISAMBUGATION: + return candidates[0][0] + return one_chat( + cnf, client, prompt, schema + ) + + class LLMLinker(AbstractLLMEntityComponent): name = "llm_linker" @@ -104,9 +121,10 @@ def _predict_entities_with_context_sequential( ) -> list[MutableEntity]: linked_ents: list[MutableEntity] = [] for ent_idx, prompt, candidates in all_contexts: - raw = one_chat( + raw = _one_chat( self.cnf, self._client, - prompt, schema=self._candidate_schema(candidates) + prompt, schema=self._candidate_schema(candidates), + candidates=candidates, ) cui = _pick_cui(raw, candidates) ent = ents[ent_idx] @@ -132,11 +150,13 @@ def _predict_entities_with_context_mp( # Submit all tasks future_to_id_cands = { executor.submit( - one_chat, + _one_chat, self.cnf, self._client, prompt, - self._candidate_schema(cands)): (idx, cands) + self._candidate_schema(cands), + cands, + ): (idx, cands) for idx, prompt, cands in all_contexts} # Collect results as they complete From 0ddd9344556b456c306724ee1f22a3983a8dad32 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 9 Nov 2026 12:31:03 +0000 Subject: [PATCH 11/23] Update prompt somewhat --- medcat-plugins/llm-comps/src/medcat_llm_components/linker.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index 8d9326948..131037d86 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -35,7 +35,8 @@ class LLMLinkConfig(LLMConnectionConfig): prompt: str = ( "Given the surrounding text and a medical term found in it, pick " "the single best matching concept from the candidates below, or " - "'NONE' if none fit.\n\nCONTEXT:\n%s\n\nTERM: %s\n\nCANDIDATES " + "'NONE' if none fit. Only return the specific concept ID and " + "nothing else.\n\nCONTEXT:\n%s\n\nTERM: %s\n\nCANDIDATES " "(cui: name):\n%s" ) prompt_multiprocess_threads: int = 4 From 5a17e076e8fc75c83274b93204e571c8456ea9b7 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 9 Nov 2026 15:29:08 +0000 Subject: [PATCH 12/23] Remove debug output --- medcat-plugins/llm-comps/src/medcat_llm_components/base.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py index bd0c70501..5e259b798 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py @@ -131,7 +131,6 @@ def _one_call( "type": "json_schema", "json_schema": {"name": "response", "schema": schema, "strict": True}, } - print(" - C w prompt len", len(prompt)) try: resp = client.chat.completions.create(**kwargs) except APIError as exc: @@ -140,6 +139,7 @@ def _one_call( raise return resp.choices[0].message.content or "" + class AbstractLLMEntityComponent(AbstractEntityProvidingComponent, ABC): """Shared connection / chat / cleanup plumbing for LLM-based components. @@ -167,6 +167,7 @@ def clean_response(raw: str) -> str: text = _FENCE_RE.sub("", text).strip() return _strip_markdown_table(text) + def _strip_markdown_table(text: str) -> str: r"""Small/instruction-weak models sometimes wrap the requested CSV/plain output in a markdown table instead - either one field From cdffcb1b2072a863fe5bdd748b8fa7a82c403f27 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 16 Nov 2026 10:50:41 +0000 Subject: [PATCH 13/23] Add pure LLM component --- .../medcat_llm_components/pure_llm_linker.py | 305 ++++++++++++++++++ 1 file changed, 305 insertions(+) create mode 100644 medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py new file mode 100644 index 000000000..32ceb9aae --- /dev/null +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py @@ -0,0 +1,305 @@ +from __future__ import annotations + +import json +import logging +import re +from typing import Any + +from medcat.cdb import CDB +from medcat.components.types import CoreComponentType +from medcat.config.config import ComponentConfig, Linking +from medcat.tokenizing.tokenizers import BaseTokenizer +from medcat.tokenizing.tokens import MutableDocument, MutableEntity +from medcat.vocab import Vocab +from openai import APIConnectionError, APIError, APITimeoutError + +from .base import ( + AbstractLLMEntityComponent, + LLMConnectionConfig, + MisconfiguredComponentException, + clean_response, + one_chat, +) + +logger = logging.getLogger(__name__) + +_THINK_RE = re.compile(r".*?", flags=re.DOTALL) + + +class NoSuchSpan(ValueError): + """Raised when a reported span cannot be found in the source text.""" + + +class PureLLMLinkConfig(LLMConnectionConfig): + """Config for a linker that detects and links in a single LLM call. + + The model sees the whole document plus every concept in the CDB. + Connection details (``base_url``, ``api_key``, ``model``, + ``temperature``, ``timeout``, ``retries``) come from + ``LLMConnectionConfig``. ``timeout`` and ``retries`` default to the + values the standalone script used. + """ + + comp_name: str = "pure_llm_linker" + model: str = "qwen3.8:27b" + timeout: float = 600.0 + retries: int = 5 + # Qwen-style servers otherwise spend the timeout on a hidden + # reasoning trace. Set ``reasoning_effort`` to None to omit it, + # and ``enable_thinking`` to True to leave thinking on. + reasoning_effort: str | None = "none" + enable_thinking: bool = False + + prompt_opt_list_placeholder: str = "{##OPTIONS##}" + prompt_doc_placeholder: str = "{##DOC##}" + prompt: str = f""" + Identify all medical concepts (i.e the spans) in the text provided + and map them to the correct Snomed codes. The possible Snomed codes + are listed here in the format "CUI (name)": {prompt_opt_list_placeholder}. + + Respond in JSON format with the following schema, include no other response: + {{ + "entities": [ + {{ + "value": "val-str", + "start_char_index": 0, + "cui": "91936005" + }}, + # and so on + ] + }} + + In the above: + value - the exact string in the text that was identified as a medical term + start_char_index - the character index where the value starts + cui - the concept ID (from the list above) + + The text to process is as follows: + {prompt_doc_placeholder} + """ + + +def _strip_model_wrappers(raw: str) -> str: + text = _THINK_RE.sub("", raw) + return clean_response(text) + + +def find_start( + orig_doc: str, + orig_name: str, + raw_start_char: int, + in_lower_case: bool = False, +) -> int: + """Reconcile a model-reported start index with the source text. + + Uses the reported index when the span matches there. Otherwise + searches for the surface form and, if it occurs more than once, + picks the occurrence closest to the reported index. Falls back to + a case-insensitive search once. + """ + doc = orig_doc.lower() if in_lower_case else orig_doc + name = orig_name.lower() if in_lower_case else orig_name + name_len = len(name) + if ( + name + and 0 <= raw_start_char <= len(doc) - name_len + and doc[raw_start_char:raw_start_char + name_len] == name + ): + return raw_start_char + found = list(re.finditer(re.escape(name), doc)) if name else [] + if len(found) == 1: + # A unique hit can still be the wrong mention, but there is + # nothing else to disambiguate against. + return found[0].start() + if len(found) > 1: + return min(found, key=lambda m: abs(raw_start_char - m.start())).start() + if in_lower_case: + raise NoSuchSpan(f"No span {name!r} found in document") + return find_start(orig_doc, orig_name, raw_start_char, in_lower_case=True) + + +def parse_output( + doc: str, + raw_response: str, + valid_cuis: set[str], +) -> list[tuple[int, str, str]]: + """Turn one model response into ``(start, surface, cui)`` triples.""" + cleaned = _strip_model_wrappers(raw_response) + try: + payload = json.loads(cleaned.strip()) + entities = payload["entities"] + except (json.JSONDecodeError, KeyError, TypeError, AttributeError) as exc: + logger.warning( + "Unparseable LLM response (%s). Raw response starts: %r", + exc, raw_response[:500]) + return [] + if not isinstance(entities, list): + logger.warning("LLM response 'entities' is not a list: %r", entities) + return [] + + linked: list[tuple[int, str, str]] = [] + for rn, ent in enumerate(entities): + try: + name = ent["value"] + raw_start_char = ent["start_char_index"] + cui = str(ent["cui"]).strip() + except (KeyError, TypeError, AttributeError): + logger.warning("Malformed entity at row %s: %r", rn, ent) + continue + if cui not in valid_cuis: + logger.warning( + "Dropping row %s (%r): cui %s is not in the candidate list", + rn, name, cui) + continue + try: + real_start_char = find_start(doc, name, raw_start_char) + except (NoSuchSpan, TypeError, ValueError): + window = 20 + start_at = raw_start_char if isinstance(raw_start_char, int) else 0 + context = doc[max(start_at - window, 0):start_at + len(str(name)) + window] + logger.warning( + "Could not place row %s: %r, %s @ %s. Nearby text: %r", + rn, name, cui, raw_start_char, context) + continue + linked.append((real_start_char, name, cui)) + return linked + + +class PureLLMLinker(AbstractLLMEntityComponent): + """Detect and link concepts with one prompt per document. + + Upstream NER entities are ignored. Each document is sent to the + model together with the full candidate list taken from the CDB, + and the JSON response is reconciled back into MedCAT entities. + """ + + name = "pure_llm_linker" + + def __init__( + self, + cnf: PureLLMLinkConfig, + tokenizer: BaseTokenizer, + name_separator: str, + all_candidates: list[tuple[str, str]], + ) -> None: + super().__init__(cnf) + self.cnf: PureLLMLinkConfig = cnf + self._tokenizer = tokenizer + self._name_separator = name_separator + self._all_candidates = all_candidates + self._valid_cuis = {cui for cui, _ in all_candidates} + self._all_candidates_str = ", ".join( + f"{cui} ({name})" for cui, name in all_candidates) + + def get_type(self) -> CoreComponentType: + return CoreComponentType.linking + + def _response_schema(self) -> dict[str, Any]: + return { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "value": {"type": "string"}, + "start_char_index": {"type": "integer"}, + "cui": {"type": "string"}, + }, + "required": ["value", "start_char_index", "cui"], + "additionalProperties": False, + }, + }, + }, + "required": ["entities"], + "additionalProperties": False, + } + + def _request_kwargs(self) -> dict[str, Any]: + extra: dict[str, Any] = {} + if self.cnf.reasoning_effort is not None: + extra["reasoning_effort"] = self.cnf.reasoning_effort + if not self.cnf.enable_thinking: + extra["extra_body"] = { + "chat_template_kwargs": {"enable_thinking": False}, + } + return extra + + def _prep_prompt(self, text: str) -> str: + prompt = self.cnf.prompt.replace( + self.cnf.prompt_opt_list_placeholder, self._all_candidates_str) + return prompt.replace(self.cnf.prompt_doc_placeholder, text) + + def _to_entities( + self, + doc: MutableDocument, + raw_ents: list[tuple[int, str, str]], + ) -> list[MutableEntity]: + out_ents: list[MutableEntity] = [] + seen: set[tuple[int, int]] = set() + for ent_id, (start_char_index, raw_name, cui) in enumerate(raw_ents): + end_char_index = start_char_index + len(raw_name) + if (start_char_index, end_char_index) in seen: + continue + tkns = [ + tkn for tkn in doc.get_tokens(start_char_index, end_char_index) + if not tkn.to_skip + ] + if not tkns: + logger.warning( + "Unable to tokenize %r (%s) @ [%s:%s] %r", + raw_name, cui, start_char_index, end_char_index, + doc.base.text[start_char_index:end_char_index]) + continue + entity = self._tokenizer.entity_from_tokens_in_doc(tkns, doc) + entity.cui = cui + entity.detected_name = self._name_separator.join( + tkn.base.text.lower() for tkn in tkns) + entity.link_candidates = [cui] + entity.confidence = entity.context_similarity = 1.0 + entity.id = ent_id + out_ents.append(entity) + seen.add((start_char_index, end_char_index)) + return out_ents + + def predict_entities( + self, doc: MutableDocument, ents: list[MutableEntity] | None = None + ) -> list[MutableEntity]: + text = doc.base.text + try: + raw = one_chat( + self.cnf, + self._client, + self._prep_prompt(text), + schema=self._response_schema(), + request_kwargs=self._request_kwargs(), + ) + except (APIConnectionError, APITimeoutError, APIError) as exc: + logger.warning("%s: giving up on document: %s", self.name, exc) + return [] + return self._to_entities(doc, parse_output(text, raw, self._valid_cuis)) + + @classmethod + def create_new_component( + cls, + cnf: ComponentConfig, + tokenizer: BaseTokenizer, + cdb: CDB, + vocab: Vocab, + model_load_path: str | None, + ) -> PureLLMLinker: + if not isinstance(cnf, Linking): + raise MisconfiguredComponentException( + "Wrong type of config on config.linking - " + f"Expected Linking, got {type(cnf).__name__}" + ) + llm_cnf = cnf.additional + if not isinstance(llm_cnf, PureLLMLinkConfig): + raise MisconfiguredComponentException( + "Wrong type of config on config.linking.additional - " + f"Expected PureLLMLinkConfig, got {type(llm_cnf).__name__}" + ) + all_candidates = [(cui, cdb.get_name(cui)) for cui in cdb.cui2info] + return cls( + llm_cnf, tokenizer, cdb.config.general.separator, all_candidates) From aea0706141bfe7c49f02ce62df84771ee3258e09 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 16 Nov 2026 10:51:11 +0000 Subject: [PATCH 14/23] Registr pure LLM component --- .../llm-comps/src/medcat_llm_components/registration.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/registration.py b/medcat-plugins/llm-comps/src/medcat_llm_components/registration.py index a5ceda184..2b6ea9924 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/registration.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/registration.py @@ -12,3 +12,7 @@ def do_registration(): lazy_register_core_component( CoreComponentType.linking, "llm_linker", "medcat_llm_components.linker", "LLMLinker.create_new_component") + lazy_register_core_component( + CoreComponentType.linking, "pure_llm_linker", + "medcat_llm_components.pure_llm_linker", + "PureLLMLinker.create_new_component") From 7b1851e69b3e5a2ab167555746865722708a3ac1 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 16 Nov 2026 12:28:52 +0000 Subject: [PATCH 15/23] Update base in line with changes for pure-llm component --- .../src/medcat_llm_components/base.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py index 5e259b798..e87b4341a 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/base.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/base.py @@ -83,18 +83,25 @@ def one_chat( client: OpenAI, prompt: str, schema: dict[str, Any] | None = None, + request_kwargs: dict[str, Any] | None = None, ) -> str: """Send `prompt` as a single user message, return the raw text response. `schema`, if given, requests structured output for this call specifically (falls back to freeform if the backend - rejects it). Retries transient connection/timeout failures.""" + rejects it). Retries transient connection/timeout failures. + + `request_kwargs` is merged into the chat-completions call for + backend-specific options (for example disabling reasoning). + Model, messages, temperature, and timeout always come from `cnf`. + """ structured_output_supported = cnf.use_structured_output use_schema = schema if structured_output_supported else None last_exc: Exception | None = None for attempt in range(cnf.retries + 1): try: - return _one_call(cnf, client, prompt, use_schema) + return _one_call( + cnf, client, prompt, use_schema, request_kwargs) except _StructuredOutputUnsupported: logger.warning( "%s: backend rejected structured output, falling " @@ -119,13 +126,17 @@ def _one_call( client: OpenAI, prompt: str, schema: dict[str, Any] | None, + request_kwargs: dict[str, Any] | None = None, ) -> str: - kwargs: dict[str, Any] = { + kwargs: dict[str, Any] = {} + if request_kwargs: + kwargs.update(request_kwargs) + kwargs.update({ "model": cnf.model, "messages": [{"role": "user", "content": prompt}], "temperature": cnf.temperature, "timeout": cnf.timeout, - } + }) if schema is not None: kwargs["response_format"] = { "type": "json_schema", From 41dcff7a132d6b762416569c85037e379640ac52 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 16 Nov 2026 12:29:21 +0000 Subject: [PATCH 16/23] Add tests for new component --- .../llm-comps/tests/test_pure_llm_linker.py | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 medcat-plugins/llm-comps/tests/test_pure_llm_linker.py diff --git a/medcat-plugins/llm-comps/tests/test_pure_llm_linker.py b/medcat-plugins/llm-comps/tests/test_pure_llm_linker.py new file mode 100644 index 000000000..fb07016ea --- /dev/null +++ b/medcat-plugins/llm-comps/tests/test_pure_llm_linker.py @@ -0,0 +1,96 @@ +import pytest + +from medcat.config.config import Linking, Ner +from medcat.cdb import CDB +from medcat.config import Config + +from medcat_llm_components.base import MisconfiguredComponentException +from medcat_llm_components.pure_llm_linker import ( + NoSuchSpan, + PureLLMLinkConfig, + PureLLMLinker, + find_start, + parse_output, +) + + +BASE = {"base_url": "http://localhost:9/v1", "model": "test-model"} + + +def test_find_start_uses_reported_index_when_it_matches(): + assert find_start("pain in the chest", "pain", 0) == 0 + + +def test_find_start_picks_the_closest_occurrence(): + text = "pain and then more pain later" + # "pain" starts at 0 and at 19. The closest index is not the + # position of that match in the match list. + assert find_start(text, "pain", 20) == 19 + + +def test_find_start_falls_back_to_case_insensitive_match(): + assert find_start("Has Diabetes mellitus", "diabetes mellitus", 4) == 4 + + +def test_find_start_raises_when_the_span_is_absent(): + with pytest.raises(NoSuchSpan): + find_start("no medical terms here", "diabetes", 0) + + +def test_parse_output_keeps_only_placeable_known_cuis(): + raw = """ + looking +```json + {"entities": [ + {"value": "pain", "start_char_index": 99, "cui": "111"}, + {"value": "nope", "start_char_index": 0, "cui": "111"}, + {"value": "pain", "start_char_index": 0, "cui": "999"}, + {"value": "missing-field", "cui": "111"} + ]} +``` + """ + assert parse_output("pain here", raw, {"111"}) == [(0, "pain", "111")] + + +def test_parse_output_returns_empty_on_garbage(): + assert parse_output("pain", "not json", {"111"}) == [] + + +def test_prompt_is_filled_from_config_and_candidates(): + cnf = PureLLMLinkConfig(**BASE) + linker = PureLLMLinker(cnf, tokenizer=None, name_separator="~", + all_candidates=[("111", "Pain")]) + prompt = linker._prep_prompt("patient has pain") + assert "111 (Pain)" in prompt + assert "patient has pain" in prompt + assert cnf.prompt_opt_list_placeholder not in prompt + assert cnf.prompt_doc_placeholder not in prompt + assert linker._request_kwargs()["reasoning_effort"] == "none" + assert linker._request_kwargs()["extra_body"] == { + "chat_template_kwargs": {"enable_thinking": False}, + } + + +def test_create_new_component_reads_candidates_from_the_cdb(): + config = Config() + cdb = CDB(config) + cdb.cui2info["111"] = { + "preferred_name": "Pain", + "names": {"Pain"}, + } + linking = Linking(additional=PureLLMLinkConfig(**BASE)) + linker = PureLLMLinker.create_new_component( + linking, tokenizer=None, cdb=cdb, vocab=None, model_load_path=None) + assert linker._all_candidates == [("111", "Pain")] + assert linker._name_separator == "~" + + +def test_create_new_component_rejects_the_wrong_config(): + with pytest.raises(MisconfiguredComponentException): + PureLLMLinker.create_new_component( + Ner(), tokenizer=None, cdb=CDB(Config()), vocab=None, + model_load_path=None) + with pytest.raises(MisconfiguredComponentException): + PureLLMLinker.create_new_component( + Linking(), tokenizer=None, cdb=CDB(Config()), vocab=None, + model_load_path=None) From b99610f2380f0dad6797bdbc2f70096e2b8cf8f8 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 16 Nov 2026 12:30:18 +0000 Subject: [PATCH 17/23] Add new component to registration tests --- medcat-plugins/llm-comps/tests/test_registration.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/medcat-plugins/llm-comps/tests/test_registration.py b/medcat-plugins/llm-comps/tests/test_registration.py index 3d4692ac4..ef62c1861 100644 --- a/medcat-plugins/llm-comps/tests/test_registration.py +++ b/medcat-plugins/llm-comps/tests/test_registration.py @@ -5,6 +5,7 @@ from medcat.cdb import CDB from medcat_llm_components.ner import LLMNERConfig from medcat_llm_components.linker import LLMLinkConfig +from medcat_llm_components.pure_llm_linker import PureLLMLinkConfig BASE_CNF_OPTS = { @@ -21,6 +22,9 @@ (CoreComponentType.linking, 'llm_linker', (Linking( additional=LLMLinkConfig(**BASE_CNF_OPTS), ), None, None, None)), + (CoreComponentType.linking, 'pure_llm_linker', (Linking( + additional=PureLLMLinkConfig(**BASE_CNF_OPTS), + ), None, None, None)), ] From 9b30926e7e8f51717219cb66a8ade2d3fbfee7e8 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Mon, 16 Nov 2026 12:53:06 +0000 Subject: [PATCH 18/23] Linting fixes --- medcat-plugins/llm-comps/src/medcat_llm_components/linker.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py index 131037d86..812781ccb 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py @@ -5,15 +5,14 @@ from collections.abc import Callable, Iterable from typing import Any -from openai import OpenAI - from medcat.cdb import CDB from medcat.components.types import CoreComponentType from medcat.config.config import ComponentConfig, Linking from medcat.tokenizing.tokenizers import BaseTokenizer from medcat.tokenizing.tokens import MutableDocument, MutableEntity -from medcat.vocab import Vocab from medcat.utils.defaults import StatusTypes +from medcat.vocab import Vocab +from openai import OpenAI from .base import ( AbstractLLMEntityComponent, From 77f8053ea26dba5689c900ff0a064906b00cc574 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Tue, 17 Nov 2026 09:07:57 +0000 Subject: [PATCH 19/23] Use filters instead of entire CUI list --- .../medcat_llm_components/pure_llm_linker.py | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py index 32ceb9aae..2bff8ae73 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py @@ -177,19 +177,36 @@ class PureLLMLinker(AbstractLLMEntityComponent): def __init__( self, + l_cnf: Linking, cnf: PureLLMLinkConfig, tokenizer: BaseTokenizer, name_separator: str, all_candidates: list[tuple[str, str]], ) -> None: super().__init__(cnf) + self.l_cnf = l_cnf self.cnf: PureLLMLinkConfig = cnf self._tokenizer = tokenizer self._name_separator = name_separator - self._all_candidates = all_candidates + self._all_candidates = dict(all_candidates) self._valid_cuis = {cui for cui, _ in all_candidates} + self._recreate_candidates() + + def _filter_changed(self) -> bool: + return ( + self.l_cnf.filters.cuis != self._cur_cui_include or + self.l_cnf.filters.cuis_exclude != self._cur_cui_exclude + ) + + def _recreate_candidates(self) -> None: + cui_include: set[str] = self.l_cnf.filters.cuis + cui_exclude: set[str] = self.l_cnf.filters.cuis_exclude self._all_candidates_str = ", ".join( - f"{cui} ({name})" for cui, name in all_candidates) + f"{cui} ({self._all_candidates[cui]})" for cui in cui_include + if self.l_cnf.filters.check_filters(cui) + ) + self._cur_cui_include = set(cui_include) + self._cur_cui_exclude = set(cui_exclude) def get_type(self) -> CoreComponentType: return CoreComponentType.linking @@ -302,4 +319,4 @@ def create_new_component( ) all_candidates = [(cui, cdb.get_name(cui)) for cui in cdb.cui2info] return cls( - llm_cnf, tokenizer, cdb.config.general.separator, all_candidates) + cnf, llm_cnf, tokenizer, cdb.config.general.separator, all_candidates) From bb1daaaf78fee25e35f3773c82bad2765febf342 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Tue, 17 Nov 2026 09:08:47 +0000 Subject: [PATCH 20/23] Add in-flight recalculation based on filters --- .../llm-comps/src/medcat_llm_components/pure_llm_linker.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py index 2bff8ae73..abda6bd48 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py @@ -283,6 +283,9 @@ def _to_entities( def predict_entities( self, doc: MutableDocument, ents: list[MutableEntity] | None = None ) -> list[MutableEntity]: + if self._filter_changed(): + logger.info("Recreating candidates based on new filter") + self._recreate_candidates() text = doc.base.text try: raw = one_chat( From cfba5994f33fa74b877e8e9db1aaddbdfead6f8c Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Tue, 17 Nov 2026 09:27:18 +0000 Subject: [PATCH 21/23] Fix no-filter case --- .../llm-comps/src/medcat_llm_components/pure_llm_linker.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py b/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py index abda6bd48..cfd924632 100644 --- a/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py +++ b/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py @@ -199,7 +199,7 @@ def _filter_changed(self) -> bool: ) def _recreate_candidates(self) -> None: - cui_include: set[str] = self.l_cnf.filters.cuis + cui_include: set[str] = self.l_cnf.filters.cuis or set(self._valid_cuis) cui_exclude: set[str] = self.l_cnf.filters.cuis_exclude self._all_candidates_str = ", ".join( f"{cui} ({self._all_candidates[cui]})" for cui in cui_include From abc34d8f4f4eb309a5a9978b9c95d339158550d7 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Tue, 17 Nov 2026 09:52:18 +0000 Subject: [PATCH 22/23] Update model creation to allow creating PureLLM component --- .../llm-comps/tests/test_save_load.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/medcat-plugins/llm-comps/tests/test_save_load.py b/medcat-plugins/llm-comps/tests/test_save_load.py index 1eb13e8f3..fbceaf91e 100644 --- a/medcat-plugins/llm-comps/tests/test_save_load.py +++ b/medcat-plugins/llm-comps/tests/test_save_load.py @@ -9,16 +9,20 @@ from medcat_llm_components.ner import LLMNERConfig from medcat_llm_components.linker import LLMLinkConfig +from medcat_llm_components.pure_llm_linker import PureLLMLinkConfig import pytest DEFAULT_BASE_URL = "my_ollama_ip:port/whatever" DEFAULT_MODEL = "gemma:2b" -DEFAULT_PROMPT_NER = "Never gonna give you up" +DEFAULT_PROMPT_NER = "Never gonna give you up: %s" DEFAULT_PROMPT_LINKER = "Never gonna let you go" -def create_new_llm_model(): +def create_new_llm_model( + default_ner: bool = False, + use_pure_llm_linker: bool = False, +): # the URL to the (e.g) ollama instance base_url = DEFAULT_BASE_URL @@ -33,16 +37,19 @@ def create_new_llm_model(): prompt=DEFAULT_PROMPT_NER, ) # linker - linking_cnf = LLMLinkConfig( + l_cnf_cls = PureLLMLinkConfig if use_pure_llm_linker else LLMLinkConfig + linking_cnf = l_cnf_cls( base_url=base_url, model=llm_model, prompt=DEFAULT_PROMPT_LINKER, ) config = Config() - config.components.ner.comp_name = "llm_ner" - config.components.ner.custom_cnf = ner_cnf - config.components.linking.comp_name = "llm_linker" + if not default_ner: + config.components.ner.comp_name = "llm_ner" + config.components.ner.custom_cnf = ner_cnf + config.components.linking.comp_name = ( + "pure_llm_linker" if use_pure_llm_linker else "llm_linker") config.components.linking.additional = linking_cnf vocab = Vocab() From a474c64e838d14e8ea8e516a3fc81f7c08a6d939 Mon Sep 17 00:00:00 2001 From: Mart Ratas Date: Tue, 17 Nov 2026 09:53:16 +0000 Subject: [PATCH 23/23] Add a few more pure LLM tests (e.g for filters) --- .../llm-comps/tests/test_pure_llm_linker.py | 66 ++++++++++++++++++- 1 file changed, 63 insertions(+), 3 deletions(-) diff --git a/medcat-plugins/llm-comps/tests/test_pure_llm_linker.py b/medcat-plugins/llm-comps/tests/test_pure_llm_linker.py index fb07016ea..241c8b03f 100644 --- a/medcat-plugins/llm-comps/tests/test_pure_llm_linker.py +++ b/medcat-plugins/llm-comps/tests/test_pure_llm_linker.py @@ -1,8 +1,13 @@ import pytest +import pandas as pd + from medcat.config.config import Linking, Ner +from medcat.components.types import CoreComponentType from medcat.cdb import CDB from medcat.config import Config +from medcat.stats import get_stats +from medcat.model_creation.cdb_maker import CDBMaker from medcat_llm_components.base import MisconfiguredComponentException from medcat_llm_components.pure_llm_linker import ( @@ -13,6 +18,8 @@ parse_output, ) +from test_save_load import create_new_llm_model + BASE = {"base_url": "http://localhost:9/v1", "model": "test-model"} @@ -57,8 +64,9 @@ def test_parse_output_returns_empty_on_garbage(): def test_prompt_is_filled_from_config_and_candidates(): - cnf = PureLLMLinkConfig(**BASE) - linker = PureLLMLinker(cnf, tokenizer=None, name_separator="~", + l_cnf = Linking() + l_cnf.additional = cnf = PureLLMLinkConfig(**BASE) + linker = PureLLMLinker(l_cnf, cnf, tokenizer=None, name_separator="~", all_candidates=[("111", "Pain")]) prompt = linker._prep_prompt("patient has pain") assert "111 (Pain)" in prompt @@ -81,7 +89,7 @@ def test_create_new_component_reads_candidates_from_the_cdb(): linking = Linking(additional=PureLLMLinkConfig(**BASE)) linker = PureLLMLinker.create_new_component( linking, tokenizer=None, cdb=cdb, vocab=None, model_load_path=None) - assert linker._all_candidates == [("111", "Pain")] + assert linker._all_candidates == {"111": "Pain"} assert linker._name_separator == "~" @@ -94,3 +102,55 @@ def test_create_new_component_rejects_the_wrong_config(): PureLLMLinker.create_new_component( Linking(), tokenizer=None, cdb=CDB(Config()), vocab=None, model_load_path=None) + + +filtered_cuis = ["C1"] +filtered_data = { + "projects": [ + { + "id": "1", + "name": "p1", + "cuis": ",".join(filtered_cuis), + "documents": [ + { + "id": "101", + "name": "D101", + "text": "This text is super long", + "annotations": [] + } + ] + } + ] +} + + +@pytest.fixture +def cat(): + cat = create_new_llm_model(True, True) + maker = CDBMaker(cat.config, cat.cdb) + df = pd.DataFrame( + [["C1", "NAME1"], ["C2", "NAME2"]], + columns=["cui", "name"], + ) + maker.prepare_csvs([df]) + cat._recreate_pipe() + return cat + + +def test_model_has_cuis(cat): + assert cat.cdb.cui2info + assert len(cat.cdb.cui2info) > 1 + + +def assert_pure_llm_linker_has_filter_cuis(cat, cuis): + linker = cat.pipe.get_component(CoreComponentType.linking) + assert isinstance(linker, PureLLMLinker) + assert linker._cur_cui_include == set(cuis) + + +def test_uses_correct_filters(cat): + # prev has all + assert_pure_llm_linker_has_filter_cuis(cat, set(cat.cdb.cui2info)) + get_stats(cat, filtered_data, use_project_filters=True) + # now has stuff in the filter + assert_pure_llm_linker_has_filter_cuis(cat, set(filtered_cuis))