Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(mcp): window GLiNER extract and redact by words so the whole text is read (#359)
Shai Shmuel35e711bf6bde
diff --git a/packages/sie_mcp/src/sie_mcp/offload.py b/packages/sie_mcp/src/sie_mcp/offload.pyindex 41566684b..d09437de6 100644--- a/packages/sie_mcp/src/sie_mcp/offload.py+++ b/packages/sie_mcp/src/sie_mcp/offload.py@@ -32,18 +32,31 @@ DEFAULT_PII_LABELS = []REQUEST_TIMEOUT_S = 600.0+# Lowest score redact_pii keeps. It is sent as the request threshold; otherwise+# the server applies the model's default (0.5) and drops lower spans first.MIN_PII_SCORE = 0.3-# Bounded chunking for the GLiNER extract/redact path. GLiNER runs on a single-# text item per call (no internal chunking), so a large resolved document is-# split into overlapping windows, run per-window, and the entities merged with-# offsets shifted back to the original text. The overlap keeps an entity that-# straddles a window edge fully present in at least one window; a detection that+# Bounded windowing for the GLiNER extract/redact path. GLiNER reads only the+# first ``max_len`` words of each text (384 for the default models) and silently+# ignores the rest, where a word is a match of ``_GLINER_WORD``, so every+# punctuation mark counts as one. The label prompt does not count toward that+# limit. A document is therefore split into overlapping windows of+# EXTRACT_WINDOW_WORDS words, under the smallest ``max_len`` of the GLiNER models+# in the catalog (296) so that any configured model reads each window whole, and+# the entities are merged with offsets shifted back to the original text. The overlap is longer than the+# longest span the default models predict (12 words), so an entity that+# straddles a window edge is whole in at least one window; a detection that# touches an interior window edge (likely truncated) is dropped in favor of the-# neighbor window's full span. EXTRACT_MAX_CHARS bounds the fan-out so one-# request cannot spawn an unbounded number of (un-batched, ~1 rps) GLiNER calls.-EXTRACT_CHUNK_CHARS = 8_000-EXTRACT_OVERLAP_CHARS = 256+# neighbor window's full span. A run of word characters longer than+# EXTRACT_MAX_WORD_CHARS counts as several words, so text without breaks still+# gives bounded windows. Windows are sent EXTRACT_BATCH_WINDOWS per request, and+# EXTRACT_MAX_CHARS bounds the fan-out so one call cannot spawn an unbounded+# number of GLiNER requests.+_GLINER_WORD = re.compile(r"\w+(?:[-_]\w+)*|\S")+EXTRACT_WINDOW_WORDS = 256+EXTRACT_OVERLAP_WORDS = 32+EXTRACT_MAX_WORD_CHARS = 32+EXTRACT_BATCH_WINDOWS = 8EXTRACT_MAX_CHARS = 1_000_000_MAP_PROMPT = (@@ -218,19 +231,23 @@ def _generated_text(result: Mapping[str, Any]) -> str:return text-def _extract_windows(content: str, chunk_chars: int, overlap: int) -> list[tuple[int, str]]:- """Overlapping ``(base_offset, window)`` tuples covering ``content`` exactly."""- if len(content) <= chunk_chars:+def _extract_windows(content: str, window_words: int, overlap_words: int) -> list[tuple[int, str]]:+ """Overlapping ``(base_offset, window)`` tuples of at most ``window_words`` GLiNER words each."""+ words = [+ (start, min(start + EXTRACT_MAX_WORD_CHARS, match.end()))+ for match in _GLINER_WORD.finditer(content)+ for start in range(match.start(), match.end(), EXTRACT_MAX_WORD_CHARS)+ ]+ if len(words) <= window_words:return [(0, content)]- step = max(1, chunk_chars - overlap)+ step = max(1, window_words - overlap_words)windows: list[tuple[int, str]] = []- index = 0- length = len(content)- while index < length:- windows.append((index, content[index : index + chunk_chars]))- if index + chunk_chars >= length:+ for first in range(0, len(words), step):+ last = min(first + window_words, len(words)) - 1+ start, end = words[first][0], words[last][1]+ windows.append((start, content[start:end]))+ if last == len(words) - 1:break- index += stepreturn windows@@ -241,42 +258,49 @@ async def _gliner_entities(labels: Sequence[str],model: str,gpu: str | None,+ threshold: float | None = None,) -> list[dict[str, Any]]:- """Run GLiNER over ``content``, chunking large inputs and merging offset-adjusted spans.-- GLiNER is called on one text item per request, so a document larger than- ``EXTRACT_CHUNK_CHARS`` is split into overlapping windows; each window's- entities are shifted back to the original offsets and de-duplicated. A- detection clipped at an interior window edge is dropped (its overlapping- neighbor holds the full span). Inputs over ``EXTRACT_MAX_CHARS`` are rejected- rather than fanned into an unbounded number of GLiNER calls.+ """Run GLiNER over ``content`` in word windows and merge offset-adjusted spans.++ GLiNER reads only the first ``max_len`` words of each text, so ``content`` is+ split into overlapping windows of at most ``EXTRACT_WINDOW_WORDS`` words, sent+ ``EXTRACT_BATCH_WINDOWS`` per request; each window's entities are shifted back+ to the original offsets and de-duplicated. A detection clipped at an interior+ window edge is dropped (its overlapping neighbor holds the full span). Inputs+ over ``EXTRACT_MAX_CHARS`` are rejected rather than fanned into an unbounded+ number of GLiNER calls. ``threshold`` replaces the model's default minimum score."""if len(content) > EXTRACT_MAX_CHARS:raise OffloadError(f"content is {len(content)} characters, over the {EXTRACT_MAX_CHARS}-character ""extraction limit; summarize or section the document first, or send a smaller piece")+ options = None if threshold is None else {"threshold": threshold}- async def _run(text: str) -> list[Mapping[str, Any]]:- result = await client.extract(+ async def _run(texts: list[str]) -> list[list[Mapping[str, Any]]]:+ results = await client.extract(model,- {"text": text},+ [{"text": text} for text in texts],labels=list(labels),+ options=options,gpu=gpu,wait_for_capacity=True,provision_timeout_s=REQUEST_TIMEOUT_S,)- return list(result.get("entities", []))+ return [list(result.get("entities", [])) for result in results]- windows = _extract_windows(content, EXTRACT_CHUNK_CHARS, EXTRACT_OVERLAP_CHARS)+ windows = _extract_windows(content, EXTRACT_WINDOW_WORDS, EXTRACT_OVERLAP_WORDS)+ window_entities: list[list[Mapping[str, Any]]] = []+ for index in range(0, len(windows), EXTRACT_BATCH_WINDOWS):+ window_entities += await _run([window for _, window in windows[index : index + EXTRACT_BATCH_WINDOWS]])if len(windows) == 1:- return [dict(entity) for entity in await _run(content)]+ return [dict(entity) for entity in window_entities[0]]merged: dict[tuple[Any, ...], dict[str, Any]] = {}last = len(windows) - 1- for position, (base, window) in enumerate(windows):+ for position, ((base, window), entities) in enumerate(zip(windows, window_entities, strict=True)):window_len = len(window)- for entity in await _run(window):+ for entity in entities:start = entity.get("start")end = entity.get("end")# Drop detections clipped at an interior window edge; the overlapping@@ -354,7 +378,9 @@ async def redact_pii(raise OffloadError("content contains no text to redact")resolved_labels = labels or DEFAULT_PII_LABELS- entities = await _gliner_entities(client, content=content, labels=resolved_labels, model=model, gpu=gpu)+ entities = await _gliner_entities(+ client, content=content, labels=resolved_labels, model=model, gpu=gpu, threshold=MIN_PII_SCORE+ )redacted, placeholder_map, span_count = redact_text(content, entities)return {"redacted_text": redacted,diff --git a/packages/sie_mcp/tests/test_offload.py b/packages/sie_mcp/tests/test_offload.pyindex 3baf241a0..ca405d1f1 100644--- a/packages/sie_mcp/tests/test_offload.py+++ b/packages/sie_mcp/tests/test_offload.py@@ -1,10 +1,20 @@from __future__ import annotations+import math+import re+from itertools import pairwisefrom typing import Anyimport pytestfrom sie_mcp import offload+# GLiNER's default word splitter (punctuation marks are words too), and how many+# of those words the default GLiNER models read from each text before silently+# dropping the rest.+_GLINER_WORD = re.compile(r"\w+(?:[-_]\w+)*|\S")+_GLINER_MAX_WORDS = 384+_FILLER = "The committee reviewed the figures, then adjourned. " # 9 GLiNER words+class _FakeOffloadClient:def __init__(self) -> None:@@ -15,10 +25,15 @@ class _FakeOffloadClient:self.generate_calls.append({"model": model, "prompt": prompt, **kwargs})return {"text": f"summary {len(self.generate_calls)}"}- async def extract(self, model: str, items: dict[str, str], **kwargs: Any) -> dict[str, Any]:+ async def extract(self, model: str, items: Any, **kwargs: Any) -> Any:self.extract_calls.append({"model": model, "items": items, **kwargs})+ # Like the SDK: one result for a single item, a list for a list of items.+ if isinstance(items, list):+ return [self._extract_one(model, item["text"]) for item in items]+ return self._extract_one(model, items["text"])++ def _extract_one(self, model: str, text: str) -> dict[str, Any]:if model == offload.PII_MODEL:- text = items["text"]return {"entities": [{@@ -99,6 +114,7 @@ async def test_extract_entities_returns_entities_and_markdown_table() -> None:assert result["entities"][0]["text"] == "Alice Example"assert "| Alice Example | person | 0.93 |" in result["markdown_table"]assert client.extract_calls[0]["labels"] == ["person", "organization"]+ assert client.extract_calls[0]["options"] is None # the model's own thresholdasync def test_redact_pii_returns_redacted_text_without_original_map() -> None:@@ -143,37 +159,72 @@ async def test_extract_entities_rejects_bad_input(content: str, labels: list[strclass _WindowAwareClient:- """Returns each known phrase present in the window with start/end relative to- that window, mimicking GLiNER being called per chunk.+ """Mimics GLiNER on every text it is sent: returns each known phrase found in the+ first ``_GLINER_MAX_WORDS`` words, with start/end relative to that text. Like the+ real model, it silently ignores everything after that."""def __init__(self, phrases: list[tuple[str, str]]) -> None:self.phrases = phrases+ self.calls: list[dict[str, Any]] = []self.windows_seen: list[str] = []- async def extract(self, model: str, items: dict[str, str], **kwargs: Any) -> dict[str, Any]:- text = items["text"]+ async def extract(self, model: str, items: Any, **kwargs: Any) -> Any:+ self.calls.append({"model": model, "items": items, **kwargs})+ if isinstance(items, list):+ return [self._extract_one(item["text"]) for item in items]+ return self._extract_one(items["text"])++ def _extract_one(self, text: str) -> dict[str, Any]:self.windows_seen.append(text)+ words = list(_GLINER_WORD.finditer(text))+ read = text[: words[_GLINER_MAX_WORDS - 1].end()] if len(words) > _GLINER_MAX_WORDS else textentities: list[dict[str, Any]] = []for phrase, label in self.phrases:- idx = text.find(phrase)+ idx = read.find(phrase)while idx != -1:entities.append({"text": phrase, "label": label, "start": idx, "end": idx + len(phrase), "score": 0.9})- idx = text.find(phrase, idx + 1)+ idx = read.find(phrase, idx + 1)return {"entities": entities}+async def test_redact_pii_redacts_pii_past_the_model_word_limit() -> None:+ # Each paragraph is 40 filler sentences (360 words) and one email address, so all+ # but the first address sit well past the first 384 words GLiNER reads per text.+ emails = [f"member{index}@example.com" for index in range(10)]+ content = "".join(_FILLER * 40 + f"Write to {email} today. " for email in emails)+ client = _WindowAwareClient([(email, "email") for email in emails])++ result = await offload.redact_pii(client, content=content, labels=["email"], model="pii")++ assert [email for email in emails if email in result["redacted_text"]] == []+ assert result["metadata"]["span_count"] == len(emails)+++async def test_extract_entities_finds_entities_past_the_model_word_limit() -> None:+ phrase = "Acme Corporation"+ # About 450 words before the phrase: a short text, but longer than GLiNER reads at once.+ content = _FILLER * 50 + f"They signed with {phrase} in May. " + _FILLER * 5+ abs_start = content.index(phrase)+ client = _WindowAwareClient([(phrase, "organization")])++ result = await offload.extract_entities(client, content=content, labels=["organization"], model="gliner")++ spans = [(entity["start"], entity["end"]) for entity in result["entities"] if entity["text"] == phrase]+ assert spans == [(abs_start, abs_start + len(phrase))]++async def test_extract_entities_chunks_large_content_and_shifts_offsets() -> None:phrase = "Acme Corporation"# Past the first window, so it is only found in a later chunk.- content = ("x" * (offload.EXTRACT_CHUNK_CHARS + 300)) + " " + phrase + " " + ("y" * 200)+ content = ("lorem " * (offload.EXTRACT_WINDOW_WORDS + 30)) + phrase + (" ipsum" * 200)abs_start = content.index(phrase)- assert abs_start > offload.EXTRACT_CHUNK_CHARSclient = _WindowAwareClient([(phrase, "organization")])result = await offload.extract_entities(client, content=content, labels=["organization"], model="gliner")assert len(client.windows_seen) > 1 # actually chunked+ assert phrase not in client.windows_seen[0]matches = [e for e in result["entities"] if e["text"] == phrase]assert len(matches) == 1assert matches[0]["start"] == abs_start@@ -183,21 +234,21 @@ async def test_extract_entities_chunks_large_content_and_shifts_offsets() -> Nonasync def test_extract_entities_dedupes_phrase_in_window_overlap() -> None:phrase = "Globex Inc"# Inside the overlap region, so it is seen in two adjacent windows.- pos = offload.EXTRACT_CHUNK_CHARS - offload.EXTRACT_OVERLAP_CHARS + 20- content = ("x" * pos) + phrase + ("z" * 1000)+ pos_words = offload.EXTRACT_WINDOW_WORDS - offload.EXTRACT_OVERLAP_WORDS + 20+ content = ("lorem " * pos_words) + phrase + (" ipsum" * 300)client = _WindowAwareClient([(phrase, "organization")])result = await offload.extract_entities(client, content=content, labels=["organization"], model="gliner")- assert len(client.windows_seen) > 1+ assert sum(phrase in window for window in client.windows_seen) == 2matches = [e for e in result["entities"] if e["text"] == phrase]assert len(matches) == 1- assert matches[0]["start"] == pos+ assert matches[0]["start"] == content.index(phrase)async def test_redact_pii_chunks_large_content_and_redacts_full_span() -> None:ssn = "123-45-6789"- content = ("x" * (offload.EXTRACT_CHUNK_CHARS + 200)) + " SSN: " + ssn + " end"+ content = ("lorem " * (offload.EXTRACT_WINDOW_WORDS + 200)) + "SSN: " + ssn + " end"client = _WindowAwareClient([(ssn, "social security number")])result = await offload.redact_pii(client, content=content, labels=["social security number"], model="pii")@@ -208,6 +259,44 @@ async def test_redact_pii_chunks_large_content_and_redacts_full_span() -> None:assert result["metadata"]["span_count"] == 1+def test_extract_windows_fit_the_model_word_limit_and_cover_the_text() -> None:+ content = _FILLER * 200+ windows = offload._extract_windows(content, offload.EXTRACT_WINDOW_WORDS, offload.EXTRACT_OVERLAP_WORDS)++ assert len(windows) > 1+ assert offload.EXTRACT_WINDOW_WORDS < _GLINER_MAX_WORDS+ for base, window in windows:+ assert content[base : base + len(window)] == window+ assert len(_GLINER_WORD.findall(window)) <= offload.EXTRACT_WINDOW_WORDS+ # Neighbors overlap, and together the windows run from the first word to the last.+ assert windows[0][0] == 0+ assert windows[-1][0] + len(windows[-1][1]) == len(content.rstrip())+ for (base, window), (next_base, _) in pairwise(windows):+ assert next_base < base + len(window)+++def test_extract_windows_stay_bounded_for_text_without_word_breaks() -> None:+ content = "x" * 100_000+ windows = offload._extract_windows(content, offload.EXTRACT_WINDOW_WORDS, offload.EXTRACT_OVERLAP_WORDS)++ assert max(len(window) for _, window in windows) <= offload.EXTRACT_WINDOW_WORDS * offload.EXTRACT_MAX_WORD_CHARS+ assert windows[-1][0] + len(windows[-1][1]) == len(content)+++async def test_redact_pii_batches_windows_and_sends_its_score_threshold() -> None:+ content = _FILLER * 300+ windows = offload._extract_windows(content, offload.EXTRACT_WINDOW_WORDS, offload.EXTRACT_OVERLAP_WORDS)+ assert len(windows) > offload.EXTRACT_BATCH_WINDOWS+ client = _WindowAwareClient([])++ await offload.redact_pii(client, content=content, labels=["person"], model="pii")++ # Every window is sent once, in order, at most EXTRACT_BATCH_WINDOWS to a request.+ assert [item["text"] for call in client.calls for item in call["items"]] == [window for _, window in windows]+ assert len(client.calls) == math.ceil(len(windows) / offload.EXTRACT_BATCH_WINDOWS)+ assert all(call["options"] == {"threshold": offload.MIN_PII_SCORE} for call in client.calls)++@pytest.mark.parametrize("tool", ["extract", "redact"])async def test_extraction_rejects_content_over_cap(tool: str) -> None:client = _FakeOffloadClient()