Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Fix: LLM enhancement responses were being discarded by enhance_entities() and enhance_relations(). (#1659)

Sameer Kadamf450e3bd04ed
diff --git a/semantica/semantic_extract/llm_extraction.py b/semantica/semantic_extract/llm_extraction.py
index 1f902501..a3372605 100644
--- a/semantica/semantic_extract/llm_extraction.py
+++ b/semantica/semantic_extract/llm_extraction.py
@@ -60,8 +60,9 @@ Author: Semantica Contributors
License: MIT
"""
+import re
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
@@ -70,6 +71,14 @@ from .ner_extractor import Entity
from .providers import create_provider
from .relation_extractor import Relation
+try:
+ from .schemas import EntitiesResponse, RelationsResponse
+ _SCHEMAS_AVAILABLE = True
+except ImportError: # pydantic not installed
+ _SCHEMAS_AVAILABLE = False
+ EntitiesResponse = None # type: ignore[assignment,misc]
+ RelationsResponse = None # type: ignore[assignment,misc]
+
@dataclass
class LLMResponse:
@@ -81,6 +90,33 @@ class LLMResponse:
metadata: Dict[str, Any]
+def _find_span_in_text(needle: str, text: str, occupied: set) -> tuple:
+ """Return the ``(start, end)`` character span for the first occurrence of
+ *needle* in *text* that is not already in *occupied*.
+
+ Uses the same word-boundary pattern as
+ :meth:`~.ner_extractor.NERExtractor._align_entities_to_text` so that
+ ``Apple`` does not match inside ``Applesauce``.
+
+ Returns ``(0, 0)`` — the conventional "unknown span" sentinel — when no
+ unoccupied match is found rather than fabricating a position.
+ """
+ if not needle or not text:
+ return (0, 0)
+
+ left_boundary = r"(?<!\w)" if (needle[0].isalnum() or needle[0] == "_") else ""
+ right_boundary = r"(?!\w)" if (needle[-1].isalnum() or needle[-1] == "_") else ""
+ pattern = re.compile(
+ left_boundary + re.escape(needle) + right_boundary,
+ re.IGNORECASE,
+ )
+ for m in pattern.finditer(text):
+ span = (m.start(), m.end())
+ if span not in occupied:
+ return span
+ return (0, 0)
+
+
class LLMExtraction:
"""LLM-based extraction and enhancement."""
@@ -112,7 +148,7 @@ class LLMExtraction:
provider_config = config.copy()
if "api_key" in provider_config and not provider_config["api_key"]:
del provider_config["api_key"]
-
+
self.provider = create_provider(provider, **provider_config)
except Exception as e:
self.logger.warning(f"Failed to initialize {provider} provider: {e}")
@@ -156,10 +192,28 @@ class LLMExtraction:
"""
Enhance entity extraction using LLM.
+ Calls the configured LLM provider with a structured prompt, parses the
+ response using :class:`~.schemas.EntitiesResponse`, and merges the
+ result back into the original entity list:
+
+ - Existing entities whose text matches an LLM-returned entity (case-
+ insensitive) have their ``label`` and ``confidence`` updated. When the
+ same surface text appears at multiple offsets, **all** occurrences are
+ updated.
+ - New entities returned by the LLM that have no match in the original
+ list are appended. Their character spans are located in ``text`` using
+ a word-boundary search (same convention as the NER aligner); the span
+ is ``(0, 0)`` when the text cannot be found.
+ - Original entities not mentioned by the LLM are preserved unchanged.
+ - All returned entities carry ``enhanced_by`` and ``model`` metadata.
+
+ Falls back to the original entities on any LLM or parsing failure so
+ that downstream processing is never blocked by an enhancement error.
+
Args:
text: Input text
entities: Pre-extracted entities
- **options: Enhancement options
+ **options: Enhancement options (``temperature`` overrides instance default)
Returns:
list: Enhanced entities
@@ -182,6 +236,18 @@ class LLMExtraction:
)
return entities
+ if not _SCHEMAS_AVAILABLE:
+ self.logger.warning(
+ "Pydantic schemas not available; cannot perform typed LLM "
+ "enhancement. Returning original entities."
+ )
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message="Schemas unavailable",
+ )
+ return entities
+
self.progress_tracker.update_tracking(
tracking_id, message="Building prompt..."
)
@@ -190,14 +256,20 @@ class LLMExtraction:
self.progress_tracker.update_tracking(
tracking_id, message="Calling LLM API..."
)
- response = self.provider.generate(
- prompt, temperature=options.get("temperature", self.temperature)
+ # Always forward temperature (even None) so generate_typed can apply
+ # its own provider-level default consistently regardless of whether
+ # the instructor fast-path or the manual repair loop is active.
+ gen_kwargs: Dict[str, Any] = {
+ "temperature": options.get("temperature", self.temperature),
+ }
+ response_obj = self.provider.generate_typed(
+ prompt, schema=EntitiesResponse, **gen_kwargs
)
self.progress_tracker.update_tracking(
tracking_id, message="Parsing LLM response..."
)
- enhanced_entities = self._parse_entity_response(response, entities)
+ enhanced_entities = self._parse_entity_response(response_obj, entities, text)
self.progress_tracker.stop_tracking(
tracking_id,
@@ -218,10 +290,32 @@ class LLMExtraction:
"""
Enhance relation extraction using LLM.
+ Calls the configured LLM provider with a structured prompt, parses the
+ response using :class:`~.schemas.RelationsResponse`, and merges the
+ result back into the original relation list.
+
+ The prompt sends all existing relations — **including their predicates**
+ — to the LLM. The LLM therefore knows the full
+ ``(subject, predicate, object)`` context when it responds, which drives
+ the merge strategy:
+
+ - An LLM-returned triple whose ``(subject.text, predicate, object.text)``
+ exactly matches an existing relation (case-insensitive) has its
+ ``confidence`` updated. The predicate is already correct.
+ - An LLM-returned triple with no exact match in the original list is
+ **appended** as a new relation, regardless of whether the
+ ``(subject, object)`` pair already exists with a different predicate.
+ Enhancement is additive: existing graph edges are never silently
+ deleted.
+ - Original relations absent from the LLM response are **preserved**.
+ - All returned relations carry ``enhanced_by`` and ``model`` metadata.
+
+ Falls back to the original relations on any LLM or parsing failure.
+
Args:
text: Input text
relations: Pre-extracted relations
- **options: Enhancement options
+ **options: Enhancement options (``temperature`` overrides instance default)
Returns:
list: Enhanced relations
@@ -232,13 +326,25 @@ class LLMExtraction:
)
return relations
+ if not _SCHEMAS_AVAILABLE:
+ self.logger.warning(
+ "Pydantic schemas not available; cannot perform typed LLM "
+ "enhancement. Returning original relations."
+ )
+ return relations
+
prompt = self._build_relation_prompt(text, relations)
try:
- response = self.provider.generate(
- prompt, temperature=options.get("temperature", self.temperature)
+ gen_kwargs: Dict[str, Any] = {
+ "temperature": options.get("temperature", self.temperature),
+ }
+ response_obj = self.provider.generate_typed(
+ prompt, schema=RelationsResponse, **gen_kwargs
+ )
+ enhanced_relations = self._parse_relation_response(
+ response_obj, relations, text
)
- enhanced_relations = self._parse_relation_response(response, relations)
return enhanced_relations
except Exception as e:
self.logger.error(f"Failed to enhance relations with LLM: {e}")
@@ -267,7 +373,9 @@ Please:
3. Improve entity type classifications
4. Provide confidence scores
-Return the enhanced entity list in JSON format."""
+Return a JSON object with an "entities" key containing an array of entity objects.
+Each entity object must have: "text" (string), "label" (string), "confidence" (float 0-1).
+Example: {{"entities": [{{"text": "Apple Inc.", "label": "ORG", "confidence": 0.97}}]}}"""
def _build_relation_prompt(self, text: str, relations: List[Relation]) -> str:
"""Build prompt for relation enhancement.
@@ -300,37 +408,321 @@ Please:
3. Improve relation type classifications
4. Provide confidence scores
-Return the enhanced relation list in JSON format."""
+Return a JSON object with a "relations" key containing an array of relation objects.
+Each relation object must have: "subject" (string), "predicate" (string), "object" (string), "confidence" (float 0-1).
+Example: {{"relations": [{{"subject": "Apple", "predicate": "founded_by", "object": "Steve Jobs", "confidence": 0.95}}]}}"""
+
+ # ------------------------------------------------------------------
+ # Response parsers
+ # ------------------------------------------------------------------
def _parse_entity_response(
- self, response: str, original_entities: List[Entity]
+ self,
+ response_obj: Any,
+ original_entities: List[Entity],
+ text: str = "",
) -> List[Entity]:
- """Parse LLM response for entities."""
- # Simplified parsing - in practice would parse JSON
- # For now, return original entities with updated metadata
+ """Merge the LLM-returned :class:`~.schemas.EntitiesResponse` into the
+ original entity list.
+
+ Merge strategy:
+
+ * For every entity returned by the LLM, look for **all** existing
+ entities with the same text (case-insensitive). Each match has its
+ ``label`` and ``confidence`` updated. This covers the repeated-mention
+ case: if "Apple" appears at three offsets, all three are updated.
+ * LLM-returned entities with no match in the original list are
+ **appended** as new entities. Their character span is located in
+ *text* using a word-boundary search so downstream span-dependent code
+ (chunking, semantic network extraction) receives a usable offset. When
+ the text cannot be found the span is ``(0, 0)`` — the conventional
+ "unknown" sentinel used throughout the project.
+ * Original entities absent from the LLM response are **preserved**.
+ * All returned entities carry ``enhanced_by`` / ``model`` metadata.
+ * Empty/unusable responses return the original list unchanged.
+ """
+ llm_entities = getattr(response_obj, "entities", None)
+ if not llm_entities:
+ self.logger.debug(
+ "_parse_entity_response: empty LLM response; keeping original entities"
+ )
+ for entity in original_entities:
+ if entity.metadata is None:
+ entity.metadata = {}
+ entity.metadata.update({"enhanced_by": self.provider_name, "model": self.model})
+ return original_entities
+
+ # Build a lookup: lowercased text → list of indices in the working copy.
+ # Using a list (not a single int) correctly handles repeated mentions at
+ # different character offsets — all occurrences are updated.
+ working: List[Entity] = []
+ text_to_indices: Dict[str, List[int]] = {}
for entity in original_entities:
+ idx = len(working)
+ new_meta = dict(entity.metadata) if entity.metadata else {}
+ working.append(Entity(
+ text=entity.text,
+ label=entity.label,
+ start_char=entity.start_char,
+ end_char=entity.end_char,
+ confidence=entity.confidence,
+ metadata=new_meta,
+ ))
+ text_to_indices.setdefault(entity.text.lower(), []).append(idx)
+
+ # Track spans already used by existing entities for the span-recovery
+ # logic so new entities never overlap with pre-existing ones.
+ occupied_spans: set = {
+ (e.start_char, e.end_char)
+ for e in working
+ if e.start_char != 0 or e.end_char != 0
+ }
+
+ seen_new: set = set() # guard against duplicate new entities
+
+ for e_out in llm_entities:
+ key = e_out.text.lower()
+ if key in text_to_indices:
+ # Update every occurrence of this entity text
+ for idx in text_to_indices[key]:
+ existing = working[idx]
+ if e_out.label:
+ existing.label = e_out.label
+ if e_out.confidence is not None:
+ existing.confidence = e_out.confidence
+ existing.metadata.update({
+ "enhanced_by": self.provider_name,
+ "model": self.model,
+ })
+ else:
+ # New entity from LLM — append only once per unique text
+ if key not in seen_new:
+ seen_new.add(key)
+ # Attempt to locate the entity in the source text so
+ # downstream span-dependent code receives a usable offset.
+ start, end = _find_span_in_text(e_out.text, text, occupied_spans)
+ if start != 0 or end != 0:
+ occupied_spans.add((start, end))
+ working.append(Entity(
+ text=e_out.text,
+ label=e_out.label or "UNKNOWN",
+ start_char=start,
+ end_char=end,
+ confidence=e_out.confidence,
+ metadata={
+ "enhanced_by": self.provider_name,
+ "model": self.model,
+ "extraction_method": "llm_enhancement",
+ },
+ ))
+
+ # Stamp any original entities not touched by the LLM
+ for entity in working:
if entity.metadata is None:
entity.metadata = {}
- entity.metadata.update({
- "enhanced_by": self.provider_name,
- "model": self.model
- })
- return original_entities
+ entity.metadata.setdefault("enhanced_by", self.provider_name)
+ entity.metadata.setdefault("model", self.model)
+
+ return working
def _parse_relation_response(
- self, response: str, original_relations: List[Relation]
+ self,
+ response_obj: Any,
+ original_relations: List[Relation],
+ text: str = "",
) -> List[Relation]:
- """Parse LLM response for relations."""
- # Simplified parsing - in practice would parse JSON
- # For now, return original relations with updated metadata
- for relation in original_relations:
- if relation.metadata is None:
- relation.metadata = {}
- relation.metadata.update({
- "enhanced_by": self.provider_name,
- "model": self.model
- })
- return original_relations
+ """Merge the LLM-returned :class:`~.schemas.RelationsResponse` into
+ the original relation list.
+
+ Merge strategy
+ --------------
+ The enhancement prompt sends *all* existing relations to the LLM,
+ including their current predicates. The LLM therefore knows the exact
+ ``(subject, predicate, object)`` triple when it decides how to respond.
+
+ * **Exact triple match** ``(subject.text, predicate, object.text)`` —
+ all case-insensitive: the LLM confirmed or fine-tuned this relation.
+ Only its ``confidence`` is updated; the predicate does not change
+ because the LLM echoed it back unchanged.
+ * **New triple** — the LLM's ``(subject, predicate, object)`` is not
+ present in the original list (including the case where the LLM
+ returns a more specific predicate for an existing ``(subject, object)``
+ pair): treated as a new relation and **appended**. The original
+ relation with the old predicate is **preserved** — enhancement is
+ additive; it never silently deletes existing graph edges.
+ * **Truly new pair** — ``(subject, object)`` not present anywhere in
+ the original list: appended as a new relation. Subject/object
+ entities are resolved against the canonical entity pool; unresolved
+ endpoints have their span located in *text* with a word-boundary
+ search (same as the entity enhancer). The span is ``(0, 0)`` when
+ the endpoint text is not present in the document — the project-wide
+ "unknown span" sentinel. Endpoints that resolve via the pool keep
+ their canonical span unchanged.
+ * Original relations absent from the LLM response are **preserved**.
+ * All returned relations carry ``enhanced_by`` / ``model`` metadata.
+ * Empty/unusable responses return the original list unchanged.
+
+ Why ``(subject, predicate, object)`` identity?
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ Using only ``(subject, object)`` would cause every relation between the
+ same two endpoints to have its predicate blindly overwritten by a single
+ LLM entry — e.g. an LLM response for ``founded_by`` would silently
+ change an independent ``employs`` relation to ``founded_by`` as well.
+ Triple-level matching prevents this while still supporting the common
+ "verify / confirm" enhancement use case where the LLM echoes back a
+ relation that was already correct. Predicate *correction* manifests
+ as an appended new relation; the stale original remains in the graph
+ and can be pruned deliberately if required.
+ """
+ llm_relations = getattr(response_obj, "relations", None)
+ if not llm_relations:
+ self.logger.debug(
+ "_parse_relation_response: empty LLM response; keeping original relations"
+ )
+ for rel in original_relations:
+ if rel.metadata is None:
+ rel.metadata = {}
+ rel.metadata.update({"enhanced_by": self.provider_name, "model": self.model})
+ return original_relations
+
+ # Build a lookup: (subj_lower, predicate_lower, obj_lower) → index.
+ # Using the full triple as the key means that two relations sharing the
+ # same endpoints but carrying different predicates are treated as
+ # independent relations and cannot overwrite each other.
+ working: List[Relation] = []
+ triple_to_idx: Dict[tuple, int] = {}
+ for rel in original_relations:
+ idx = len(working)
+ new_meta = dict(rel.metadata) if rel.metadata else {}
+ working.append(Relation(
+ subject=rel.subject,
+ predicate=rel.predicate,
+ object=rel.object,
+ confidence=rel.confidence,
+ context=rel.context,
+ metadata=new_meta,
+ ))
+ triple_key = (
+ rel.subject.text.lower(),
+ rel.predicate.lower(),
+ rel.object.text.lower(),
+ )
+ # Keep first occurrence only (guards against pre-existing duplicates
+ # in the caller's input; duplicates are still preserved in `working`
+ # and receive the metadata stamp from the final pass below).
+ triple_to_idx.setdefault(triple_key, idx)
+
+ # Build a flat entity pool from original relations for endpoint resolution
+ entity_pool: List[Entity] = []
+ seen_ent_texts: set = set()
+ for rel in original_relations:
+ for ent in (rel.subject, rel.object):
+ t = ent.text.lower()
+ if t not in seen_ent_texts:
+ entity_pool.append(ent)
+ seen_ent_texts.add(t)
+
+ seen_new: set = set() # guard against duplicate new triples
+
+ # Track spans already used by pool entities so synthetic endpoint
+ # span-recovery never collides with a known entity position.
+ occupied_endpoint_spans: set = {
+ (e.start_char, e.end_char)
+ for e in entity_pool
+ if e.start_char != 0 or e.end_char != 0
+ }
+
+ for r_out in llm_relations:
+ subj_text = (r_out.subject or "").strip()
+ obj_text = (r_out.object or "").strip()
+ pred_text = (r_out.predicate or "").strip()
+ if not subj_text or not obj_text:
+ continue
+
+ triple_key = (
+ subj_text.lower(),
+ pred_text.lower(),
+ obj_text.lower(),
+ )
+
+ if triple_key in triple_to_idx:
+ # Exact triple match — update only confidence; predicate is
+ # unchanged because the LLM echoed it back.
+ existing = working[triple_to_idx[triple_key]]
+ if r_out.confidence is not None:
+ existing.confidence = r_out.confidence
+ existing.metadata.update({
+ "enhanced_by": self.provider_name,
+ "model": self.model,
+ })
+ else:
+ # No matching triple — append once per unique triple
+ if triple_key not in seen_new:
+ seen_new.add(triple_key)
+
+ # Resolve endpoints against the canonical entity pool
+ subj_entity = next(
+ (e for e in entity_pool if e.text.lower() == subj_text.lower()),
+ None,
+ )
+ obj_entity = next(
+ (e for e in entity_pool if e.text.lower() == obj_text.lower()),
+ None,
+ )
+
+ # For endpoints not found in the pool, attempt to locate them
+ # in the source text using the same word-boundary search
+ # already applied to new entities. This avoids fabricating a
+ # span at position 0 when the endpoint occurs later in the
+ # document. Only synthetic (unresolved) endpoints need this;
+ # pool-resolved endpoints already carry correct spans.
+ if subj_entity is None:
+ s_start, s_end = _find_span_in_text(
+ subj_text, text, occupied_endpoint_spans
+ )
+ if s_start != 0 or s_end != 0:
+ occupied_endpoint_spans.add((s_start, s_end))
+ subj_entity = Entity(
+ text=subj_text, label="UNKNOWN",
+ start_char=s_start, end_char=s_end,
+ confidence=0.8, metadata={"synthetic": True},
+ )
+
+ if obj_entity is None:
+ o_start, o_end = _find_span_in_text(
+ obj_text, text, occupied_endpoint_spans
+ )
+ if o_start != 0 or o_end != 0:
+ occupied_endpoint_spans.add((o_start, o_end))
+ obj_entity = Entity(
+ text=obj_text, label="UNKNOWN",
+ start_char=o_start, end_char=o_end,
+ confidence=0.8, metadata={"synthetic": True},
+ )
+
+ working.append(Relation(
+ subject=subj_entity,
+ predicate=pred_text or "related_to",
+ object=obj_entity,
+ confidence=(
+ r_out.confidence if r_out.confidence is not None else 0.9
+ ),
+ context=text,
+ metadata={
+ "enhanced_by": self.provider_name,
+ "model": self.model,
+ "extraction_method": "llm_enhancement",
+ },
+ ))
+
+ # Stamp any original relations not touched by the LLM
+ for rel in working:
+ if rel.metadata is None:
+ rel.metadata = {}
+ rel.metadata.setdefault("enhanced_by", self.provider_name)
+ rel.metadata.setdefault("model", self.model)
+
+ return working
# Alias for backward compatibility
diff --git a/tests/semantic_extract/test_llm_enhancement.py b/tests/semantic_extract/test_llm_enhancement.py
new file mode 100644
index 00000000..0aec74dd
--- /dev/null
+++ b/tests/semantic_extract/test_llm_enhancement.py
@@ -0,0 +1,883 @@
+"""Regression tests for LLMExtraction enhancement response parsing.
+
+These tests would ALL FAIL against the old stub implementation because
+_parse_entity_response / _parse_relation_response used to ignore the
+LLM response entirely. They pass after the fix.
+
+Coverage
+--------
+Entity enhancement
+ 1. LLM updates an existing entity's label
+ 2. LLM updates an existing entity's confidence
+ 3. LLM adds a brand-new entity; span is located in source text
+ 4. LLM adds a new entity absent from the source text → span (0, 0)
+ 5. Empty LLM response preserves originals without data loss
+ 6. Provider failure falls back gracefully
+ 7. enhanced_by / model metadata always present (updated, new, untouched)
+ 8. Entities not mentioned by the LLM are preserved unchanged
+ 9. Repeated mentions at different offsets are ALL updated
+ 10. No duplicate entities when LLM repeats the same text
+
+Relation enhancement
+ 11. LLM corrects an existing relation's predicate (subject+object identity)
+ 12. LLM updates an existing relation's confidence
+ 13. LLM adds a new relation
+ 14. Empty LLM response preserves originals
+ 15. Provider failure falls back gracefully
+ 16. enhanced_by / model metadata always present (updated, new, untouched)
+ 17. Relations not mentioned by the LLM are preserved unchanged
+ 18. No duplicate relations when LLM repeats the same pair
+ 19. Multiple relations with same endpoints but different predicates are ALL updated
+ 20. New relation endpoint resolves to canonical entity from pool
+ 21. Unresolvable endpoint becomes synthetic UNKNOWN
+
+Temperature propagation
+ 22. temperature=None is forwarded as-is to generate_typed
+ 23. Explicit temperature is forwarded correctly
+
+Case-insensitive matching
+ 24. Entity text match is case-insensitive
+ 25. Relation subject/object match is case-insensitive
+"""
+
+import pytest
+from unittest.mock import MagicMock
+
+from semantica.semantic_extract.llm_extraction import LLMExtraction
+from semantica.semantic_extract.schemas import EntitiesResponse, EntityOut, RelationsResponse, RelationOut
+from semantica.semantic_extract.types import Entity, Relation
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _make_entity(text: str, label: str, confidence: float = 0.8,
+ start: int = 0, end: int = 0) -> Entity:
+ end = end or len(text)
+ return Entity(
+ text=text, label=label,
+ start_char=start, end_char=end,
+ confidence=confidence, metadata={},
+ )
+
+
+def _make_relation(
+ subj_text: str, pred: str, obj_text: str,
+ confidence: float = 0.8,
+) -> Relation:
+ return Relation(
+ subject=_make_entity(subj_text, "ORG"),
+ predicate=pred,
+ object=_make_entity(obj_text, "PERSON"),
+ confidence=confidence,
+ context="",
+ metadata={},
+ )
+
+
+def _make_extractor(llm_response, *, temperature=None) -> LLMExtraction:
+ """Return an LLMExtraction instance whose provider.generate_typed returns
+ *llm_response* without hitting any real API."""
+ extractor = LLMExtraction.__new__(LLMExtraction)
+ extractor.provider_name = "openai"
+ extractor.model = "gpt-4"
+ extractor.temperature = temperature
+ extractor.config = {}
+
+ from semantica.utils.logging import get_logger
+ extractor.logger = get_logger("test_llm_enhancement")
+
+ from semantica.utils.progress_tracker import get_progress_tracker
+ extractor.progress_tracker = get_progress_tracker()
+ extractor.progress_tracker.enabled = False
+
+ mock_provider = MagicMock()
+ mock_provider.is_available.return_value = True
+ mock_provider.generate_typed.return_value = llm_response
+ extractor.provider = mock_provider
+
+ return extractor
+
+
+def _make_failing_extractor() -> LLMExtraction:
+ extractor = LLMExtraction.__new__(LLMExtraction)
+ extractor.provider_name = "openai"
+ extractor.model = "gpt-4"
+ extractor.temperature = None
+ extractor.config = {}
+
+ from semantica.utils.logging import get_logger
+ extractor.logger = get_logger("test_llm_enhancement")
+ from semantica.utils.progress_tracker import get_progress_tracker
+ extractor.progress_tracker = get_progress_tracker()
+ extractor.progress_tracker.enabled = False
+
+ mock_provider = MagicMock()
+ mock_provider.is_available.return_value = True
+ mock_provider.generate_typed.side_effect = Exception("simulated failure")
+ extractor.provider = mock_provider
+ return extractor
+
+
+# ---------------------------------------------------------------------------
+# Entity enhancement — label and confidence updates
+# ---------------------------------------------------------------------------
+
+class TestEnhanceEntitiesLabelUpdate:
+ """Test 1 – LLM corrects an existing entity's label."""
+
+ def test_label_is_updated(self):
+ original = [_make_entity("Apple Inc.", "PRODUCT")]
+
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("Apple Inc. is a company.", original)
+
+ assert len(result) == 1
+ assert result[0].label == "ORG", "LLM-corrected label must be applied"
+
+
+class TestEnhanceEntitiesConfidenceUpdate:
+ """Test 2 – LLM updates an existing entity's confidence score."""
+
+ def test_confidence_is_updated(self):
+ original = [_make_entity("Steve Jobs", "PERSON", confidence=0.5)]
+
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Steve Jobs", label="PERSON", confidence=0.99),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("Steve Jobs founded Apple.", original)
+
+ assert result[0].confidence == pytest.approx(0.99)
+
+
+# ---------------------------------------------------------------------------
+# Entity enhancement — new entity span recovery
+# ---------------------------------------------------------------------------
+
+class TestEnhanceEntitiesNewEntitySpan:
+ """Tests 3–4 — new entities get a located span when the text allows it."""
+
+ def test_new_entity_span_located_in_text(self):
+ """Test 3: new entity present in source text receives correct span."""
+ source = "Apple Inc. was founded by Steve Jobs in 1976."
+ original = [_make_entity("Apple Inc.", "ORG", start=0, end=10)]
+
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ EntityOut(text="Steve Jobs", label="PERSON", confidence=0.95), # new
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities(source, original)
+
+ new_ent = next(e for e in result if e.text == "Steve Jobs")
+ expected_start = source.find("Steve Jobs")
+ assert new_ent.start_char == expected_start, (
+ "New entity must be located at its actual position in the source text"
+ )
+ assert new_ent.end_char == expected_start + len("Steve Jobs")
+
+ def test_new_entity_absent_from_text_gets_zero_span(self):
+ """Test 4: new entity NOT in source text gets (0, 0) sentinel."""
+ source = "Apple Inc. is a technology company."
+ original = [_make_entity("Apple Inc.", "ORG", start=0, end=10)]
+
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Completely Absent Corp", label="ORG", confidence=0.7),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities(source, original)
+
+ absent = next(e for e in result if e.text == "Completely Absent Corp")
+ assert absent.start_char == 0
+ assert absent.end_char == 0, (
+ "Entity not present in source text must get (0, 0) sentinel span"
+ )
+
+ def test_new_entity_later_in_text_gets_correct_span(self):
+ """New entity that occurs later in the document (not at position 0)
+ must receive the correct offset, not (0, 0)."""
+ source = "The Board of Directors announced that Tim Cook will lead Apple."
+ original = [_make_entity("Apple", "ORG", start=source.find("Apple"), end=source.find("Apple") + 5)]
+
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Tim Cook", label="PERSON", confidence=0.95),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities(source, original)
+
+ tim = next(e for e in result if e.text == "Tim Cook")
+ expected = source.find("Tim Cook")
+ assert tim.start_char == expected
+ assert tim.end_char == expected + len("Tim Cook")
+
+
+# ---------------------------------------------------------------------------
+# Entity enhancement — empty response, fallback, metadata
+# ---------------------------------------------------------------------------
+
+class TestEnhanceEntitiesEmptyResponse:
+ """Test 5 – Empty LLM response preserves the original list."""
+
+ def test_empty_response_preserves_originals(self):
+ original = [
+ _make_entity("Apple Inc.", "ORG"),
+ _make_entity("Tim Cook", "PERSON"),
+ ]
+ llm_resp = EntitiesResponse(entities=[])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("Apple Inc.", original)
+
+ assert len(result) == 2
+ texts = [e.text for e in result]
+ assert "Apple Inc." in texts
+ assert "Tim Cook" in texts
+
+
+class TestEnhanceEntitiesMalformedResponse:
+ """Test 6 – Provider raises; method falls back to original entities."""
+
+ def test_fallback_on_provider_error(self):
+ original = [_make_entity("Apple Inc.", "ORG")]
+ extractor = _make_failing_extractor()
+ result = extractor.enhance_entities("Apple Inc. is a company.", original)
+
+ assert len(result) == 1
+ assert result[0].text == "Apple Inc."
+
+
+class TestEnhanceEntitiesMetadata:
+ """Test 7 – enhanced_by and model metadata always present."""
+
+ def test_metadata_present_on_updated_entity(self):
+ original = [_make_entity("Apple Inc.", "PRODUCT")]
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("text", original)
+
+ assert result[0].metadata.get("enhanced_by") == "openai"
+ assert result[0].metadata.get("model") == "gpt-4"
+
+ def test_metadata_present_on_new_entity(self):
+ original = [_make_entity("Apple Inc.", "ORG")]
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ EntityOut(text="Steve Jobs", label="PERSON", confidence=0.95),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("Apple Inc. was founded by Steve Jobs.", original)
+
+ new_ent = next(e for e in result if e.text == "Steve Jobs")
+ assert new_ent.metadata.get("enhanced_by") == "openai"
+ assert new_ent.metadata.get("model") == "gpt-4"
+
+ def test_metadata_present_on_untouched_entity(self):
+ original = [
+ _make_entity("Apple Inc.", "ORG"),
+ _make_entity("Tim Cook", "PERSON"),
+ ]
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.98),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("text", original)
+
+ tim = next(e for e in result if e.text == "Tim Cook")
+ assert tim.metadata.get("enhanced_by") == "openai"
+
+
+class TestEnhanceEntitiesPreservesUntouched:
+ """Test 8 – Entities not referenced by the LLM are preserved unchanged."""
+
+ def test_untouched_entity_preserved(self):
+ original = [
+ _make_entity("Apple Inc.", "ORG", confidence=0.9),
+ _make_entity("Cupertino", "GPE", confidence=0.85),
+ ]
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("text", original)
+
+ cupertino = next(e for e in result if e.text == "Cupertino")
+ assert cupertino.label == "GPE"
+ assert cupertino.confidence == pytest.approx(0.85)
+
+
+# ---------------------------------------------------------------------------
+# Entity enhancement — repeated mentions
+# ---------------------------------------------------------------------------
+
+class TestEnhanceEntitiesRepeatedMentions:
+ """Test 9 – Same entity text at different offsets are ALL updated."""
+
+ def test_all_occurrences_updated(self):
+ """Apple appears twice at different offsets; both must get the updated label."""
+ source = "Apple is large. Apple is also profitable."
+ original = [
+ _make_entity("Apple", "PRODUCT", start=0, end=5),
+ _make_entity("Apple", "PRODUCT", start=16, end=21),
+ ]
+
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple", label="ORG", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities(source, original)
+
+ assert len(result) == 2
+ for ent in result:
+ assert ent.label == "ORG", (
+ "All occurrences of the entity text must receive the updated label"
+ )
+
+ def test_offsets_of_repeated_mentions_preserved(self):
+ """Original character positions must be preserved after an update."""
+ source = "Apple is large. Apple is also profitable."
+ original = [
+ _make_entity("Apple", "PRODUCT", start=0, end=5),
+ _make_entity("Apple", "PRODUCT", start=16, end=21),
+ ]
+
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple", label="ORG", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities(source, original)
+
+ spans = sorted((e.start_char, e.end_char) for e in result)
+ assert spans == [(0, 5), (16, 21)], (
+ "Character offsets must be preserved during an update"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Entity enhancement — deduplication
+# ---------------------------------------------------------------------------
+
+class TestNoDuplicateEntities:
+ """Test 10 – LLM repeating an entity does not duplicate it."""
+
+ def test_no_duplicate_on_repeated_existing_entity(self):
+ original = [_make_entity("Apple Inc.", "ORG")]
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.95),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("text", original)
+
+ apple_count = sum(1 for e in result if e.text == "Apple Inc.")
+ assert apple_count == 1
+
+ def test_no_duplicate_new_entity_mentioned_twice(self):
+ original = [_make_entity("Apple Inc.", "ORG")]
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Steve Jobs", label="PERSON", confidence=0.95),
+ EntityOut(text="Steve Jobs", label="PERSON", confidence=0.93),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("Steve Jobs founded Apple Inc.", original)
+
+ jobs_count = sum(1 for e in result if e.text == "Steve Jobs")
+ assert jobs_count == 1
+
+
+# ---------------------------------------------------------------------------
+# Relation enhancement — predicate correction (subject+object identity)
+# ---------------------------------------------------------------------------
+
+class TestEnhanceRelationsPredicateUpdate:
+ """Test 11 – Relation enhancement matching uses (subject, predicate, object) identity.
+
+ The prompt sends all existing relations WITH their predicates to the LLM, so
+ the LLM has full context. An exact-triple match updates confidence; a
+ response with a different predicate is additive (new relation appended).
+ """
+
+ def test_exact_triple_match_updates_confidence(self):
+ """When the LLM returns the same (subj, pred, obj), only confidence changes."""
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs", confidence=0.5)]
+
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.99),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ assert len(result) == 1
+ assert result[0].predicate == "founded_by"
+ assert result[0].confidence == pytest.approx(0.99)
+
+ def test_new_predicate_is_appended_not_overwritten(self):
+ """When the LLM returns a different predicate for an existing (subj, obj),
+ the result is additive: original is preserved and new predicate is appended.
+ Enhancement never silently deletes existing graph edges."""
+ original = [_make_relation("Apple Inc.", "related_to", "Steve Jobs")]
+
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations(
+ "Apple Inc. was founded by Steve Jobs.", original
+ )
+
+ predicates = {r.predicate for r in result}
+ assert "related_to" in predicates, "Original relation must be preserved"
+ assert "founded_by" in predicates, "LLM-suggested new predicate must be appended"
+ assert len(result) == 2
+
+
+class TestEnhanceRelationsConfidenceUpdate:
+ """Test 12 – LLM updates an existing relation's confidence."""
+
+ def test_confidence_is_updated(self):
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs", confidence=0.5)]
+
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.99),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ assert result[0].confidence == pytest.approx(0.99)
+
+
+# ---------------------------------------------------------------------------
+# Relation enhancement — new relation, empty, fallback, metadata
+# ---------------------------------------------------------------------------
+
+class TestEnhanceRelationsNewRelation:
+ """Test 13 – LLM adds a new relation absent from the original list."""
+
+ def test_new_relation_appended(self):
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs")]
+
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.97),
+ RelationOut(subject="Apple Inc.", predicate="located_in",
+ object="Cupertino", confidence=0.95),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations(
+ "Apple Inc. is located in Cupertino.", original
+ )
+
+ predicates = [r.predicate for r in result]
+ assert "located_in" in predicates
+ assert len(result) == 2
+
+
+class TestEnhanceRelationsEmptyResponse:
+ """Test 14 – Empty LLM response preserves the original relations."""
+
+ def test_empty_response_preserves_originals(self):
+ original = [
+ _make_relation("Apple Inc.", "founded_by", "Steve Jobs"),
+ _make_relation("Steve Jobs", "ceo_of", "Apple Inc."),
+ ]
+ llm_resp = RelationsResponse(relations=[])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ assert len(result) == 2
+
+
+class TestEnhanceRelationsMalformedResponse:
+ """Test 15 – Provider raises; method falls back to original relations."""
+
+ def test_fallback_on_provider_error(self):
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs")]
+ extractor = _make_failing_extractor()
+ result = extractor.enhance_relations("text", original)
+
+ assert len(result) == 1
+ assert result[0].predicate == "founded_by"
+
+
+class TestEnhanceRelationsMetadata:
+ """Test 16 – enhanced_by and model metadata always present on relations."""
+
+ def test_metadata_present_on_updated_relation(self):
+ original = [_make_relation("Apple Inc.", "related_to", "Steve Jobs")]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ assert result[0].metadata.get("enhanced_by") == "openai"
+ assert result[0].metadata.get("model") == "gpt-4"
+
+ def test_metadata_present_on_new_relation(self):
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs")]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.97),
+ RelationOut(subject="Apple Inc.", predicate="located_in",
+ object="Cupertino", confidence=0.9),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ new_rel = next(r for r in result if r.predicate == "located_in")
+ assert new_rel.metadata.get("enhanced_by") == "openai"
+ assert new_rel.metadata.get("model") == "gpt-4"
+
+ def test_metadata_present_on_untouched_relation(self):
+ original = [
+ _make_relation("Apple Inc.", "founded_by", "Steve Jobs"),
+ _make_relation("Steve Jobs", "ceo_of", "Apple Inc."),
+ ]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ untouched = next(r for r in result if r.predicate == "ceo_of")
+ assert untouched.metadata.get("enhanced_by") == "openai"
+
+
+class TestEnhanceRelationsPreservesUntouched:
+ """Test 17 – Relations not referenced by the LLM are preserved unchanged."""
+
+ def test_untouched_relation_preserved(self):
+ original = [
+ _make_relation("Apple Inc.", "founded_by", "Steve Jobs", confidence=0.9),
+ _make_relation("Steve Jobs", "ceo_of", "Apple Inc.", confidence=0.85),
+ ]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ untouched = next(r for r in result if r.predicate == "ceo_of")
+ assert untouched.subject.text == "Steve Jobs"
+ assert untouched.confidence == pytest.approx(0.85)
+
+
+# ---------------------------------------------------------------------------
+# Relation enhancement — deduplication
+# ---------------------------------------------------------------------------
+
+class TestNoDuplicateRelations:
+ """Test 18 – LLM repeating the same (subject, object) pair does not
+ duplicate relations."""
+
+ def test_no_duplicate_on_repeated_pair(self):
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs")]
+
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.97),
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.95),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ count = sum(
+ 1 for r in result
+ if r.subject.text == "Apple Inc." and r.object.text == "Steve Jobs"
+ )
+ assert count == 1
+
+ def test_no_duplicate_new_relation_mentioned_twice(self):
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs")]
+
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="located_in",
+ object="Cupertino", confidence=0.9),
+ RelationOut(subject="Apple Inc.", predicate="located_in",
+ object="Cupertino", confidence=0.85),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ new_count = sum(1 for r in result if r.object.text == "Cupertino")
+ assert new_count == 1
+
+
+# ---------------------------------------------------------------------------
+# Relation enhancement — multiple predicates same endpoints (core correctness)
+# ---------------------------------------------------------------------------
+
+class TestMultiplePredicatesSameEndpoints:
+ """Tests 19 — Multiple relations with the same endpoints but different
+ predicates must remain independent. An LLM response for one predicate
+ must not overwrite the other."""
+
+ def test_unrelated_predicate_not_overwritten(self):
+ """Core correctness: Apple→founded_by→Jobs and Apple→employs→Jobs.
+ LLM returns founded_by — employs must NOT be changed."""
+ original = [
+ _make_relation("Apple Inc.", "founded_by", "Steve Jobs"),
+ _make_relation("Apple Inc.", "employs", "Steve Jobs"),
+ ]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.99),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ assert len(result) == 2, "Both original relations must be preserved"
+ predicates = {r.predicate for r in result}
+ assert "founded_by" in predicates
+ assert "employs" in predicates, (
+ "employs relation must not be overwritten by the founded_by LLM response"
+ )
+
+ def test_founded_by_confidence_updated_employs_unchanged(self):
+ """founded_by confidence must be updated; employs confidence must stay unchanged."""
+ original = [
+ _make_relation("Apple Inc.", "founded_by", "Steve Jobs", confidence=0.5),
+ _make_relation("Apple Inc.", "employs", "Steve Jobs", confidence=0.8),
+ ]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.99),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ founded = next(r for r in result if r.predicate == "founded_by")
+ employs = next(r for r in result if r.predicate == "employs")
+ assert founded.confidence == pytest.approx(0.99)
+ assert employs.confidence == pytest.approx(0.8), (
+ "employs confidence must be unchanged"
+ )
+
+ def test_llm_can_add_second_predicate_between_same_pair(self):
+ """LLM can legitimately add a second predicate between an existing pair."""
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs")]
+
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.99),
+ RelationOut(subject="Apple Inc.", predicate="employs",
+ object="Steve Jobs", confidence=0.85),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ predicates = {r.predicate for r in result}
+ assert "founded_by" in predicates
+ assert "employs" in predicates
+ assert len(result) == 2
+
+
+# ---------------------------------------------------------------------------
+# Relation endpoint resolution
+# ---------------------------------------------------------------------------
+
+class TestNewRelationEndpointResolution:
+ """Tests 20–21 — endpoint resolution for new relations."""
+
+ def test_new_relation_reuses_canonical_subject_entity(self):
+ """Test 20: New relation's subject resolves to the canonical entity."""
+ apple_entity = Entity(
+ text="Apple Inc.", label="ORG",
+ start_char=0, end_char=10,
+ confidence=0.95,
+ metadata={"canonical": True},
+ )
+ original = [
+ Relation(
+ subject=apple_entity,
+ predicate="founded_by",
+ object=_make_entity("Steve Jobs", "PERSON"),
+ confidence=0.9, context="", metadata={},
+ )
+ ]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="located_in",
+ object="Cupertino", confidence=0.88),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("Apple Inc. is in Cupertino.", original)
+
+ new_rel = next(r for r in result if r.predicate == "located_in")
+ assert new_rel.subject.label == "ORG"
+ assert new_rel.subject.metadata.get("canonical") is True
+
+ def test_unresolvable_endpoint_becomes_synthetic(self):
+ """Test 21: Unknown endpoint becomes a synthetic UNKNOWN entity."""
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs")]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Completely Unknown Corp", predicate="partner_of",
+ object="Apple Inc.", confidence=0.7),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ new_rel = next(r for r in result if r.predicate == "partner_of")
+ assert new_rel.subject.label == "UNKNOWN"
+ assert new_rel.subject.metadata.get("synthetic") is True
+ assert new_rel.object.label == "ORG"
+
+ def test_synthetic_endpoint_span_located_in_source_text(self):
+ """Finding #2: A synthetic endpoint that appears in the source text must
+ receive its actual character span, not a fabricated (0, len(name)) value."""
+ source = "The Board met. Tim Cook announced that Apple would expand."
+ # Only Apple is in the original relation pool
+ apple = Entity(text="Apple", label="ORG", start_char=40, end_char=45,
+ confidence=0.9, metadata={})
+ original = [
+ Relation(
+ subject=apple,
+ predicate="will_expand",
+ object=_make_entity("market", "CONCEPT"),
+ confidence=0.8, context="", metadata={},
+ )
+ ]
+ llm_resp = RelationsResponse(relations=[
+ # Tim Cook is NOT in the original entity pool → synthetic
+ RelationOut(subject="Tim Cook", predicate="leads",
+ object="Apple", confidence=0.95),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations(source, original)
+
+ new_rel = next(r for r in result if r.predicate == "leads")
+ expected_start = source.find("Tim Cook")
+ assert new_rel.subject.start_char == expected_start, (
+ "Synthetic endpoint must be located at its actual position in source text"
+ )
+ assert new_rel.subject.end_char == expected_start + len("Tim Cook")
+
+ def test_synthetic_endpoint_absent_from_text_gets_zero_span(self):
+ """Finding #2: A synthetic endpoint that genuinely does not appear in the
+ source text must receive the (0, 0) sentinel, not a fabricated span."""
+ source = "Apple was founded in 1976."
+ original = [_make_relation("Apple", "founded_in", "1976")]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Nonexistent Entity XYZ", predicate="partner_of",
+ object="Apple", confidence=0.7),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations(source, original)
+
+ new_rel = next(r for r in result if r.predicate == "partner_of")
+ assert new_rel.subject.start_char == 0
+ assert new_rel.subject.end_char == 0, (
+ "Endpoint absent from source text must receive (0, 0) sentinel span"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Temperature propagation (Finding 6)
+# ---------------------------------------------------------------------------
+
+class TestTemperaturePropagation:
+ """Tests 22–23 — temperature is always forwarded to generate_typed."""
+
+ def test_temperature_none_is_forwarded(self):
+ """Test 22: temperature=None must be forwarded so providers.py can apply
+ its own default (0.1 for instructor) consistently."""
+ original = [_make_entity("Apple Inc.", "ORG")]
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp, temperature=None)
+ extractor.enhance_entities("Apple Inc.", original)
+
+ call_kwargs = extractor.provider.generate_typed.call_args[1]
+ assert "temperature" in call_kwargs, (
+ "temperature must always be passed to generate_typed"
+ )
+ assert call_kwargs["temperature"] is None
+
+ def test_explicit_temperature_is_forwarded(self):
+ """Test 23: an explicit temperature value is forwarded unchanged."""
+ original = [_make_entity("Apple Inc.", "ORG")]
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp, temperature=0.7)
+ extractor.enhance_entities("Apple Inc.", original)
+
+ call_kwargs = extractor.provider.generate_typed.call_args[1]
+ assert call_kwargs.get("temperature") == pytest.approx(0.7)
+
+ def test_option_temperature_overrides_instance(self):
+ """Per-call temperature option takes priority over instance temperature."""
+ original = [_make_entity("Apple Inc.", "ORG")]
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp, temperature=0.5)
+ extractor.enhance_entities("Apple Inc.", original, temperature=0.2)
+
+ call_kwargs = extractor.provider.generate_typed.call_args[1]
+ assert call_kwargs.get("temperature") == pytest.approx(0.2)
+
+ def test_temperature_none_also_forwarded_for_relations(self):
+ """Temperature=None is forwarded for relation enhancement too."""
+ original = [_make_relation("Apple Inc.", "founded_by", "Steve Jobs")]
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp, temperature=None)
+ extractor.enhance_relations("text", original)
+
+ call_kwargs = extractor.provider.generate_typed.call_args[1]
+ assert "temperature" in call_kwargs
+ assert call_kwargs["temperature"] is None
+
+
+# ---------------------------------------------------------------------------
+# Case-insensitive matching
+# ---------------------------------------------------------------------------
+
+class TestCaseInsensitiveMatching:
+ """Tests 24–25 — matching is case-insensitive."""
+
+ def test_entity_match_is_case_insensitive(self):
+ """Test 24: entity matched case-insensitively; original casing preserved."""
+ original = [_make_entity("apple inc.", "PRODUCT")]
+
+ llm_resp = EntitiesResponse(entities=[
+ EntityOut(text="Apple Inc.", label="ORG", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_entities("text", original)
+
+ assert len(result) == 1
+ assert result[0].label == "ORG"
+
+ def test_relation_match_is_case_insensitive(self):
+ """Test 25: triple matched case-insensitively; same predicate updates
+ only confidence."""
+ original = [_make_relation("apple inc.", "founded_by", "steve jobs",
+ confidence=0.5)]
+
+ llm_resp = RelationsResponse(relations=[
+ RelationOut(subject="Apple Inc.", predicate="founded_by",
+ object="Steve Jobs", confidence=0.97),
+ ])
+ extractor = _make_extractor(llm_resp)
+ result = extractor.enhance_relations("text", original)
+
+ # Exact triple match (case-insensitive) -> update confidence, no append
+ assert len(result) == 1
+ assert result[0].predicate == "founded_by"
+ assert result[0].confidence == pytest.approx(0.97)