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..e87b4341a 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,78 @@ 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,
+ 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.
+
+ `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, request_kwargs)
+ 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,
+ client: OpenAI,
+ prompt: str,
+ schema: dict[str, Any] | None,
+ request_kwargs: dict[str, Any] | None = None,
+) -> str:
+ 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",
+ "json_schema": {"name": "response", "schema": schema, "strict": True},
+ }
+ 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.
@@ -94,91 +166,45 @@ 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 self._one_call(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
-
- 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|:-]+$")
-
- 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 9d0176703..812781ccb 100644
--- a/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py
+++ b/medcat-plugins/llm-comps/src/medcat_llm_components/linker.py
@@ -2,7 +2,7 @@
import json
import logging
-from collections.abc import Callable
+from collections.abc import Callable, Iterable
from typing import Any
from medcat.cdb import CDB
@@ -10,18 +10,22 @@
from medcat.config.config import ComponentConfig, Linking
from medcat.tokenizing.tokenizers import BaseTokenizer
from medcat.tokenizing.tokens import MutableDocument, MutableEntity
+from medcat.utils.defaults import StatusTypes
from medcat.vocab import Vocab
+from openai import OpenAI
from .base import (
AbstractLLMEntityComponent,
LLMConnectionConfig,
MisconfiguredComponentException,
+ clean_response,
+ one_chat,
)
logger = logging.getLogger(__name__)
-CandidateFn = Callable[[str], list[tuple[str, str]]]
+CandidateFn = Callable[[str], list[tuple[str, str, str]]]
class LLMLinkConfig(LLMConnectionConfig):
@@ -30,9 +34,38 @@ 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
+
+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, str]]):
+ answer = _extract_cui(raw)
+ valid = {cui for cui, _, _ in candidates}
+ 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):
@@ -46,54 +79,112 @@ 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"],
}
- 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 = self._chat(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 _prep_prompt(
+ self,
+ text: str,
+ ent: MutableEntity,
+ 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, status in candidates)
+ context = text[start:end]
+ 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, 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_with_context_sequential(
+ self,
+ ents: list[MutableEntity],
+ 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:
+ raw = _one_chat(
+ self.cnf, self._client,
+ prompt, schema=self._candidate_schema(candidates),
+ candidates=candidates,
+ )
+ cui = _pick_cui(raw, candidates)
+ ent = ents[ent_idx]
+ if cui is not None:
+ 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 ,str]]]],
+ ) -> list[MutableEntity]:
+ from concurrent.futures import ThreadPoolExecutor, as_completed
+ max_workers = self.cnf.prompt_multiprocess_threads
+ linked_ents: list[MutableEntity] = []
+ 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),
+ 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 linked_ents
def predict_entities(
self, doc: MutableDocument, ents: list[MutableEntity] | None = None
) -> 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.")
- text = doc.base.text
- for ent in ents:
- 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)
- cui = self._pick_cui(text[start:end], ent.base.text, 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
- ent.context_similarity = ent.confidence = 1.0
- linked_ents.append(ent)
- return linked_ents
+ 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(
@@ -105,11 +196,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 - "
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..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,6 +19,8 @@
LLMConnectionConfig,
MisconfiguredComponentException,
UnknownSpanException,
+ clean_response,
+ one_chat,
)
logger = logging.getLogger(__name__)
@@ -61,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))
@@ -78,7 +80,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(
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..cfd924632
--- /dev/null
+++ b/medcat-plugins/llm-comps/src/medcat_llm_components/pure_llm_linker.py
@@ -0,0 +1,325 @@
+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,
+ 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 = 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 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
+ 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
+
+ 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]:
+ if self._filter_changed():
+ logger.info("Recreating candidates based on new filter")
+ self._recreate_candidates()
+ 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(
+ cnf, llm_cnf, tokenizer, cdb.config.general.separator, all_candidates)
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")
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..241c8b03f
--- /dev/null
+++ b/medcat-plugins/llm-comps/tests/test_pure_llm_linker.py
@@ -0,0 +1,156 @@
+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 (
+ NoSuchSpan,
+ PureLLMLinkConfig,
+ PureLLMLinker,
+ find_start,
+ parse_output,
+)
+
+from test_save_load import create_new_llm_model
+
+
+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():
+ 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
+ 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)
+
+
+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))
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)),
]
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()