Skip to content

Phase Component Reference

Injected extractors, linkers, rerankers, and classifiers used across Phases 2–4. As injected computational units they are recursively discovered by find_components and their state is fingerprinted for run invalidation and phase reuse.

Entity Linkers & NER (Phase 2)

DenseEntityLinker

Dense retrieval based entity linker.

Bases: EntityLinker

Entity linker using dense retrieval (bi-encoder) and structural reranking (cross-encoder).

Parameters

embedding_model : EmbeddingModel | str | None, optional Bi-encoder used to embed the mention envelope and candidate envelopes. Must satisfy :class:EmbeddingModel. If None, defaults to :class:HuggingFaceEmbeddingModel. cross_encoder : CrossEncoder | None, optional Reranker scoring (mention envelope, candidate structural envelope) pairs. Must satisfy :class:CrossEncoder and return probability-like scores. tau : float, default 0.85 Acceptance threshold on the cross-encoder score in [0, 1]. top_k : int, default 10 Number of bi-encoder candidates forwarded to the cross-encoder.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/sota_entity_linker.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
class DenseEntityLinker(EntityLinker):
    """
    Entity linker using dense retrieval (bi-encoder) and structural reranking (cross-encoder).

    Parameters
    ----------
    embedding_model : EmbeddingModel | str | None, optional
        Bi-encoder used to embed the mention envelope and candidate envelopes.
        Must satisfy :class:`EmbeddingModel`. If None, defaults to :class:`HuggingFaceEmbeddingModel`.
    cross_encoder : CrossEncoder | None, optional
        Reranker scoring ``(mention envelope, candidate structural envelope)`` pairs. Must
        satisfy :class:`CrossEncoder` and return probability-like scores.
    tau : float, default 0.85
        Acceptance threshold on the cross-encoder score in ``[0, 1]``.
    top_k : int, default 10
        Number of bi-encoder candidates forwarded to the cross-encoder.
    """

    def __init__(
        self,
        embedding_model: EmbeddingModel | str | None = None,
        cross_encoder: CrossEncoder | None = None,
        tau: float = 0.85,
        top_k: int = 10,
    ):
        from episteme_pipeline.protocols.extractors import HuggingFaceEmbeddingModel

        if embedding_model is None:
            self.embedding_model: EmbeddingModel = HuggingFaceEmbeddingModel()
        elif isinstance(embedding_model, str):
            self.embedding_model = HuggingFaceEmbeddingModel(model_name=embedding_model)
        else:
            self.embedding_model = ensure_embedding_model(embedding_model)

        self.cross_encoder: CrossEncoder | None = cross_encoder
        self.tau = tau
        self.top_k = top_k
        # Candidate envelope cache
        # Key: entity.id
        # Value: (bi-encoder_text, bi-encoder_vector)
        self._candidate_cache: dict[str, tuple[str, list[float]]] = {}

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic dense entity linker configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing tau threshold, top_k, and fingerprints of
            embedding model and cross encoder.
        """
        from episteme_pipeline.runs.fingerprints import fingerprint_method

        return {
            "class": self.__class__.__name__,
            "tau": self.tau,
            "top_k": self.top_k,
            "embedding_model": fingerprint_method(self.embedding_model),
            "cross_encoder": fingerprint_method(self.cross_encoder) if self.cross_encoder else None,
        }

    @property
    def event_emitter(self) -> EventEmitter:
        from episteme_pipeline.events.context import get_event_emitter
        return get_event_emitter()

    @staticmethod
    def _canonical_entity_string(candidate: L2Entity) -> str:
        """Format candidate entity for bi-encoder embedding with explicit type grounding."""
        return f"[{candidate.label}] {candidate.name}: {candidate.description or ''}"

    async def _populate_candidate_cache(self, candidates: list[L2Entity], graph_store: GraphReader) -> None:
        """Pre-fetch basic texts and embeddings for new or stale candidates."""
        stale_candidates = []
        stale_basic_texts = []
        for c in candidates:
            basic_text = self._canonical_entity_string(c)
            cached = self._candidate_cache.get(c.id)
            if not cached or cached[0] != basic_text:
                stale_candidates.append(c)
                stale_basic_texts.append(basic_text)

        if not stale_candidates:
            return

        fresh_vectors = await self.embedding_model.aget_text_embedding_batch(stale_basic_texts)
        for c, b_text, vec in zip(stale_candidates, stale_basic_texts, fresh_vectors):
            self._candidate_cache[c.id] = (b_text, vec)

    async def _candidate_embeddings(self, candidates: list[L2Entity]) -> torch.Tensor:
        """Return vectors from cache as float tensor."""
        embs = [self._candidate_cache[c.id][1] for c in candidates]
        return as_tensor(embs)

    async def link(
        self,
        mention: L2Entity,
        graph_store: GraphReader,
        *,
        top_k: int | None = None,
        threshold: float | None = None,
    ) -> L2Entity | None:
        effective_top_k = self.top_k if top_k is None else top_k
        tau = self.tau if threshold is None else threshold

        if not mention.textual_envelope:
            logger.warning(f"Mention {mention.name} lacks textual envelope. Raising UnlinkableMentionError.")
            raise UnlinkableMentionError(f"Mention {mention.name} lacks textual envelope.")

        # 1. Bi-Encoder: Cosine Similarity over L2-normalized embeddings
        T_n = f"[{mention.label}] {mention.textual_envelope}"
        raw_T_n_emb = await self.embedding_model.aget_text_embedding_batch([T_n])
        T_n_emb = as_tensor(raw_T_n_emb)[0]
        # L2-normalize mention vector
        T_n_emb = torch.nn.functional.normalize(T_n_emb, p=2, dim=0)

        candidates = await graph_store.get_entities()
        if not candidates:
            return None

        # Pre-fetch and cache vectors
        await self._populate_candidate_cache(candidates, graph_store)
        G_embs = await self._candidate_embeddings(candidates)

        # L2-normalize candidate vectors
        G_embs = torch.nn.functional.normalize(G_embs, p=2, dim=1)

        # Cosine similarity (since both are normalized, dot product = cosine)
        scores = torch.matmul(G_embs, T_n_emb)
        top_k_indices = torch.topk(scores, min(effective_top_k, len(candidates))).indices

        top_candidates = [candidates[i] for i in top_k_indices]
        top_scores = scores[top_k_indices].tolist()

        # Emit candidates retrieved event
        self.event_emitter.emit(
            EntityLinkingCandidatesRetrieved(
                mention_id=mention.id,
                mention_name=mention.name,
                candidate_count=len(top_candidates),
                candidates=[
                    {"id": c.id, "name": c.name, "score": float(s)}
                    for c, s in zip(top_candidates, top_scores)
                ]
            )
        )

        # 2. Cross-Encoder: Structural Evaluation (L07 Option B)
        # Fetch actual 1-hop subgraph ONLY for the top-k candidates
        import asyncio

        from episteme_pipeline.prompts.input_formatters import InputFormatStrategy
        from episteme_pipeline.utils import format_envelope

        tasks = [graph_store.get_neighborhood(c.id, depth=1) for c in top_candidates]
        subgraphs = await asyncio.gather(*tasks, return_exceptions=True)

        empty_subgraph = SubGraph(center_id="", nodes=[], triples=[], depth=0)
        top_G_structs = []
        for c, sg in zip(top_candidates, subgraphs):
            if isinstance(sg, Exception):
                logger.warning(f"Failed to fetch neighborhood for cross-encoder reranking of {c.name}: {sg}")
                sg = SubGraph(center_id=c.id, nodes=[c], triples=[], depth=1)
            top_G_structs.append(format_envelope(sg, empty_subgraph, strategy=InputFormatStrategy.TEXT))

        # [CLS] T_n [SEP] G_k_struct [SEP]
        cross_inputs = [(T_n, G_k_struct) for G_k_struct in top_G_structs]
        cross_scores = normalize_scores(self.cross_encoder.predict(cross_inputs))

        best_idx = argmax(cross_scores)
        best_score = cross_scores[best_idx]
        best_candidate = top_candidates[best_idx]

        accepted = best_score >= tau

        # Emit reranker score event
        self.event_emitter.emit(
            EntityLinkingReranked(
                mention_id=mention.id,
                mention_name=mention.name,
                candidate_id=best_candidate.id,
                candidate_name=best_candidate.name,
                score=best_score,
                accepted=accepted,
                threshold=tau,
            )
        )

        # 3. Resolution Threshold
        if accepted:
            logger.debug(f"DenseLinked {mention.name} -> {best_candidate.name} (Score: {best_score})")
            return best_candidate

        # Pass to LLM Reasoner (returns None to mint novel node)
        logger.debug(f"DenseLinker failed to cross threshold tau={tau} for {mention.name}. Max score: {best_score}")
        return None

fingerprint()

Return deterministic dense entity linker configuration.

Returns

dict of str to Any Dictionary containing tau threshold, top_k, and fingerprints of embedding model and cross encoder.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/sota_entity_linker.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic dense entity linker configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing tau threshold, top_k, and fingerprints of
        embedding model and cross encoder.
    """
    from episteme_pipeline.runs.fingerprints import fingerprint_method

    return {
        "class": self.__class__.__name__,
        "tau": self.tau,
        "top_k": self.top_k,
        "embedding_model": fingerprint_method(self.embedding_model),
        "cross_encoder": fingerprint_method(self.cross_encoder) if self.cross_encoder else None,
    }

JevEntityLinker

Bases: EntityLinker

Entity linker backed by TypeSafe Jev / Laya calibrated decision engine.

Performs bi-encoder candidate retrieval from the active graph store followed by Jev categorical choice disambiguation with conformal prediction guarantees and explicit Out-of-Ontology (OoO) detection.

Parameters

decision_engine : DecisionEngine Calibrated decision engine supporting evaluate_choice. embedding_model : EmbeddingModel or str or None, default None Bi-encoder used to embed mentions and candidate nodes. If None, defaults to HuggingFaceEmbeddingModel. alpha : float, default 0.05 Conformal significance level providing 1 - alpha prediction set coverage. top_k : int, default 5 Maximum number of candidate entities evaluated in the Jev choice prompt. Bounded to 5 by default to prevent context window saturation. ooo_threshold : float, default 0.75 Confidence threshold fallback for Out-of-Ontology decisions.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/jev_entity_linker.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
class JevEntityLinker(EntityLinker):
    """Entity linker backed by TypeSafe Jev / Laya calibrated decision engine.

    Performs bi-encoder candidate retrieval from the active graph store followed
    by Jev categorical choice disambiguation with conformal prediction guarantees
    and explicit Out-of-Ontology (OoO) detection.

    Parameters
    ----------
    decision_engine : DecisionEngine
        Calibrated decision engine supporting ``evaluate_choice``.
    embedding_model : EmbeddingModel or str or None, default None
        Bi-encoder used to embed mentions and candidate nodes. If None,
        defaults to ``HuggingFaceEmbeddingModel``.
    alpha : float, default 0.05
        Conformal significance level providing 1 - alpha prediction set coverage.
    top_k : int, default 5
        Maximum number of candidate entities evaluated in the Jev choice prompt.
        Bounded to 5 by default to prevent context window saturation.
    ooo_threshold : float, default 0.75
        Confidence threshold fallback for Out-of-Ontology decisions.
    """

    def __init__(
        self,
        decision_engine: DecisionEngine,
        embedding_model: EmbeddingModel | Any,
        alpha: float = 0.05,
        top_k: int = 5,
        ooo_threshold: float = 0.75,
    ) -> None:
        engine = ensure_decision_engine(decision_engine)
        if engine is None:
            raise ValueError("A valid DecisionEngine must be provided to JevEntityLinker.")
        self.decision_engine: DecisionEngine = engine

        model = ensure_embedding_model(embedding_model)
        if model is None:
            raise ValueError("A valid EmbeddingModel must be provided to JevEntityLinker.")
        self.embedding_model: EmbeddingModel = model

        self.alpha = alpha
        self.top_k = top_k
        self.ooo_threshold = ooo_threshold

        # Candidate envelope cache: entity_id -> (text, embedding)
        self._candidate_cache: dict[str, tuple[str, list[float]]] = {}

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic Jev entity linker configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing alpha, top_k, ooo_threshold, and fingerprints of
            embedding model and decision engine.
        """
        from episteme_pipeline.runs.fingerprints import fingerprint_method

        de_fp = (
            self.decision_engine.fingerprint()
            if hasattr(self.decision_engine, "fingerprint") and callable(self.decision_engine.fingerprint)
            else fingerprint_method(self.decision_engine)
        )
        return {
            "class": self.__class__.__name__,
            "alpha": self.alpha,
            "top_k": self.top_k,
            "ooo_threshold": self.ooo_threshold,
            "embedding_model": fingerprint_method(self.embedding_model),
            "decision_engine": de_fp,
        }

    @property
    def event_emitter(self) -> EventEmitter:
        """Return the bound domain event emitter."""
        return get_event_emitter()

    @staticmethod
    def _canonical_entity_string(candidate: L2Entity) -> str:
        """Format candidate entity for bi-encoder embedding with explicit type grounding."""
        return f"[{candidate.label}] {candidate.name}: {candidate.description or ''}"

    async def _populate_candidate_cache(self, candidates: list[L2Entity]) -> None:
        """Pre-fetch embeddings for new or stale candidates."""
        stale_candidates = []
        stale_basic_texts = []
        for c in candidates:
            basic_text = self._canonical_entity_string(c)
            cached = self._candidate_cache.get(c.id)
            if not cached or cached[0] != basic_text:
                stale_candidates.append(c)
                stale_basic_texts.append(basic_text)

        if not stale_candidates:
            return

        fresh_vectors = await self.embedding_model.aget_text_embedding_batch(stale_basic_texts)
        for c, b_text, vec in zip(stale_candidates, stale_basic_texts, fresh_vectors):
            self._candidate_cache[c.id] = (b_text, vec)

    async def _candidate_embeddings(self, candidates: list[L2Entity]) -> torch.Tensor:
        """Return cached embeddings as a torch Tensor."""
        embs = [self._candidate_cache[c.id][1] for c in candidates]
        return as_tensor(embs)

    async def link_with_decision(
        self,
        mention: L2Entity,
        graph_store: GraphReader,
        *,
        top_k: int | None = None,
        threshold: float | None = None,
        alpha: float | None = None,
    ) -> tuple[L2Entity | None, DecisionScore | None, bool]:
        """Link a mention to a canonical entity and return detailed decision telemetry.

        Parameters
        ----------
        mention : L2Entity
            The extracted entity mention to link.
        graph_store : GraphReader
            Active graph store holding canonical entities.
        top_k : int or None, default None
            Optional override for candidate retrieval count (bounded to 5).
        threshold : float or None, default None
            Optional override for acceptance threshold.
        alpha : float or None, default None
            Optional override for conformal significance level.

        Returns
        -------
        tuple of (L2Entity or None, DecisionScore or None, bool)
            - Matched canonical entity, or None if novel/ambiguous.
            - Decision score telemetry from the DecisionEngine.
            - ``is_ambiguous`` flag indicating whether decision escalated (e.g.
              conformal set size > 1 or empty).
        """
        if not mention.textual_envelope:
            logger.warning("Mention %s lacks textual envelope. Raising UnlinkableMentionError.", mention.name)
            raise UnlinkableMentionError(f"Mention {mention.name} lacks textual envelope.")

        effective_top_k = min(self.top_k if top_k is None else top_k, 5)
        effective_alpha = self.alpha if alpha is None else alpha
        effective_threshold = self.ooo_threshold if threshold is None else threshold

        candidates = await graph_store.get_entities()
        if not candidates:
            return None, None, False

        # 1. Bi-Encoder retrieval
        t_n = f"[{mention.label}] {mention.textual_envelope}"
        raw_t_n_emb = await self.embedding_model.aget_text_embedding_batch([t_n])
        t_n_emb = as_tensor(raw_t_n_emb)[0]
        t_n_emb = torch.nn.functional.normalize(t_n_emb, p=2, dim=0)

        await self._populate_candidate_cache(candidates)
        g_embs = await self._candidate_embeddings(candidates)
        g_embs = torch.nn.functional.normalize(g_embs, p=2, dim=1)

        scores = torch.matmul(g_embs, t_n_emb)
        top_k_indices = torch.topk(scores, min(effective_top_k, len(candidates))).indices

        top_candidates = [candidates[i] for i in top_k_indices]
        top_scores = scores[top_k_indices].tolist()

        self.event_emitter.emit(
            EntityLinkingCandidatesRetrieved(
                mention_id=mention.id,
                mention_name=mention.name,
                candidate_count=len(top_candidates),
                candidates=[
                    {"id": c.id, "name": c.name, "score": float(s)}
                    for c, s in zip(top_candidates, top_scores)
                ],
            )
        )

        # 2. In-context Jev Choice options formulation
        options: dict[str, str] = {}
        key_to_candidate: dict[str, L2Entity] = {}
        for c in top_candidates:
            key = c.name
            if key in options:
                key = f"{c.name} ({c.id})"
            options[key] = c.description or f"Entity [{c.label}]"
            key_to_candidate[key] = c

        options["OUT_OF_ONTOLOGY"] = "Novel entity not represented in candidates"

        # 3. Jev Choice evaluation
        state = f"Mention: {mention.name}\nContext:\n{t_n}"
        question = "Which entity best matches this mention?"
        decision = await self.decision_engine.evaluate_choice(
            state=state,
            question=question,
            options=options,
            alpha=effective_alpha,
        )

        conformal_set = decision.prediction_set
        if conformal_set is None:
            conformal_set = [str(decision.selected_option)] if decision.selected_option is not None else []

        # If conformal set contains multiple candidates or is empty (uncertain), mark ambiguous
        if len(conformal_set) > 1 or len(conformal_set) == 0:
            logger.debug(
                "JevEntityLinker: ambiguous conformal set %s for mention %s",
                conformal_set,
                mention.name,
            )
            return None, decision, True

        selected = conformal_set[0]

        # Case: Confidently novel Out-of-Ontology
        if selected == "OUT_OF_ONTOLOGY":
            logger.debug("JevEntityLinker: Out-of-Ontology declared for %s", mention.name)
            self.event_emitter.emit(
                EntityLinkingReranked(
                    mention_id=mention.id,
                    mention_name=mention.name,
                    candidate_id="OUT_OF_ONTOLOGY",
                    candidate_name="OUT_OF_ONTOLOGY",
                    score=decision.empirical_accuracy,
                    accepted=False,
                    threshold=effective_threshold,
                )
            )
            return None, decision, False

        # Case: Confidently matched single canonical entity
        matched = key_to_candidate.get(selected)
        if matched is not None:
            logger.debug(
                "JevEntityLinker: linked %s -> %s (Acc: %s)",
                mention.name,
                matched.name,
                decision.empirical_accuracy,
            )
            self.event_emitter.emit(
                EntityLinkingReranked(
                    mention_id=mention.id,
                    mention_name=mention.name,
                    candidate_id=matched.id,
                    candidate_name=matched.name,
                    score=decision.empirical_accuracy,
                    accepted=True,
                    threshold=effective_threshold,
                )
            )
            return matched, decision, False

        return None, decision, True

    async def link(
        self,
        mention: L2Entity,
        graph_store: GraphReader,
        *,
        top_k: int | None = None,
        threshold: float | None = None,
    ) -> L2Entity | None:
        """Link an extracted entity mention to an existing canonical graph node.

        Parameters
        ----------
        mention : L2Entity
            The extracted entity mention.
        graph_store : GraphReader
            Active graph store.
        top_k : int or None, default None
            Optional override for candidate retrieval count.
        threshold : float or None, default None
            Optional override for confidence threshold.

        Returns
        -------
        L2Entity or None
            The matched canonical entity, or None if novel or ambiguous.
        """
        matched, _, _ = await self.link_with_decision(
            mention, graph_store, top_k=top_k, threshold=threshold
        )
        return matched

event_emitter property

Return the bound domain event emitter.

fingerprint()

Return deterministic Jev entity linker configuration.

Returns

dict of str to Any Dictionary containing alpha, top_k, ooo_threshold, and fingerprints of embedding model and decision engine.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/jev_entity_linker.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic Jev entity linker configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing alpha, top_k, ooo_threshold, and fingerprints of
        embedding model and decision engine.
    """
    from episteme_pipeline.runs.fingerprints import fingerprint_method

    de_fp = (
        self.decision_engine.fingerprint()
        if hasattr(self.decision_engine, "fingerprint") and callable(self.decision_engine.fingerprint)
        else fingerprint_method(self.decision_engine)
    )
    return {
        "class": self.__class__.__name__,
        "alpha": self.alpha,
        "top_k": self.top_k,
        "ooo_threshold": self.ooo_threshold,
        "embedding_model": fingerprint_method(self.embedding_model),
        "decision_engine": de_fp,
    }

Link an extracted entity mention to an existing canonical graph node.

mention : L2Entity The extracted entity mention. graph_store : GraphReader Active graph store. top_k : int or None, default None Optional override for candidate retrieval count. threshold : float or None, default None Optional override for confidence threshold.

L2Entity or None The matched canonical entity, or None if novel or ambiguous.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/jev_entity_linker.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
async def link(
    self,
    mention: L2Entity,
    graph_store: GraphReader,
    *,
    top_k: int | None = None,
    threshold: float | None = None,
) -> L2Entity | None:
    """Link an extracted entity mention to an existing canonical graph node.

    Parameters
    ----------
    mention : L2Entity
        The extracted entity mention.
    graph_store : GraphReader
        Active graph store.
    top_k : int or None, default None
        Optional override for candidate retrieval count.
    threshold : float or None, default None
        Optional override for confidence threshold.

    Returns
    -------
    L2Entity or None
        The matched canonical entity, or None if novel or ambiguous.
    """
    matched, _, _ = await self.link_with_decision(
        mention, graph_store, top_k=top_k, threshold=threshold
    )
    return matched

Link a mention to a canonical entity and return detailed decision telemetry.

mention : L2Entity The extracted entity mention to link. graph_store : GraphReader Active graph store holding canonical entities. top_k : int or None, default None Optional override for candidate retrieval count (bounded to 5). threshold : float or None, default None Optional override for acceptance threshold. alpha : float or None, default None Optional override for conformal significance level.

tuple of (L2Entity or None, DecisionScore or None, bool) - Matched canonical entity, or None if novel/ambiguous. - Decision score telemetry from the DecisionEngine. - is_ambiguous flag indicating whether decision escalated (e.g. conformal set size > 1 or empty).

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/jev_entity_linker.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
async def link_with_decision(
    self,
    mention: L2Entity,
    graph_store: GraphReader,
    *,
    top_k: int | None = None,
    threshold: float | None = None,
    alpha: float | None = None,
) -> tuple[L2Entity | None, DecisionScore | None, bool]:
    """Link a mention to a canonical entity and return detailed decision telemetry.

    Parameters
    ----------
    mention : L2Entity
        The extracted entity mention to link.
    graph_store : GraphReader
        Active graph store holding canonical entities.
    top_k : int or None, default None
        Optional override for candidate retrieval count (bounded to 5).
    threshold : float or None, default None
        Optional override for acceptance threshold.
    alpha : float or None, default None
        Optional override for conformal significance level.

    Returns
    -------
    tuple of (L2Entity or None, DecisionScore or None, bool)
        - Matched canonical entity, or None if novel/ambiguous.
        - Decision score telemetry from the DecisionEngine.
        - ``is_ambiguous`` flag indicating whether decision escalated (e.g.
          conformal set size > 1 or empty).
    """
    if not mention.textual_envelope:
        logger.warning("Mention %s lacks textual envelope. Raising UnlinkableMentionError.", mention.name)
        raise UnlinkableMentionError(f"Mention {mention.name} lacks textual envelope.")

    effective_top_k = min(self.top_k if top_k is None else top_k, 5)
    effective_alpha = self.alpha if alpha is None else alpha
    effective_threshold = self.ooo_threshold if threshold is None else threshold

    candidates = await graph_store.get_entities()
    if not candidates:
        return None, None, False

    # 1. Bi-Encoder retrieval
    t_n = f"[{mention.label}] {mention.textual_envelope}"
    raw_t_n_emb = await self.embedding_model.aget_text_embedding_batch([t_n])
    t_n_emb = as_tensor(raw_t_n_emb)[0]
    t_n_emb = torch.nn.functional.normalize(t_n_emb, p=2, dim=0)

    await self._populate_candidate_cache(candidates)
    g_embs = await self._candidate_embeddings(candidates)
    g_embs = torch.nn.functional.normalize(g_embs, p=2, dim=1)

    scores = torch.matmul(g_embs, t_n_emb)
    top_k_indices = torch.topk(scores, min(effective_top_k, len(candidates))).indices

    top_candidates = [candidates[i] for i in top_k_indices]
    top_scores = scores[top_k_indices].tolist()

    self.event_emitter.emit(
        EntityLinkingCandidatesRetrieved(
            mention_id=mention.id,
            mention_name=mention.name,
            candidate_count=len(top_candidates),
            candidates=[
                {"id": c.id, "name": c.name, "score": float(s)}
                for c, s in zip(top_candidates, top_scores)
            ],
        )
    )

    # 2. In-context Jev Choice options formulation
    options: dict[str, str] = {}
    key_to_candidate: dict[str, L2Entity] = {}
    for c in top_candidates:
        key = c.name
        if key in options:
            key = f"{c.name} ({c.id})"
        options[key] = c.description or f"Entity [{c.label}]"
        key_to_candidate[key] = c

    options["OUT_OF_ONTOLOGY"] = "Novel entity not represented in candidates"

    # 3. Jev Choice evaluation
    state = f"Mention: {mention.name}\nContext:\n{t_n}"
    question = "Which entity best matches this mention?"
    decision = await self.decision_engine.evaluate_choice(
        state=state,
        question=question,
        options=options,
        alpha=effective_alpha,
    )

    conformal_set = decision.prediction_set
    if conformal_set is None:
        conformal_set = [str(decision.selected_option)] if decision.selected_option is not None else []

    # If conformal set contains multiple candidates or is empty (uncertain), mark ambiguous
    if len(conformal_set) > 1 or len(conformal_set) == 0:
        logger.debug(
            "JevEntityLinker: ambiguous conformal set %s for mention %s",
            conformal_set,
            mention.name,
        )
        return None, decision, True

    selected = conformal_set[0]

    # Case: Confidently novel Out-of-Ontology
    if selected == "OUT_OF_ONTOLOGY":
        logger.debug("JevEntityLinker: Out-of-Ontology declared for %s", mention.name)
        self.event_emitter.emit(
            EntityLinkingReranked(
                mention_id=mention.id,
                mention_name=mention.name,
                candidate_id="OUT_OF_ONTOLOGY",
                candidate_name="OUT_OF_ONTOLOGY",
                score=decision.empirical_accuracy,
                accepted=False,
                threshold=effective_threshold,
            )
        )
        return None, decision, False

    # Case: Confidently matched single canonical entity
    matched = key_to_candidate.get(selected)
    if matched is not None:
        logger.debug(
            "JevEntityLinker: linked %s -> %s (Acc: %s)",
            mention.name,
            matched.name,
            decision.empirical_accuracy,
        )
        self.event_emitter.emit(
            EntityLinkingReranked(
                mention_id=mention.id,
                mention_name=mention.name,
                candidate_id=matched.id,
                candidate_name=matched.name,
                score=decision.empirical_accuracy,
                accepted=True,
                threshold=effective_threshold,
            )
        )
        return matched, decision, False

    return None, decision, True

CascadingEntityLinker

Bases: EntityLinker

Cascading entity linker combining System 1 triage with System 2 verification.

Routes mentions first to a primary linker (typically :class:JevEntityLinker). If the primary decision is ambiguous (e.g. conformal prediction set contains multiple candidates or is uncertain), the mention cascades to a fallback linker (typically :class:DenseEntityLinker using cross-encoder reranking).

Parameters

primary : EntityLinker Primary fast triage linker (typically :class:JevEntityLinker). fallback : EntityLinker Secondary fallback linker (typically :class:DenseEntityLinker). audit_rate : float, default 0.0 Stochastic rate at which mentions bypass the primary linker and run directly through the fallback linker for calibration auditing.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/jev_entity_linker.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
class CascadingEntityLinker(EntityLinker):
    """Cascading entity linker combining System 1 triage with System 2 verification.

    Routes mentions first to a primary linker (typically :class:`JevEntityLinker`).
    If the primary decision is ambiguous (e.g. conformal prediction set contains
    multiple candidates or is uncertain), the mention cascades to a fallback
    linker (typically :class:`DenseEntityLinker` using cross-encoder reranking).

    Parameters
    ----------
    primary : EntityLinker
        Primary fast triage linker (typically :class:`JevEntityLinker`).
    fallback : EntityLinker
        Secondary fallback linker (typically :class:`DenseEntityLinker`).
    audit_rate : float, default 0.0
        Stochastic rate at which mentions bypass the primary linker and run
        directly through the fallback linker for calibration auditing.
    """

    def __init__(
        self,
        primary: EntityLinker,
        fallback: EntityLinker,
        audit_rate: float = 0.0,
    ) -> None:
        self.primary = primary
        self.fallback = fallback
        self.audit_rate = audit_rate

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic cascading entity linker configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing audit rate and fingerprints of primary and fallback linkers.
        """
        from episteme_pipeline.runs.fingerprints import fingerprint_method

        return {
            "class": self.__class__.__name__,
            "audit_rate": self.audit_rate,
            "primary": (
                self.primary.fingerprint()
                if hasattr(self.primary, "fingerprint") and callable(self.primary.fingerprint)
                else fingerprint_method(self.primary)
            ),
            "fallback": (
                self.fallback.fingerprint()
                if hasattr(self.fallback, "fingerprint") and callable(self.fallback.fingerprint)
                else fingerprint_method(self.fallback)
            ),
        }

    async def link(
        self,
        mention: L2Entity,
        graph_store: GraphReader,
        *,
        top_k: int | None = None,
        threshold: float | None = None,
    ) -> L2Entity | None:
        """Link mention via cascading triage with fallback.

        Parameters
        ----------
        mention : L2Entity
            The extracted entity mention.
        graph_store : GraphReader
            Active graph store.
        top_k : int or None, default None
            Optional override for candidate retrieval count.
        threshold : float or None, default None
            Optional override for confidence threshold.

        Returns
        -------
        L2Entity or None
            The matched canonical entity, or None to mint a novel entity.
        """
        if self.audit_rate > 0.0 and random.random() < self.audit_rate:
            logger.debug("CascadingEntityLinker: stochastic audit triggered for %s", mention.name)
            return await self.fallback.link(mention, graph_store, top_k=top_k, threshold=threshold)

        if isinstance(self.primary, JevEntityLinker):
            matched, _decision, is_ambiguous = await self.primary.link_with_decision(
                mention, graph_store, top_k=top_k, threshold=threshold
            )
            if not is_ambiguous:
                return matched
            logger.debug(
                "CascadingEntityLinker: primary returned ambiguous decision for %s; escalating to fallback",
                mention.name,
            )
        else:
            matched = await self.primary.link(mention, graph_store, top_k=top_k, threshold=threshold)
            if matched is not None:
                return matched

        return await self.fallback.link(mention, graph_store, top_k=top_k, threshold=threshold)

fingerprint()

Return deterministic cascading entity linker configuration.

Returns

dict of str to Any Dictionary containing audit rate and fingerprints of primary and fallback linkers.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/jev_entity_linker.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic cascading entity linker configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing audit rate and fingerprints of primary and fallback linkers.
    """
    from episteme_pipeline.runs.fingerprints import fingerprint_method

    return {
        "class": self.__class__.__name__,
        "audit_rate": self.audit_rate,
        "primary": (
            self.primary.fingerprint()
            if hasattr(self.primary, "fingerprint") and callable(self.primary.fingerprint)
            else fingerprint_method(self.primary)
        ),
        "fallback": (
            self.fallback.fingerprint()
            if hasattr(self.fallback, "fingerprint") and callable(self.fallback.fingerprint)
            else fingerprint_method(self.fallback)
        ),
    }

Link mention via cascading triage with fallback.

mention : L2Entity The extracted entity mention. graph_store : GraphReader Active graph store. top_k : int or None, default None Optional override for candidate retrieval count. threshold : float or None, default None Optional override for confidence threshold.

L2Entity or None The matched canonical entity, or None to mint a novel entity.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/jev_entity_linker.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
async def link(
    self,
    mention: L2Entity,
    graph_store: GraphReader,
    *,
    top_k: int | None = None,
    threshold: float | None = None,
) -> L2Entity | None:
    """Link mention via cascading triage with fallback.

    Parameters
    ----------
    mention : L2Entity
        The extracted entity mention.
    graph_store : GraphReader
        Active graph store.
    top_k : int or None, default None
        Optional override for candidate retrieval count.
    threshold : float or None, default None
        Optional override for confidence threshold.

    Returns
    -------
    L2Entity or None
        The matched canonical entity, or None to mint a novel entity.
    """
    if self.audit_rate > 0.0 and random.random() < self.audit_rate:
        logger.debug("CascadingEntityLinker: stochastic audit triggered for %s", mention.name)
        return await self.fallback.link(mention, graph_store, top_k=top_k, threshold=threshold)

    if isinstance(self.primary, JevEntityLinker):
        matched, _decision, is_ambiguous = await self.primary.link_with_decision(
            mention, graph_store, top_k=top_k, threshold=threshold
        )
        if not is_ambiguous:
            return matched
        logger.debug(
            "CascadingEntityLinker: primary returned ambiguous decision for %s; escalating to fallback",
            mention.name,
        )
    else:
        matched = await self.primary.link(mention, graph_store, top_k=top_k, threshold=threshold)
        if matched is not None:
            return matched

    return await self.fallback.link(mention, graph_store, top_k=top_k, threshold=threshold)

LLMNERExtractor

Bases: NERExtractor

Default NERExtractor using LlamaIndex LLM structured prediction.

Accepts any LlamaIndex BaseLLM (LiteLLM, OpenAI, Ollama, etc.).

Parameters

llm : Any Underlying LLM instance. prompts : StructuredPromptBundle or None, default None Prompt bundle for direct, reasoning, format, and gleaning templates. max_gleanings : int, default 0 Maximum extraction iterations if no dynamic stopping oracle is supplied. mention_context_injector : Any, default None Textual context injector for mentions. strategy : Any, default "direct_constrained" Decoding strategy. stopping_oracle : GleaningStoppingOracle or None, default None Stopping oracle evaluating whether additional passes are warranted.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/ner_extractor.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
class LLMNERExtractor(NERExtractor):
    """Default NERExtractor using LlamaIndex LLM structured prediction.

    Accepts any LlamaIndex BaseLLM (LiteLLM, OpenAI, Ollama, etc.).

    Parameters
    ----------
    llm : Any
        Underlying LLM instance.
    prompts : StructuredPromptBundle or None, default None
        Prompt bundle for direct, reasoning, format, and gleaning templates.
    max_gleanings : int, default 0
        Maximum extraction iterations if no dynamic stopping oracle is supplied.
    mention_context_injector : Any, default None
        Textual context injector for mentions.
    strategy : Any, default "direct_constrained"
        Decoding strategy.
    stopping_oracle : GleaningStoppingOracle or None, default None
        Stopping oracle evaluating whether additional passes are warranted.
    """

    def __init__(
        self, 
        llm: Any, 
        prompts: StructuredPromptBundle | None = None,
        max_gleanings: int = 0, 
        mention_context_injector: Any = None,
        strategy: Any = "direct_constrained",
        stopping_oracle: GleaningStoppingOracle | None = None,
    ) -> None:
        self.llm = ensure_structured_llm(llm)
        self.max_gleanings = max_gleanings
        self.mention_context_injector = mention_context_injector or DefaultMentionContextInjector()
        self.prompts = prompts or DEFAULT_NER_PROMPTS
        self.strategy = strategy
        self.stopping_oracle = stopping_oracle or FixedPassGleaningOracle(max_passes=max_gleanings)

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic NER extractor configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing class identifier, max gleanings, strategy,
            and fingerprints of stopping oracle and language model.
        """
        from episteme_pipeline.runs.fingerprints import fingerprint_method

        oracle_fp = (
            self.stopping_oracle.fingerprint()
            if hasattr(self.stopping_oracle, "fingerprint") and callable(self.stopping_oracle.fingerprint)
            else fingerprint_method(self.stopping_oracle)
        )
        return {
            "class": self.__class__.__name__,
            "max_gleanings": self.max_gleanings,
            "strategy": str(getattr(self.strategy, "value", self.strategy)),
            "llm": fingerprint_method(self.llm),
            "stopping_oracle": oracle_fp,
        }

    @classmethod
    def from_config(
        cls,
        llm: Any,
        config: Any,
        decision_engine: DecisionEngine | None = None,
        mention_context_injector: Any = None,
    ) -> LLMNERExtractor:
        """Construct LLMNERExtractor with dependencies wired from Phase2Config.

        Parameters
        ----------
        llm : Any
            LlamaIndex BaseLLM instance.
        config : Phase2Config
            Phase 2 configuration.
        decision_engine : DecisionEngine or None, default None
            Optional decision engine for stopping oracle.
        mention_context_injector : Any, default None
            Optional custom mention context injector.

        Returns
        -------
        LLMNERExtractor
            Configured extractor instance.
        """
        from episteme_pipeline.decision.gleaning import JevGleaningGate

        stopping_oracle = JevGleaningGate.create(
            decision_engine=decision_engine,
            config=config.gleaning,
            prompts=config.ner_prompts,
        )

        return cls(
            llm=llm,
            prompts=config.ner_prompts,
            max_gleanings=config.gleaning.max_passes,
            mention_context_injector=mention_context_injector,
            strategy=config.ner_decoding_strategy,
            stopping_oracle=stopping_oracle,
        )

    async def extract(
        self,
        chunk_id: str,
        chunk_text: str,
        schema: SchemaConfig,
        memory: Any | None = None,
        anchor: Any | None = None,
    ) -> tuple[list[L2Entity], list[L2Triple], dict | None, bool, str | None]:
        global_structural_anchor_str = anchor.to_prompt_context() if anchor and hasattr(anchor, "to_prompt_context") else ""
        working_memory_str = memory.to_prompt_context() if memory and hasattr(memory, "to_prompt_context") else ""

        all_raw_entities = []
        all_raw_triples = []
        memory_update: dict | None = None
        boundary_detected = False
        transitional_summary: str | None = None

        try:
            raw: NERExtractionOutput = await self.llm.predict_structured(
                NERExtractionOutput,
                self.prompts,
                strategy=self.strategy,
                global_structural_anchor=global_structural_anchor_str,
                working_memory_context=working_memory_str,
                entity_types=schema.node_types_str(),
                relation_types=schema.relation_types_str(),
                chunk_text=chunk_text,
            )
            raw = raw.validate_references()
            all_raw_entities.extend(raw.entities)
            all_raw_triples.extend(raw.triples)
            if raw.working_memory:
                memory_update = raw.working_memory.state_delta
                boundary_detected = raw.working_memory.boundary_detected
                transitional_summary = raw.working_memory.transitional_summary

            # Unified gleanings loop via stopping oracle
            gleaning_prompt = self.prompts.gleaning_template or NER_GLEANING_PROMPT
            pass_count = 0
            while True:
                should_continue, _ = await self.stopping_oracle.should_glean(
                    chunk_text=chunk_text,
                    current_extractions=all_raw_entities,
                    pass_count=pass_count,
                )
                if not should_continue:
                    break
                pass_count += 1
                prior_text = ", ".join([e.name for e in all_raw_entities])
                raw_glean: NERExtractionOutput = await self.llm.predict_structured(
                    NERExtractionOutput,
                    gleaning_prompt,
                    chunk_text=chunk_text,
                    prior_extractions=prior_text,
                )
                raw_glean = raw_glean.validate_references()
                if not raw_glean.entities and not raw_glean.triples:
                    break  # model found nothing new

                all_raw_entities.extend(raw_glean.entities)
                all_raw_triples.extend(raw_glean.triples)

        except Exception as exc:
            logger.warning(
                "NER extraction failed for chunk %s: %s", chunk_id, exc
            )
            return [], [], None, False, None

        # Validate labels against schema (drop unknown types silently)
        valid_node_types = set(schema.node_types)
        valid_rel_types = set(schema.relation_types)

        valid_entities = [
            e for e in all_raw_entities if e.label in valid_node_types
        ]
        if len(valid_entities) < len(all_raw_entities):
            logger.debug(
                "Dropped %d entities with unknown labels for chunk %s",
                len(all_raw_entities) - len(valid_entities),
                chunk_id,
            )

        # local_id -> stable graph ID
        id_map: dict[str, str] = {}
        entities: list[L2Entity] = []

        for ext in valid_entities:
            stable_id = _stable_entity_id(ext.label, ext.name)
            id_map[ext.id] = stable_id

            # Topologically inject the textual envelope bounds
            textual_envelope = self.mention_context_injector.inject(
                chunk_text=chunk_text, 
                mention_name=ext.name, 
                mention_quote=ext.mention_quote, 
                chunk_id=chunk_id
            )

            entities.append(
                L2Entity(
                    id=stable_id,
                    label=ext.label,
                    name=ext.name,
                    description=ext.mention_quote if ext.mention_quote != ext.name else None,
                    textual_envelope=textual_envelope,
                    confidence=ext.confidence,
                    source_chunk_ids=[chunk_id],
                )
            )

        triples: list[L2Triple] = []
        for t in all_raw_triples:
            if t.predicate not in valid_rel_types:
                continue
            subj_id = id_map.get(t.subject_id)
            obj_id = id_map.get(t.object_id)
            if subj_id is None or obj_id is None:
                continue
            triples.append(
                L2Triple(
                    subject_id=subj_id,
                    predicate=t.predicate,
                    object_id=obj_id,
                    confidence=t.confidence,
                    scope="local",
                    source_chunk_id=chunk_id,
                )
            )

        return entities, triples, memory_update, boundary_detected, transitional_summary

fingerprint()

Return deterministic NER extractor configuration.

Returns

dict of str to Any Dictionary containing class identifier, max gleanings, strategy, and fingerprints of stopping oracle and language model.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/ner_extractor.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic NER extractor configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing class identifier, max gleanings, strategy,
        and fingerprints of stopping oracle and language model.
    """
    from episteme_pipeline.runs.fingerprints import fingerprint_method

    oracle_fp = (
        self.stopping_oracle.fingerprint()
        if hasattr(self.stopping_oracle, "fingerprint") and callable(self.stopping_oracle.fingerprint)
        else fingerprint_method(self.stopping_oracle)
    )
    return {
        "class": self.__class__.__name__,
        "max_gleanings": self.max_gleanings,
        "strategy": str(getattr(self.strategy, "value", self.strategy)),
        "llm": fingerprint_method(self.llm),
        "stopping_oracle": oracle_fp,
    }

from_config(llm, config, decision_engine=None, mention_context_injector=None) classmethod

Construct LLMNERExtractor with dependencies wired from Phase2Config.

Parameters

llm : Any LlamaIndex BaseLLM instance. config : Phase2Config Phase 2 configuration. decision_engine : DecisionEngine or None, default None Optional decision engine for stopping oracle. mention_context_injector : Any, default None Optional custom mention context injector.

Returns

LLMNERExtractor Configured extractor instance.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase2_entity_discovery/ner_extractor.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
@classmethod
def from_config(
    cls,
    llm: Any,
    config: Any,
    decision_engine: DecisionEngine | None = None,
    mention_context_injector: Any = None,
) -> LLMNERExtractor:
    """Construct LLMNERExtractor with dependencies wired from Phase2Config.

    Parameters
    ----------
    llm : Any
        LlamaIndex BaseLLM instance.
    config : Phase2Config
        Phase 2 configuration.
    decision_engine : DecisionEngine or None, default None
        Optional decision engine for stopping oracle.
    mention_context_injector : Any, default None
        Optional custom mention context injector.

    Returns
    -------
    LLMNERExtractor
        Configured extractor instance.
    """
    from episteme_pipeline.decision.gleaning import JevGleaningGate

    stopping_oracle = JevGleaningGate.create(
        decision_engine=decision_engine,
        config=config.gleaning,
        prompts=config.ner_prompts,
    )

    return cls(
        llm=llm,
        prompts=config.ner_prompts,
        max_gleanings=config.gleaning.max_passes,
        mention_context_injector=mention_context_injector,
        strategy=config.ner_decoding_strategy,
        stopping_oracle=stopping_oracle,
    )

Rerankers & Global Relation Extractors (Phase 3)

DenseRetrievalGlobalRelationExtractor

Bases: GlobalRelationExtractor

SOTA GlobalRelationExtractor leveraging dense embeddings for candidate generation and a cross-encoder for relational reranking prior to LLM extraction.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/dense_retrieval_extractor.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
class DenseRetrievalGlobalRelationExtractor(GlobalRelationExtractor):
    """
    SOTA GlobalRelationExtractor leveraging dense embeddings for candidate 
    generation and a cross-encoder for relational reranking prior to LLM extraction.
    """

    def __init__(
        self, 
        llm, 
        embedding_model: EmbeddingModel, 
        reranker: RelationReranker,
        config: Phase3Config,
        envelope_overflow_handler: EnvelopeOverflowHandler | None = None,
        # Kept for backward compatibility
        trace_sink: TraceSink | None = None,
        decision_engine: DecisionEngine | None = None,
    ) -> None:
        self.llm = ensure_structured_llm(llm)
        self.embedding_model = embedding_model
        self.reranker = reranker
        self.config = config
        self.envelope_overflow_handler = envelope_overflow_handler
        self.trace_sink = trace_sink or NoOpTraceSink()
        self.decision_engine = decision_engine

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic dense retrieval global relation extractor configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing class identifier and fingerprints of injected
            reranker, decision engine, embedding model, and language model.
        """
        from episteme_pipeline.runs.fingerprints import fingerprint_method

        reranker_fp = (
            self.reranker.fingerprint()
            if hasattr(self.reranker, "fingerprint") and callable(self.reranker.fingerprint)
            else fingerprint_method(self.reranker)
        )
        de_fp = (
            self.decision_engine.fingerprint()
            if self.decision_engine and hasattr(self.decision_engine, "fingerprint") and callable(self.decision_engine.fingerprint)
            else fingerprint_method(self.decision_engine) if self.decision_engine else None
        )
        return {
            "class": self.__class__.__name__,
            "reranker": reranker_fp,
            "decision_engine": de_fp,
            "embedding_model": fingerprint_method(self.embedding_model),
            "llm": fingerprint_method(self.llm),
        }

    @property
    def event_emitter(self) -> EventEmitter:
        from episteme_pipeline.events.context import get_event_emitter
        return get_event_emitter()

    async def get_structural_neighborhood(
        self,
        entity: L2Entity,
        graph_store: GraphReader,
        depth: int = 2,
    ) -> SubGraph:
        return await graph_store.get_neighborhood(entity.id, depth=depth)

    async def extract(
        self,
        entities: list[L2Entity],
        graph_store: GraphReader,
        schema: SchemaConfig,
    ) -> list[L2Triple]:
        if len(entities) < 2:
            return []

        # Emit event for entity processing
        for entity in entities:
            self.event_emitter.emit(EntityProcessed(
                entity_id=entity.id,
                entity_name=entity.name,
                entity_type=entity.label,
                run_id=None,
                phase="phase3_dense"
            ))

        # Optionally trace dense candidate generation
        with self.trace_sink.span(
            name="phase3.dense.candidates",
            input={
                "entities": [_entity_summary(e) for e in entities],
                "threshold": self.config.dense_similarity_threshold,
            },
            enabled=self.config.trace_dense_retrieval,
        ) as span:
            candidates = await self._generate_dense_candidates(entities)
            span.update(
                output={
                    "candidate_count": len(candidates),
                    "candidates": [_candidate_summary(c) for c in candidates[:10]],
                }
            )
        logger.info(
            "Phase 3 (Dense): %d entities → %d global candidate pairs",
            len(entities),
            len(candidates),
        )

        progress_task = f"Phase 3: {len(candidates)} global pairs"
        self.event_emitter.emit(ProgressStarted(task_name=progress_task, total_items=len(candidates), description="Global Relations"))

        sem = asyncio.Semaphore(50)
        async def _extract_with_sem(candidate: _DenseCandidate) -> L2Triple | None:
            async with sem:
                res = await self._extract_pair(candidate, graph_store, schema)
                self.event_emitter.emit(ProgressAdvanced(task_name=progress_task, advance=1))
                return res

        tasks = [
            _extract_with_sem(candidate) for candidate in candidates
        ]
        results = await asyncio.gather(*tasks, return_exceptions=True)
        self.event_emitter.emit(ProgressCompleted(task_name=progress_task))

        triples: list[L2Triple] = []
        for candidate, result in zip(candidates, results):
            if isinstance(result, Exception):
                logger.error(
                    "Phase 3 pair (%s, %s) failed: %s",
                    candidate.entity_a.id,
                    candidate.entity_b.id,
                    result,
                )
                continue
            if result is not None:
                triples.append(result)

        logger.info(
            "Phase 3 (Dense): extracted %d global triples",
            len(triples)
        )
        return triples

    async def candidate_pairs(
        self, entities: list[L2Entity]
    ) -> list[CandidatePair]:
        """Generate candidate entity pairs via dense embedding retrieval.

        Parameters
        ----------
        entities : list[L2Entity]
            Entities considered for candidate pairing.

        Returns
        -------
        list[CandidatePair]
            Dense candidate pairs above configured similarity threshold.
        """
        return await self._generate_dense_candidates(entities)

    async def extract_pair(
        self,
        pair: CandidatePair,
        graph_store: GraphReader,
        schema: SchemaConfig,
    ) -> L2Triple | None:
        """Extract a relation triple for a single candidate pair.

        Parameters
        ----------
        pair : CandidatePair
            Candidate entity pair to evaluate.
        graph_store : GraphReader
            Graph reader for envelope retrieval.
        schema : SchemaConfig
            Schema configuration defining valid relation types.

        Returns
        -------
        L2Triple | None
            Extracted triple if validated, otherwise None.
        """
        return await self._extract_pair(pair, graph_store, schema)

    async def _generate_dense_candidates(
        self, entities: list[L2Entity]
    ) -> list[_DenseCandidate]:
        """Embed entities and compute dense candidate pairs.

        Parameters
        ----------
        entities
            Entities considered for global relation extraction.

        Returns
        -------
        list[_DenseCandidate]
            Candidate pairs that exceeded the dense similarity threshold, sorted
            by descending dense score and capped by configured limits.
        """
        # Sort entities deterministically to ensure order-invariant candidate generation
        entities = sorted(entities, key=lambda e: e.id)

        # Step 1: Embed textual envelopes (T_A x T_B proximity)
        # We fallback to name/description only if textual_envelope is mysteriously missing
        embed_texts = [
            ent.textual_envelope if ent.textual_envelope else f"{ent.name} {ent.description or ''}".strip()
            for ent in entities
        ]

        # Note: In practice, we'd chunk these for large batches, but for
        # reasonable entity counts (<200), hitting the endpoint once is fine.
        # Ideally this should use our new EnvelopeBiEncoder, but for compatibility 
        # with the existing embedding_model signature, we pass the text.
        embeddings = await self.embedding_model.aget_text_embedding_batch(embed_texts)

        # Step 2: Compute dense cosine similarities
        #
        # For n entities, this produces (n choose 2) = ~n²/2 pairs. For n=50,
        # that's ~1250 pairs. Still manageable in memory and useful downstream.
        #
        # For scaling beyond 100-200 entities, we'd switch to FAISS/ANN search.
        entity_vectors = np.array(embeddings)
        norms = np.linalg.norm(entity_vectors, axis=1, keepdims=True)
        normalized_vectors = entity_vectors / norms

        similarity_matrix = np.dot(normalized_vectors, normalized_vectors.T)

        # Collect top-k pairs per entity, or globally if preferred
        candidates: list[_DenseCandidate] = []
        for i in range(len(entities)):
            row_scores = [(j, similarity_matrix[i, j]) for j in range(i + 1, len(entities))]
            row_scores.sort(key=lambda x: x[1], reverse=True)
            for j, score in row_scores[:self.config.max_candidates_per_entity_pair]:
                # Emit event for each candidate pair evaluation
                candidates.append(_DenseCandidate(
                    score=float(score),
                    entity_a=entities[i],
                    entity_b=entities[j],
                ))

        # Emit event for dense candidates generated
        self.event_emitter.emit(DenseCandidatesGenerated(
            candidate_count=len(candidates),
            candidates=[{
                "entity_a": candidate.entity_a.id,
                "entity_b": candidate.entity_b.id,
                "score": candidate.score
            } for candidate in candidates[:10]],  # First 10 for brevity
            entities_count=len(entities),
            run_id=None,
            phase="phase3_dense"
        ))

        # Filter candidates by dense similarity threshold
        filtered_candidates = [
            c for c in candidates if c.score >= self.config.dense_similarity_threshold
        ]

        # Apply Jev pair gating if enabled
        return await self.filter_candidate_pairs(filtered_candidates)

    async def filter_candidate_pairs(self, pairs: list[CandidatePair]) -> list[CandidatePair]:
        """Fast Cartesian pair pre-gating using Decision Engine.

        Filters candidate entity pairs using fast binary decision evaluation
        before heavy cross-encoder reranking or LLM extraction.

        Parameters
        ----------
        pairs : list of CandidatePair
            The candidate entity pairs to filter.

        Returns
        -------
        list of CandidatePair
            The filtered candidate pairs surviving gating or stochastic audit.
        """
        if not self.config.use_jev_pair_gating or not self.decision_engine:
            return pairs

        prompts = getattr(self.config, "global_relation_prompts", None)
        if prompts is not None:
            template = prompts.decision_template
        else:
            template = PAIR_GATING_DECISION_PROMPT

        if not template or not template.strip():
            raise ValueError(
                "No decision prompt configured for DenseRetrievalGlobalRelationExtractor pair gating."
            )
        template = template.strip()

        import random
        gated_pairs = []

        for pair in pairs:
            entity_a = pair.entity_a
            entity_b = pair.entity_b

            question = template.format(entity_a=entity_a.name, entity_b=entity_b.name)
            context = f"Entity A: {entity_a.description or entity_a.name}\nEntity B: {entity_b.description or entity_b.name}"

            decision = await self.decision_engine.evaluate_noul(
                state=context,
                question=question,
            )

            is_related = decision.passed
            threshold = self.config.pair_gating_threshold
            p_has_relation = decision.probability if is_related else (1.0 - decision.probability)

            if p_has_relation >= threshold or (not is_related and random.random() < self.config.pair_gating_audit_rate):
                gated_pairs.append(pair)

        return gated_pairs

    async def _extract_pair(
        self,
        candidate: _DenseCandidate,
        graph_store: GraphReader,
        schema: SchemaConfig,
    ) -> L2Triple | None:
        """Run the full rerank-and-extract pipeline on a candidate pair."""
        entity_a, entity_b = candidate.entity_a, candidate.entity_b

        async def _fetch_envelopes(depth: int) -> tuple[SubGraph, SubGraph]:
            return await asyncio.gather(
                self.get_structural_neighborhood(entity_a, graph_store, depth=depth),
                self.get_structural_neighborhood(entity_b, graph_store, depth=depth),
            )

        # 1. Fetch contextual neighborhood envelopes for both entities
        try:
            env_a, env_b = await _fetch_envelopes(self.config.subgraph_depth)
        except Exception as exc:
            logger.warning(
                "Failed to fetch envelopes for pair (%s, %s): %s",
                entity_a.name,
                entity_b.name,
                exc,
            )
            return None

        # 2. Rerank using cross-encoder
        try:
            initial_reranker_input = _reranker_input_summary(
                self.reranker,
                entity_a,
                env_a,
                entity_b,
                env_b,
            )
            initial_reranker_payload = _reranker_trace_payload(
                entity_a,
                env_a,
                entity_b,
                env_b,
            )
            with self.trace_sink.span(
                name="phase3.dense.rerank",
                input={
                    "entity_a": _entity_summary(entity_a),
                    "entity_b": _entity_summary(entity_b),
                    "env_a": _subgraph_summary(env_a),
                    "env_b": _subgraph_summary(env_b),
                    "requested_subgraph_depth": self.config.subgraph_depth,
                    "reranker_input": initial_reranker_input,
                    "reranker_payload": initial_reranker_payload,
                    "threshold": self.config.reranker_threshold,
                },
                enabled=self.config.trace_dense_retrieval,
            ) as span:
                recovery_attempts: list[dict[str, object]] = []
                retry_index = 0
                while True:
                    reranker_input = _reranker_input_summary(
                        self.reranker,
                        entity_a,
                        env_a,
                        entity_b,
                        env_b,
                    )
                    try:
                        # Align with RelationReranker protocol:
                        # (entity_a, env_a, entity_b, env_b)
                        rerank_score = await self.reranker.score_relation(
                            entity_a,
                            env_a,
                            entity_b,
                            env_b,
                        )
                        break
                    except Exception as exc:
                        if self.envelope_overflow_handler is None:
                            span.update(
                                output={
                                    "error": str(exc),
                                    "error_type": type(exc).__name__,
                                    "reranker_input": reranker_input,
                                    "recovery_attempts": recovery_attempts,
                                }
                            )
                            raise

                        try:
                            resolution = await _resolve_envelope_overflow(
                                self.envelope_overflow_handler,
                                EnvelopeOverflowContext(
                                    entity_a=entity_a,
                                    entity_b=entity_b,
                                    graph_store=graph_store,
                                    env_a=env_a,
                                    env_b=env_b,
                                    current_depth=min(env_a.depth, env_b.depth),
                                    reranker_input=reranker_input,
                                    error=exc,
                                    retry_index=retry_index,
                                    refetch_envelopes=_fetch_envelopes,
                                ),
                            )
                        except Exception as handler_exc:
                            span.update(
                                output={
                                    "error": str(handler_exc),
                                    "error_type": type(handler_exc).__name__,
                                    "reranker_input": reranker_input,
                                    "recovery_attempts": recovery_attempts,
                                }
                            )
                            raise

                        if resolution is None:
                            span.update(
                                output={
                                    "error": str(exc),
                                    "error_type": type(exc).__name__,
                                    "reranker_input": reranker_input,
                                    "recovery_attempts": recovery_attempts,
                                }
                            )
                            raise

                        recovery_attempts.append(
                            {
                                "retry_index": retry_index,
                                "error": str(exc),
                                "error_type": type(exc).__name__,
                                "strategy": resolution.strategy,
                                "metadata": resolution.metadata,
                                "reranker_input": reranker_input,
                            }
                        )
                        logger.info(
                            "Recovered Phase 3 reranker overflow for pair (%s, %s) "
                            "using %s",
                            entity_a.name,
                            entity_b.name,
                            resolution.strategy,
                        )
                        env_a, env_b = resolution.env_a, resolution.env_b
                        retry_index += 1

                span.update(
                    output={
                        "rerank_score": rerank_score,
                        "accepted": rerank_score >= self.config.reranker_threshold,
                        "reranker_input": _reranker_input_summary(
                            self.reranker,
                            entity_a,
                            env_a,
                            entity_b,
                            env_b,
                        ),
                        "recovery_attempts": recovery_attempts,
                    }
                )

            # Emit reranker score event
            self.event_emitter.emit(RerankerScoreAssigned(
                candidate_pair=(entity_a.id, entity_b.id),
                score=rerank_score,
                accepted=rerank_score >= self.config.reranker_threshold,
                threshold=self.config.reranker_threshold,
                entity_a=_entity_summary(entity_a),
                entity_b=_entity_summary(entity_b),
                reranker_input=_reranker_input_summary(
                    self.reranker,
                    entity_a,
                    env_a,
                    entity_b,
                    env_b,
                ),
                reranker_payload=(
                    _reranker_trace_payload(entity_a, env_a, entity_b, env_b)
                    if self.config.trace_dense_retrieval
                    else None
                ),
                recovery_attempts=recovery_attempts,
                run_id=None,
                phase="phase3_dense"
            ))

            # Emit rejection event if score is too low
            if rerank_score < self.config.reranker_threshold:
                self.event_emitter.emit(CandidateRejectedByThreshold(
                    candidate_pair=(entity_a.id, entity_b.id),
                    score=rerank_score,
                    threshold=self.config.reranker_threshold,
                    reason="Below reranker threshold",
                    run_id=None,
                    phase="phase3_dense"
                ))
                return None  # Skip LLM extraction if reranker says no
        except Exception as exc:
            logger.warning(
                "Phase 3 reranker failed for pair (%s, %s): %s",
                entity_a.name,
                entity_b.name,
                exc,
            )
            return None

        # 3. LLM Extraction: structured predict to extract schema-compliant edge
        try:
            envelope_text = format_envelope(env_a, env_b)
            with self.trace_sink.span(
                name="phase3.dense.llm_extract",
                input={
                    "merged_envelope": _merged_envelope_summary(env_a, env_b),
                },
                enabled=self.config.trace_dense_retrieval,
            ) as span:
                raw: GlobalRelationOutput = await self.llm.predict_structured(
                    GlobalRelationOutput,
                    self.config.global_relation_prompts,
                    strategy=self.config.global_relation_decoding_strategy,
                    entity_a_id=entity_a.id,
                    entity_a_name=entity_a.name,
                    entity_a_type=entity_a.label,
                    entity_a_context=entity_a.description or entity_a.name,
                    entity_b_id=entity_b.id,
                    entity_b_name=entity_b.name,
                    entity_b_type=entity_b.label,
                    entity_b_context=entity_b.description or entity_b.name,
                    relation_types=schema.relation_types_str(),
                    subgraph_envelope=envelope_text,
                )
                span.update(output=_global_relation_summary(raw))

            # Emit LLM decoding event
            self.event_emitter.emit(LLMRelationDecoded(
                candidate_pair=(entity_a.id, entity_b.id),
                relation=raw.relation,
                direction=raw.direction,
                confidence=raw.confidence,
                raw_response=raw.model_dump() if hasattr(raw, 'model_dump') else str(raw),
                run_id=None,
                phase="phase3_dense"
            ))
        except Exception as exc:
            logger.warning(
                "Phase 3 LLM call failed for pair (%s, %s): %s",
                entity_a.name,
                entity_b.name,
                exc,
            )
            return None

        if raw.relation is None:
            return None

        # Validate relation type against schema
        if raw.relation not in schema.relation_types:
            logger.debug(
                "Discarded unknown relation type %r for pair (%s, %s)",
                raw.relation,
                entity_a.name,
                entity_b.name,
            )
            # Emit schema validation rejection event
            self.event_emitter.emit(SchemaValidationRejectedRelation(
                candidate_pair=(entity_a.id, entity_b.id),
                relation=raw.relation,
                reason=f"Unknown relation type: {raw.relation}",
                run_id=None,
                phase="phase3_dense"
            ))
            return None

        subj_id = entity_a.id if raw.direction == "A_to_B" else entity_b.id
        obj_id = entity_b.id if raw.direction == "A_to_B" else entity_a.id

        # Since this is global extraction, chunks may differ. 
        # We fallback to 'global' if they don't share a source chunk.
        common = set(entity_a.source_chunk_ids) & set(entity_b.source_chunk_ids)
        source_chunk_id = (
            next(iter(common))
            if common
            else "global"
        )

        triple = L2Triple(
            subject_id=subj_id,
            predicate=raw.relation,
            object_id=obj_id,
            confidence=raw.confidence,
            rerank_score=rerank_score,
            scope="global",
            source_chunk_id=source_chunk_id,
        )

        # Emit triple committed event
        self.event_emitter.emit(TripleCommitted(
            subject_id=triple.subject_id,
            predicate=triple.predicate,
            object_id=triple.object_id,
            confidence=triple.confidence,
            scope=triple.scope,
            source_chunk_id=triple.source_chunk_id,
            run_id=None,
            phase="phase3_dense"
        ))

        return triple

candidate_pairs(entities) async

Generate candidate entity pairs via dense embedding retrieval.

Parameters

entities : list[L2Entity] Entities considered for candidate pairing.

Returns

list[CandidatePair] Dense candidate pairs above configured similarity threshold.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/dense_retrieval_extractor.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
async def candidate_pairs(
    self, entities: list[L2Entity]
) -> list[CandidatePair]:
    """Generate candidate entity pairs via dense embedding retrieval.

    Parameters
    ----------
    entities : list[L2Entity]
        Entities considered for candidate pairing.

    Returns
    -------
    list[CandidatePair]
        Dense candidate pairs above configured similarity threshold.
    """
    return await self._generate_dense_candidates(entities)

extract_pair(pair, graph_store, schema) async

Extract a relation triple for a single candidate pair.

Parameters

pair : CandidatePair Candidate entity pair to evaluate. graph_store : GraphReader Graph reader for envelope retrieval. schema : SchemaConfig Schema configuration defining valid relation types.

Returns

L2Triple | None Extracted triple if validated, otherwise None.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/dense_retrieval_extractor.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
async def extract_pair(
    self,
    pair: CandidatePair,
    graph_store: GraphReader,
    schema: SchemaConfig,
) -> L2Triple | None:
    """Extract a relation triple for a single candidate pair.

    Parameters
    ----------
    pair : CandidatePair
        Candidate entity pair to evaluate.
    graph_store : GraphReader
        Graph reader for envelope retrieval.
    schema : SchemaConfig
        Schema configuration defining valid relation types.

    Returns
    -------
    L2Triple | None
        Extracted triple if validated, otherwise None.
    """
    return await self._extract_pair(pair, graph_store, schema)

filter_candidate_pairs(pairs) async

Fast Cartesian pair pre-gating using Decision Engine.

Filters candidate entity pairs using fast binary decision evaluation before heavy cross-encoder reranking or LLM extraction.

Parameters

pairs : list of CandidatePair The candidate entity pairs to filter.

Returns

list of CandidatePair The filtered candidate pairs surviving gating or stochastic audit.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/dense_retrieval_extractor.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
async def filter_candidate_pairs(self, pairs: list[CandidatePair]) -> list[CandidatePair]:
    """Fast Cartesian pair pre-gating using Decision Engine.

    Filters candidate entity pairs using fast binary decision evaluation
    before heavy cross-encoder reranking or LLM extraction.

    Parameters
    ----------
    pairs : list of CandidatePair
        The candidate entity pairs to filter.

    Returns
    -------
    list of CandidatePair
        The filtered candidate pairs surviving gating or stochastic audit.
    """
    if not self.config.use_jev_pair_gating or not self.decision_engine:
        return pairs

    prompts = getattr(self.config, "global_relation_prompts", None)
    if prompts is not None:
        template = prompts.decision_template
    else:
        template = PAIR_GATING_DECISION_PROMPT

    if not template or not template.strip():
        raise ValueError(
            "No decision prompt configured for DenseRetrievalGlobalRelationExtractor pair gating."
        )
    template = template.strip()

    import random
    gated_pairs = []

    for pair in pairs:
        entity_a = pair.entity_a
        entity_b = pair.entity_b

        question = template.format(entity_a=entity_a.name, entity_b=entity_b.name)
        context = f"Entity A: {entity_a.description or entity_a.name}\nEntity B: {entity_b.description or entity_b.name}"

        decision = await self.decision_engine.evaluate_noul(
            state=context,
            question=question,
        )

        is_related = decision.passed
        threshold = self.config.pair_gating_threshold
        p_has_relation = decision.probability if is_related else (1.0 - decision.probability)

        if p_has_relation >= threshold or (not is_related and random.random() < self.config.pair_gating_audit_rate):
            gated_pairs.append(pair)

    return gated_pairs

fingerprint()

Return deterministic dense retrieval global relation extractor configuration.

Returns

dict of str to Any Dictionary containing class identifier and fingerprints of injected reranker, decision engine, embedding model, and language model.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/dense_retrieval_extractor.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic dense retrieval global relation extractor configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing class identifier and fingerprints of injected
        reranker, decision engine, embedding model, and language model.
    """
    from episteme_pipeline.runs.fingerprints import fingerprint_method

    reranker_fp = (
        self.reranker.fingerprint()
        if hasattr(self.reranker, "fingerprint") and callable(self.reranker.fingerprint)
        else fingerprint_method(self.reranker)
    )
    de_fp = (
        self.decision_engine.fingerprint()
        if self.decision_engine and hasattr(self.decision_engine, "fingerprint") and callable(self.decision_engine.fingerprint)
        else fingerprint_method(self.decision_engine) if self.decision_engine else None
    )
    return {
        "class": self.__class__.__name__,
        "reranker": reranker_fp,
        "decision_engine": de_fp,
        "embedding_model": fingerprint_method(self.embedding_model),
        "llm": fingerprint_method(self.llm),
    }

JevRelationReranker

Bases: RelationReranker

Relation reranker backed by the TypeSafe Jev Decision Engine.

Evaluates relation plausibility and returns the empirical accuracy score.

Parameters

decision_engine : DecisionEngine The calibrated decision engine instance. prompts : StructuredPromptBundle or None, default None Optional prompt bundle carrying the decision question template.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/rerankers.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
class JevRelationReranker(RelationReranker):
    """Relation reranker backed by the TypeSafe Jev Decision Engine.

    Evaluates relation plausibility and returns the empirical accuracy score.

    Parameters
    ----------
    decision_engine : DecisionEngine
        The calibrated decision engine instance.
    prompts : StructuredPromptBundle or None, default None
        Optional prompt bundle carrying the decision question template.
    """

    def __init__(
        self,
        decision_engine: DecisionEngine,
        prompts: StructuredPromptBundle | None = None,
    ) -> None:
        self.decision_engine = decision_engine
        self.prompts = prompts
        if prompts is not None:
            template = prompts.decision_template
        else:
            template = PAIR_GATING_DECISION_PROMPT

        if not template or not template.strip():
            raise ValueError("No decision prompt configured for JevRelationReranker.")
        self.decision_template = template.strip()

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic Jev relation reranker configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing class identifier, decision template, and decision engine fingerprint.
        """
        eng_fp = (
            self.decision_engine.fingerprint()
            if hasattr(self.decision_engine, "fingerprint") and callable(self.decision_engine.fingerprint)
            else {"class": self.decision_engine.__class__.__name__}
        )
        return {
            "class": self.__class__.__name__,
            "decision_template": self.decision_template,
            "decision_engine": eng_fp,
        }

    async def score_relation(
        self,
        entity_a: L2Entity,
        env_a: SubGraph,
        entity_b: L2Entity,
        env_b: SubGraph,
    ) -> float:
        # Context window guard - limit tokens to < 800 (or characters approx 3200)
        # Using a simple character truncation for envelope
        query, doc_text = build_relation_reranker_inputs(entity_a, env_a, entity_b, env_b)

        # Simple truncation to stay within budget
        if len(query) > 1600:
            query = query[:1600] + "..."
        if len(doc_text) > 1600:
            doc_text = doc_text[:1600] + "..."

        context = f"Entity A:\n{query}\n\nEntity B:\n{doc_text}"
        question = self.decision_template.format(entity_a=entity_a.name, entity_b=entity_b.name)

        decision = await self.decision_engine.evaluate_noul(
            state=context,
            question=question,
        )

        # return calibrated probability or empirical accuracy
        return decision.probability if decision.passed else (1.0 - decision.probability) * 0.1

fingerprint()

Return deterministic Jev relation reranker configuration.

Returns

dict of str to Any Dictionary containing class identifier, decision template, and decision engine fingerprint.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/rerankers.py
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic Jev relation reranker configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing class identifier, decision template, and decision engine fingerprint.
    """
    eng_fp = (
        self.decision_engine.fingerprint()
        if hasattr(self.decision_engine, "fingerprint") and callable(self.decision_engine.fingerprint)
        else {"class": self.decision_engine.__class__.__name__}
    )
    return {
        "class": self.__class__.__name__,
        "decision_template": self.decision_template,
        "decision_engine": eng_fp,
    }

CrossEncoderRelationReranker

Bases: RelationReranker

Lift a text :class:CrossEncoder into the :class:RelationReranker interface.

The two interfaces are deliberately distinct — a RelationReranker scores domain objects and may be structural (e.g. a GNN), a CrossEncoder scores text pairs. When the caller only has a text cross-encoder, this adapter makes the conversion explicit and visible at the composition root instead of relying on one concrete class happening to implement both.

Parameters

cross_encoder Any object satisfying the CrossEncoder protocol.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/rerankers.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
class CrossEncoderRelationReranker(RelationReranker):
    """Lift a text :class:`CrossEncoder` into the :class:`RelationReranker` interface.

    The two interfaces are deliberately distinct — a ``RelationReranker`` scores
    domain objects and may be structural (e.g. a GNN), a ``CrossEncoder`` scores
    text pairs. When the caller only has a text cross-encoder, this adapter
    makes the conversion explicit and visible at the composition root instead of
    relying on one concrete class happening to implement both.

    Parameters
    ----------
    cross_encoder
        Any object satisfying the ``CrossEncoder`` protocol.
    """

    def __init__(self, cross_encoder: CrossEncoder) -> None:
        if not hasattr(cross_encoder, "predict"):
            raise TypeError(
                f"{type(cross_encoder).__name__} has no .predict(pairs) method; "
                "it does not satisfy the CrossEncoder protocol."
            )
        self.cross_encoder = cross_encoder

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic cross-encoder relation reranker configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing class identifier and wrapped cross encoder fingerprint.
        """
        ce_fp = (
            self.cross_encoder.fingerprint()
            if hasattr(self.cross_encoder, "fingerprint") and callable(self.cross_encoder.fingerprint)
            else {"class": self.cross_encoder.__class__.__name__}
        )
        return {
            "class": self.__class__.__name__,
            "cross_encoder": ce_fp,
        }

    async def score_relation(
        self,
        entity_a: L2Entity,
        env_a: SubGraph,
        entity_b: L2Entity,
        env_b: SubGraph,
    ) -> float:
        query, doc_text = build_relation_reranker_inputs(entity_a, env_a, entity_b, env_b)
        return normalize_scores(self.cross_encoder.predict([(query, doc_text)]))[0]

fingerprint()

Return deterministic cross-encoder relation reranker configuration.

Returns

dict of str to Any Dictionary containing class identifier and wrapped cross encoder fingerprint.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/rerankers.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic cross-encoder relation reranker configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing class identifier and wrapped cross encoder fingerprint.
    """
    ce_fp = (
        self.cross_encoder.fingerprint()
        if hasattr(self.cross_encoder, "fingerprint") and callable(self.cross_encoder.fingerprint)
        else {"class": self.cross_encoder.__class__.__name__}
    )
    return {
        "class": self.__class__.__name__,
        "cross_encoder": ce_fp,
    }

SentenceTransformerCrossEncoderReranker

Bases: RelationReranker

Relation reranker backed by a sentence-transformers cross encoder.

The heavy sentence_transformers and torch dependencies are imported lazily so importing the pipeline package never loads a model or touches the Hugging Face cache.

Parameters

model_name Hugging Face model identifier passed to CrossEncoder when model is not provided. prompts Optional prompt mapping for reranker models that use named prompts. default_prompt_name Optional default prompt name passed to CrossEncoder. model Preconstructed cross encoder. This is primarily useful for tests or callers that want to own model loading. activation_fn Optional activation function passed to CrossEncoder.predict. When omitted, torch.nn.Sigmoid() is used. max_length Maximum input sequence length forwarded to the cross-encoder. cache_model Whether to cache the loaded model in memory for subsequent instances. When True, the model is cached using the model configuration as key. This can significantly reduce loading time when creating multiple reranker instances. device Target device for model inference (e.g., "cuda", "mps", "cpu"). trust_remote_code Whether to allow execution of custom modeling code hosted on Hugging Face. model_kwargs Keyword arguments passed down to AutoModelForSequenceClassification.from_pretrained. tokenizer_args Keyword arguments passed down to AutoTokenizer.from_pretrained. config_args Keyword arguments passed down to AutoConfig.from_pretrained.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/rerankers.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
class SentenceTransformerCrossEncoderReranker(RelationReranker):
    """Relation reranker backed by a sentence-transformers cross encoder.

    The heavy ``sentence_transformers`` and ``torch`` dependencies are imported
    lazily so importing the pipeline package never loads a model or touches the
    Hugging Face cache.

    Parameters
    ----------
    model_name
        Hugging Face model identifier passed to ``CrossEncoder`` when ``model``
        is not provided.
    prompts
        Optional prompt mapping for reranker models that use named prompts.
    default_prompt_name
        Optional default prompt name passed to ``CrossEncoder``.
    model
        Preconstructed cross encoder. This is primarily useful for tests or
        callers that want to own model loading.
    activation_fn
        Optional activation function passed to ``CrossEncoder.predict``. When
        omitted, ``torch.nn.Sigmoid()`` is used.
    max_length
        Maximum input sequence length forwarded to the cross-encoder.
    cache_model
        Whether to cache the loaded model in memory for subsequent instances.
        When True, the model is cached using the model configuration as key.
        This can significantly reduce loading time when creating multiple
        reranker instances.
    device
        Target device for model inference (e.g., ``"cuda"``, ``"mps"``, ``"cpu"``).
    trust_remote_code
        Whether to allow execution of custom modeling code hosted on Hugging Face.
    model_kwargs
        Keyword arguments passed down to ``AutoModelForSequenceClassification.from_pretrained``.
    tokenizer_args
        Keyword arguments passed down to ``AutoTokenizer.from_pretrained``.
    config_args
        Keyword arguments passed down to ``AutoConfig.from_pretrained``.
    """

    def __init__(
        self,
        model_name: str = "Qwen/Qwen3-Reranker-0.6B",
        *,
        prompts: dict[str, str] | None = None,
        default_prompt_name: str | None = "classification",
        model: Any | None = None,
        activation_fn: Callable[..., Any] | None = None,
        max_length: int | None = 1024,
        cache_model: bool = False,
        device: str | None = None,
        trust_remote_code: bool = False,
        model_kwargs: dict[str, Any] | None = None,
        tokenizer_args: dict[str, Any] | None = None,
        config_args: dict[str, Any] | None = None,
    ) -> None:
        self.prompt_name = default_prompt_name
        self.activation_fn = activation_fn
        self.max_length = max_length
        self.device = device
        self.trust_remote_code = trust_remote_code
        self.model_kwargs = model_kwargs
        self.tokenizer_args = tokenizer_args
        self.config_args = config_args
        effective_prompts = prompts or _qwen_reranker_prompts()
        cache_key = _model_cache_key(
            model_name=model_name,
            prompts=effective_prompts,
            default_prompt_name=default_prompt_name,
            max_length=max_length,
            device=device,
            trust_remote_code=trust_remote_code,
            model_kwargs=model_kwargs,
            tokenizer_args=tokenizer_args,
            config_args=config_args,
        )
        if model is not None:
            self.model = model
        elif cache_model and cache_key in _model_cache:
            self.model = _model_cache[cache_key]
        else:
            self.model = self._load_model(
                model_name=model_name,
                prompts=effective_prompts,
                max_length=max_length,
                device=device,
                trust_remote_code=trust_remote_code,
                automodel_args=model_kwargs,
                tokenizer_args=tokenizer_args,
                config_args=config_args,
            )
            if cache_model:
                _model_cache[cache_key] = self.model
        self.model_name = model_name

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic sentence transformer reranker configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing model name, prompt name, sequence length, and model arguments.
        """
        return {
            "class": self.__class__.__name__,
            "model_name": self.model_name,
            "prompt_name": self.prompt_name,
            "max_length": self.max_length,
            "device": str(self.device) if self.device else None,
            "trust_remote_code": self.trust_remote_code,
            "model_kwargs": self.model_kwargs,
        }

    async def score_relation(
        self,
        entity_a: L2Entity,
        env_a: SubGraph,
        entity_b: L2Entity,
        env_b: SubGraph,
    ) -> float:
        """Score whether two entities likely participate in a relation.

        Parameters
        ----------
        entity_a
            First entity, represented as the query side of the pair.
        env_a
            Context envelope for ``entity_a``.
        entity_b
            Second entity, represented as the document side of the pair.
        env_b
            Context envelope for ``entity_b``.

        Returns
        -------
        float
            Cross-encoder score normalized by the configured activation
            function.
        """
        query, doc_text = build_relation_reranker_inputs(
            entity_a,
            env_a,
            entity_b,
            env_b,
        )

        score = self.model.predict(
            [(query, doc_text)],
            activation_fn=self.activation_fn or self._default_activation_fn(),
            prompt_name=self.prompt_name,
        )[0]

        return float(score)

    def predict(
        self,
        pairs: list[tuple[str, str]],
        batch_size: int = 32,
        show_progress_bar: bool | None = None,
        activation_fn: Callable[..., Any] | None = None,
        apply_softmax: bool | None = None,
        convert_to_numpy: bool = True,
        convert_to_tensor: bool = False,
    ) -> Any:
        """Predict cross-encoder similarity scores for a list of text pairs.

        Implements the ``CrossEncoder`` protocol signature directly.
        """
        return self.model.predict(
            pairs,
            batch_size=batch_size,
            show_progress_bar=show_progress_bar,
            activation_fn=activation_fn or self.activation_fn or self._default_activation_fn(),
            apply_softmax=apply_softmax,
            convert_to_numpy=convert_to_numpy,
            convert_to_tensor=convert_to_tensor,
            prompt_name=self.prompt_name,
        )


    def describe_relation_input(
        self,
        entity_a: L2Entity,
        env_a: SubGraph,
        entity_b: L2Entity,
        env_b: SubGraph,
    ) -> dict[str, object]:
        """Summarize the current reranker input without executing inference.

        Parameters
        ----------
        entity_a
            Query-side entity.
        env_a
            Query-side envelope.
        entity_b
            Document-side entity.
        env_b
            Document-side envelope.

        Returns
        -------
        dict[str, object]
            Size metadata for the reranker query/document pair.
        """
        query, doc_text = build_relation_reranker_inputs(
            entity_a,
            env_a,
            entity_b,
            env_b,
        )
        return summarize_reranker_text_pair(
            query,
            doc_text,
            max_length=self.max_length,
        )

    @staticmethod
    def _load_model(
        *,
        model_name: str,
        prompts: dict[str, str],
        max_length: int | None,
        device: str | None = None,
        trust_remote_code: bool = False,
        automodel_args: dict[str, Any] | None = None,
        tokenizer_args: dict[str, Any] | None = None,
        config_args: dict[str, Any] | None = None,
    ) -> Any:
        """Load a sentence-transformers cross encoder.

        Parameters
        ----------
        model_name
            Hugging Face model identifier.
        prompts
            Prompt mapping passed to the model constructor.
        max_length
            Maximum input sequence length forwarded to the cross-encoder.
        device
            Target device for model inference (e.g., ``"cuda"``, ``"mps"``, ``"cpu"``).
        trust_remote_code
            Whether to allow custom modeling code execution from Hugging Face.
        automodel_args
            Keyword arguments passed down to ``AutoModelForSequenceClassification.from_pretrained``.
        tokenizer_args
            Keyword arguments passed down to ``AutoTokenizer.from_pretrained``.
        config_args
            Keyword arguments passed down to ``AutoConfig.from_pretrained``.

        Returns
        -------
        Any
            Initialized ``sentence_transformers.CrossEncoder`` instance.
        """
        from sentence_transformers import CrossEncoder

        kwargs: dict[str, Any] = {
            "prompts": prompts,
            "max_length": max_length,
            "trust_remote_code": trust_remote_code,
        }
        if device is not None:
            kwargs["device"] = device
        if automodel_args is not None:
            kwargs["automodel_args"] = automodel_args
        if tokenizer_args is not None:
            kwargs["tokenizer_args"] = tokenizer_args
        if config_args is not None:
            kwargs["config_args"] = config_args

        return CrossEncoder(
            model_name,
            **kwargs,
        )

    @staticmethod
    def _default_activation_fn() -> Any:
        """Return the default sigmoid activation for cross-encoder scores.

        Returns
        -------
        Any
            ``torch.nn.Sigmoid`` instance.
        """
        import torch

        return torch.nn.Sigmoid()

describe_relation_input(entity_a, env_a, entity_b, env_b)

Summarize the current reranker input without executing inference.

Parameters

entity_a Query-side entity. env_a Query-side envelope. entity_b Document-side entity. env_b Document-side envelope.

Returns

dict[str, object] Size metadata for the reranker query/document pair.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/rerankers.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def describe_relation_input(
    self,
    entity_a: L2Entity,
    env_a: SubGraph,
    entity_b: L2Entity,
    env_b: SubGraph,
) -> dict[str, object]:
    """Summarize the current reranker input without executing inference.

    Parameters
    ----------
    entity_a
        Query-side entity.
    env_a
        Query-side envelope.
    entity_b
        Document-side entity.
    env_b
        Document-side envelope.

    Returns
    -------
    dict[str, object]
        Size metadata for the reranker query/document pair.
    """
    query, doc_text = build_relation_reranker_inputs(
        entity_a,
        env_a,
        entity_b,
        env_b,
    )
    return summarize_reranker_text_pair(
        query,
        doc_text,
        max_length=self.max_length,
    )

fingerprint()

Return deterministic sentence transformer reranker configuration.

Returns

dict of str to Any Dictionary containing model name, prompt name, sequence length, and model arguments.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/rerankers.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic sentence transformer reranker configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing model name, prompt name, sequence length, and model arguments.
    """
    return {
        "class": self.__class__.__name__,
        "model_name": self.model_name,
        "prompt_name": self.prompt_name,
        "max_length": self.max_length,
        "device": str(self.device) if self.device else None,
        "trust_remote_code": self.trust_remote_code,
        "model_kwargs": self.model_kwargs,
    }

predict(pairs, batch_size=32, show_progress_bar=None, activation_fn=None, apply_softmax=None, convert_to_numpy=True, convert_to_tensor=False)

Predict cross-encoder similarity scores for a list of text pairs.

Implements the CrossEncoder protocol signature directly.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/rerankers.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def predict(
    self,
    pairs: list[tuple[str, str]],
    batch_size: int = 32,
    show_progress_bar: bool | None = None,
    activation_fn: Callable[..., Any] | None = None,
    apply_softmax: bool | None = None,
    convert_to_numpy: bool = True,
    convert_to_tensor: bool = False,
) -> Any:
    """Predict cross-encoder similarity scores for a list of text pairs.

    Implements the ``CrossEncoder`` protocol signature directly.
    """
    return self.model.predict(
        pairs,
        batch_size=batch_size,
        show_progress_bar=show_progress_bar,
        activation_fn=activation_fn or self.activation_fn or self._default_activation_fn(),
        apply_softmax=apply_softmax,
        convert_to_numpy=convert_to_numpy,
        convert_to_tensor=convert_to_tensor,
        prompt_name=self.prompt_name,
    )

score_relation(entity_a, env_a, entity_b, env_b) async

Score whether two entities likely participate in a relation.

Parameters

entity_a First entity, represented as the query side of the pair. env_a Context envelope for entity_a. entity_b Second entity, represented as the document side of the pair. env_b Context envelope for entity_b.

Returns

float Cross-encoder score normalized by the configured activation function.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase3_global_relations/rerankers.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
async def score_relation(
    self,
    entity_a: L2Entity,
    env_a: SubGraph,
    entity_b: L2Entity,
    env_b: SubGraph,
) -> float:
    """Score whether two entities likely participate in a relation.

    Parameters
    ----------
    entity_a
        First entity, represented as the query side of the pair.
    env_a
        Context envelope for ``entity_a``.
    entity_b
        Second entity, represented as the document side of the pair.
    env_b
        Context envelope for ``entity_b``.

    Returns
    -------
    float
        Cross-encoder score normalized by the configured activation
        function.
    """
    query, doc_text = build_relation_reranker_inputs(
        entity_a,
        env_a,
        entity_b,
        env_b,
    )

    score = self.model.predict(
        [(query, doc_text)],
        activation_fn=self.activation_fn or self._default_activation_fn(),
        prompt_name=self.prompt_name,
    )[0]

    return float(score)

Argument Classifiers (Phase 4)

LLMACCClassifier

Anti-contribution claim (ACC) classifier.

Bases: ACCClassifier

Default ACCClassifier using LlamaIndex LLM structured prediction. Accepts any LlamaIndex BaseLLM.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase4_argument_mining/acc_classifier.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class LLMACCClassifier(ACCClassifier):
    """
    Default ACCClassifier using LlamaIndex LLM structured prediction.
    Accepts any LlamaIndex BaseLLM.
    """

    def __init__(self, llm, prompts: Any = None, strategy: Any = "direct_constrained") -> None:
        self.llm = ensure_structured_llm(llm)
        self.prompts = prompts
        self.strategy = strategy

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic ACC classifier configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing strategy and LLM fingerprint.
        """
        from episteme_pipeline.runs.fingerprints import fingerprint_method

        return {
            "class": self.__class__.__name__,
            "strategy": str(getattr(self.strategy, "value", self.strategy)),
            "llm": fingerprint_method(self.llm),
        }

    async def classify(
        self,
        chunk_id: str,
        tagged_text: str,
        adu_ids: list[str],
        schema: SchemaConfig,
        chunk_entities: list[L2Entity] | None = None,
    ) -> tuple[list[TheoryAtom], list[TheoryRelation]]:
        chunk_entities_str = "\n".join([f"- {e.id}: {e.name} ({e.label})" for e in chunk_entities]) if chunk_entities else "None"
        try:
            raw: ACCOutput = await self.llm.predict_structured(
                ACCOutput,
                self.prompts,
                strategy=self.strategy,
                component_types=", ".join(schema.component_types),
                argument_relation_types=", ".join(schema.argument_relation_types),
                tagged_text=tagged_text,
                chunk_entities=chunk_entities_str,
            )
        except Exception as exc:
            logger.warning("ACC classification failed for chunk %s: %s", chunk_id, exc)
            return [], []

        raw = raw.validate_references()

        # Map LLM-local AC tags to stable graph IDs
        id_map: dict[str, str] = {}
        components: list[TheoryAtom] = []

        for ext in raw.components:
            if ext.component_type not in schema.component_types:
                logger.warning(
                    "Dropped unknown component type %r in chunk %s",
                    ext.component_type,
                    chunk_id,
                )
                continue
            stable_id = _stable_component_id(chunk_id, ext.id)
            id_map[ext.id] = stable_id
            components.append(
                TheoryAtom(
                    id=stable_id,
                    text=ext.text,
                    component_type=ext.component_type,
                    source_chunk_id=chunk_id,
                    confidence=ext.confidence,
                    plausibility=ext.plausibility if ext.plausibility is not None else ext.confidence,
                    entity_ids=ext.entity_ids,
                    epistemic_status=ext.epistemic_status,
                    scope_type=ext.scope_type,
                )
            )

        valid_arg_rel_types = set(schema.argument_relation_types)
        relations: list[TheoryRelation] = []
        for r in raw.relations:
            if r.relation not in valid_arg_rel_types:
                logger.warning(
                    "Dropped unknown argument relation type %r in chunk %s",
                    r.relation,
                    chunk_id,
                )
                continue
            source_id = id_map.get(r.source_id)
            target_id = id_map.get(r.target_id)
            if source_id is None or target_id is None:
                continue
            relations.append(
                TheoryRelation(
                    source_id=source_id,
                    target_id=target_id,
                    relation_type=r.relation,
                    confidence=r.confidence,
                    scope="local",
                    weight=r.weight if r.weight is not None else r.confidence,
                )
            )

        return components, relations

fingerprint()

Return deterministic ACC classifier configuration.

Returns

dict of str to Any Dictionary containing strategy and LLM fingerprint.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase4_argument_mining/acc_classifier.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic ACC classifier configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing strategy and LLM fingerprint.
    """
    from episteme_pipeline.runs.fingerprints import fingerprint_method

    return {
        "class": self.__class__.__name__,
        "strategy": str(getattr(self.strategy, "value", self.strategy)),
        "llm": fingerprint_method(self.llm),
    }

TAGARCClassifier

Anti-research claim (ARC) classifier.

Bases: ARCClassifier

Default ARCClassifier using TAG subgraph retrieval and LLM stance decoding.

This class orchestrates the classification of cross-chunk argument relations by pairing theory atoms and predicting relations via an LLM.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase4_argument_mining/arc_classifier.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
class TAGARCClassifier(ARCClassifier):
    """
    Default ARCClassifier using TAG subgraph retrieval and LLM stance decoding.

    This class orchestrates the classification of cross-chunk argument relations
    by pairing theory atoms and predicting relations via an LLM.
    """

    def __init__(
        self,
        llm: Any,
        embedding_model: Any = None,
        prompts: Any = None,
        strategy: str = "direct_constrained",
        confidence_threshold: float = 0.65,
        subgraph_depth: int = 2,
        max_candidates_per_component: int = 10,
        use_priority_rank: bool = False,
    ) -> None:
        """
        Initialize the TAGARCClassifier.

        Parameters
        ----------
        llm : Any
            The language model used for structural prediction.
        embedding_model : Any, optional
            The embedding model for computing dense representations, by default None.
        prompts : Any, optional
            The prompt template configuration, by default None.
        strategy : str, optional
            The prediction strategy, by default "direct_constrained".
        confidence_threshold : float, optional
            The minimum LLM confidence to accept a relation, by default 0.65.
        subgraph_depth : int, optional
            The depth of structural neighborhood to retrieve, by default 2.
        max_candidates_per_component : int, optional
            The max number of cross-chunk partners per component, by default 10.
        use_priority_rank : bool, optional
            If True, falls back to epistemic rank instead of embeddings, by default False.
        """
        self.llm = ensure_structured_llm(llm)
        self.embedding_model = embedding_model
        self.prompts = prompts
        self.strategy = strategy
        self.confidence_threshold = confidence_threshold
        self.subgraph_depth = subgraph_depth
        self.max_candidates_per_component = max_candidates_per_component
        self.use_priority_rank = use_priority_rank

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic TAG ARC classifier configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing thresholds, subgraph depth, strategy,
            and fingerprints of LLM and embedding model.
        """
        from episteme_pipeline.runs.fingerprints import fingerprint_method

        return {
            "class": self.__class__.__name__,
            "strategy": str(getattr(self.strategy, "value", self.strategy)),
            "confidence_threshold": self.confidence_threshold,
            "subgraph_depth": self.subgraph_depth,
            "max_candidates_per_component": self.max_candidates_per_component,
            "use_priority_rank": self.use_priority_rank,
            "llm": fingerprint_method(self.llm),
            "embedding_model": fingerprint_method(self.embedding_model),
        }

    async def classify_global(
        self,
        local_components: list[TheoryAtom],
        local_relations: list[TheoryRelation],
        graph_store: GraphReader,
        global_extractor: GlobalRelationExtractor,
        schema: SchemaConfig,
    ) -> list[TheoryRelation]:
        """
        Predict cross-chunk argument relations using the LLM.

        Parameters
        ----------
        local_components : list[TheoryAtom]
            The list of theory atoms to pair up.
        local_relations : list[TheoryRelation]
            The relations already extracted locally.
        graph_store : GraphReader
            The graph database reader to fetch subgraph neighborhoods.
        global_extractor : GlobalRelationExtractor
            The extractor used to fetch the structural context.
        schema : SchemaConfig
            The pipeline schema definitions.

        Returns
        -------
        list[TheoryRelation]
            A list of successfully predicted global relations.
        """
        candidate_pairs = await self._cross_chunk_pairs(local_components, schema)
        logger.info(
            "ARC: %d components → %d cross-chunk candidate pairs",
            len(local_components),
            len(candidate_pairs),
        )

        tasks = [
            self._classify_pair(a, b, graph_store, global_extractor, schema)
            for a, b in candidate_pairs
        ]
        results = await asyncio.gather(*tasks, return_exceptions=True)

        global_relations: list[TheoryRelation] = []
        for (a, b), result in zip(candidate_pairs, results):
            if isinstance(result, Exception):
                logger.error("ARC pair (%s, %s) failed: %s", a.id, b.id, result)
                continue
            if result is not None:
                global_relations.append(result)

        logger.info(
            "ARC: extracted %d global argument relations", len(global_relations)
        )
        return global_relations

    async def _cross_chunk_pairs(
        self, components: list[TheoryAtom], schema: SchemaConfig
    ) -> list[tuple[TheoryAtom, TheoryAtom]]:
        """
        Determine which pairs of atoms should be considered for global relations.

        Depending on configuration, this delegates to either a dense embedding
        similarity search or an epistemic priority rank.

        Parameters
        ----------
        components : list[TheoryAtom]
            The components to pair.
        schema : SchemaConfig
            The pipeline schema definitions.

        Returns
        -------
        list[tuple[TheoryAtom, TheoryAtom]]
            The selected pairs of components.
        """
        if len(components) < 2:
            return []

        if self.use_priority_rank or self.embedding_model is None:
            return self._get_pairs_by_priority(components, schema)
        return await self._get_pairs_by_embedding(components)

    def _get_pairs_by_priority(
        self, components: list[TheoryAtom], schema: SchemaConfig
    ) -> list[tuple[TheoryAtom, TheoryAtom]]:
        """
        Generate pairs based on an epistemic priority ranking of component types.

        Parameters
        ----------
        components : list[TheoryAtom]
            The components to pair.
        schema : SchemaConfig
            The schema providing the component type hierarchy.

        Returns
        -------
        list[tuple[TheoryAtom, TheoryAtom]]
            The selected pairs of components.
        """
        partner_count: dict[str, int] = defaultdict(int)
        seen: set[tuple[str, str]] = set()
        pairs: list[tuple[TheoryAtom, TheoryAtom]] = []

        priority_rank = {
            ctype: idx for idx, ctype in enumerate(schema.component_types)
        }
        sorted_components = sorted(
            components,
            key=lambda c: priority_rank.get(c.component_type, 99),
        )

        for i, a in enumerate(sorted_components):
            for b in sorted_components[i + 1 :]:
                if a.source_chunk_id == b.source_chunk_id:
                    continue
                key = (min(a.id, b.id), max(a.id, b.id))
                if key in seen:
                    continue
                if (
                    partner_count[a.id] >= self.max_candidates_per_component
                    or partner_count[b.id] >= self.max_candidates_per_component
                ):
                    continue
                seen.add(key)
                pairs.append((a, b))
                partner_count[a.id] += 1
                partner_count[b.id] += 1

        return pairs

    async def _get_pairs_by_embedding(
        self, components: list[TheoryAtom]
    ) -> list[tuple[TheoryAtom, TheoryAtom]]:
        """
        Generate pairs based on dense embedding cosine similarity.

        Parameters
        ----------
        components : list[TheoryAtom]
            The components to pair.

        Returns
        -------
        list[tuple[TheoryAtom, TheoryAtom]]
            The selected pairs of components, ordered by highest similarity.
        """
        partner_count: dict[str, int] = defaultdict(int)
        seen: set[tuple[str, str]] = set()
        pairs: list[tuple[TheoryAtom, TheoryAtom]] = []

        texts = [c.text for c in components]
        embeddings = await self.embedding_model.aget_text_embedding_batch(texts)

        emb_matrix = np.array(embeddings)
        norms = np.linalg.norm(emb_matrix, axis=1, keepdims=True)
        norms[norms == 0] = 1e-10
        emb_matrix = emb_matrix / norms

        sim_matrix = np.dot(emb_matrix, emb_matrix.T)

        num_comp = len(components)
        i_indices, j_indices = np.triu_indices(num_comp, k=1)
        similarities = sim_matrix[i_indices, j_indices]

        sorted_idx = np.argsort(similarities)[::-1]

        for idx in sorted_idx:
            i = i_indices[idx]
            j = j_indices[idx]
            a = components[i]
            b = components[j]

            if a.source_chunk_id == b.source_chunk_id:
                continue

            key = (min(a.id, b.id), max(a.id, b.id))
            if key in seen:
                continue

            if (
                partner_count[a.id] >= self.max_candidates_per_component
                or partner_count[b.id] >= self.max_candidates_per_component
            ):
                continue

            seen.add(key)
            pairs.append((a, b))
            partner_count[a.id] += 1
            partner_count[b.id] += 1

        return pairs

    async def _classify_pair(
        self,
        component_a: TheoryAtom,
        component_b: TheoryAtom,
        graph_store: GraphReader,
        global_extractor: GlobalRelationExtractor,
        schema: SchemaConfig,
    ) -> TheoryRelation | None:
        """
        Predict the argument relation between two specific theory atoms.

        This fetches the structural neighborhood for both components, merges them
        into an envelope, and prompts the LLM to decide the stance.

        Parameters
        ----------
        component_a : TheoryAtom
            The first theory atom.
        component_b : TheoryAtom
            The second theory atom.
        graph_store : GraphReader
            The graph storage client.
        global_extractor : GlobalRelationExtractor
            The extractor to retrieve structural contexts.
        schema : SchemaConfig
            The schema to validate relation types against.

        Returns
        -------
        TheoryRelation | None
            The predicted relation, or None if no valid relation was found.
        """
        entity_a = _component_as_entity(component_a)
        entity_b = _component_as_entity(component_b)

        env_a, env_b = await asyncio.gather(
            global_extractor.get_structural_neighborhood(
                entity_a, graph_store, self.subgraph_depth
            ),
            global_extractor.get_structural_neighborhood(
                entity_b, graph_store, self.subgraph_depth
            ),
        )

        envelope_text = format_envelope(env_a, env_b, include_description=False)

        try:
            raw: ARCRelationOutput = await self.llm.predict_structured(
                ARCRelationOutput,
                self.prompts,
                strategy=self.strategy,
                component_a_id=component_a.id,
                component_a_type=component_a.component_type,
                component_a_text=component_a.text,
                component_b_id=component_b.id,
                component_b_type=component_b.component_type,
                component_b_text=component_b.text,
                subgraph_envelope=envelope_text,
                argument_relation_types=schema.argument_relation_types_str(),
            )
        except Exception as exc:
            logger.warning(
                "ARC LLM call failed for (%s, %s): %s",
                component_a.id,
                component_b.id,
                exc,
            )
            return None

        if raw.relation_type is None:
            return None

        if raw.relation_type not in schema.argument_relation_types:
            logger.warning(
                "ARC: discarded unknown relation type %r for pair (%s, %s)",
                raw.relation_type,
                component_a.id,
                component_b.id,
            )
            return None

        if raw.confidence < self.confidence_threshold:
            return None

        source_id = component_a.id if raw.direction == "A_to_B" else component_b.id
        target_id = component_b.id if raw.direction == "A_to_B" else component_a.id

        return TheoryRelation(
            source_id=source_id,
            target_id=target_id,
            relation_type=raw.relation_type,
            confidence=raw.confidence,
            scope="global",
            weight=raw.weight if raw.weight is not None else raw.confidence,
        )

__init__(llm, embedding_model=None, prompts=None, strategy='direct_constrained', confidence_threshold=0.65, subgraph_depth=2, max_candidates_per_component=10, use_priority_rank=False)

Initialize the TAGARCClassifier.

Parameters

llm : Any The language model used for structural prediction. embedding_model : Any, optional The embedding model for computing dense representations, by default None. prompts : Any, optional The prompt template configuration, by default None. strategy : str, optional The prediction strategy, by default "direct_constrained". confidence_threshold : float, optional The minimum LLM confidence to accept a relation, by default 0.65. subgraph_depth : int, optional The depth of structural neighborhood to retrieve, by default 2. max_candidates_per_component : int, optional The max number of cross-chunk partners per component, by default 10. use_priority_rank : bool, optional If True, falls back to epistemic rank instead of embeddings, by default False.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase4_argument_mining/arc_classifier.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def __init__(
    self,
    llm: Any,
    embedding_model: Any = None,
    prompts: Any = None,
    strategy: str = "direct_constrained",
    confidence_threshold: float = 0.65,
    subgraph_depth: int = 2,
    max_candidates_per_component: int = 10,
    use_priority_rank: bool = False,
) -> None:
    """
    Initialize the TAGARCClassifier.

    Parameters
    ----------
    llm : Any
        The language model used for structural prediction.
    embedding_model : Any, optional
        The embedding model for computing dense representations, by default None.
    prompts : Any, optional
        The prompt template configuration, by default None.
    strategy : str, optional
        The prediction strategy, by default "direct_constrained".
    confidence_threshold : float, optional
        The minimum LLM confidence to accept a relation, by default 0.65.
    subgraph_depth : int, optional
        The depth of structural neighborhood to retrieve, by default 2.
    max_candidates_per_component : int, optional
        The max number of cross-chunk partners per component, by default 10.
    use_priority_rank : bool, optional
        If True, falls back to epistemic rank instead of embeddings, by default False.
    """
    self.llm = ensure_structured_llm(llm)
    self.embedding_model = embedding_model
    self.prompts = prompts
    self.strategy = strategy
    self.confidence_threshold = confidence_threshold
    self.subgraph_depth = subgraph_depth
    self.max_candidates_per_component = max_candidates_per_component
    self.use_priority_rank = use_priority_rank

classify_global(local_components, local_relations, graph_store, global_extractor, schema) async

Predict cross-chunk argument relations using the LLM.

Parameters

local_components : list[TheoryAtom] The list of theory atoms to pair up. local_relations : list[TheoryRelation] The relations already extracted locally. graph_store : GraphReader The graph database reader to fetch subgraph neighborhoods. global_extractor : GlobalRelationExtractor The extractor used to fetch the structural context. schema : SchemaConfig The pipeline schema definitions.

Returns

list[TheoryRelation] A list of successfully predicted global relations.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase4_argument_mining/arc_classifier.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
async def classify_global(
    self,
    local_components: list[TheoryAtom],
    local_relations: list[TheoryRelation],
    graph_store: GraphReader,
    global_extractor: GlobalRelationExtractor,
    schema: SchemaConfig,
) -> list[TheoryRelation]:
    """
    Predict cross-chunk argument relations using the LLM.

    Parameters
    ----------
    local_components : list[TheoryAtom]
        The list of theory atoms to pair up.
    local_relations : list[TheoryRelation]
        The relations already extracted locally.
    graph_store : GraphReader
        The graph database reader to fetch subgraph neighborhoods.
    global_extractor : GlobalRelationExtractor
        The extractor used to fetch the structural context.
    schema : SchemaConfig
        The pipeline schema definitions.

    Returns
    -------
    list[TheoryRelation]
        A list of successfully predicted global relations.
    """
    candidate_pairs = await self._cross_chunk_pairs(local_components, schema)
    logger.info(
        "ARC: %d components → %d cross-chunk candidate pairs",
        len(local_components),
        len(candidate_pairs),
    )

    tasks = [
        self._classify_pair(a, b, graph_store, global_extractor, schema)
        for a, b in candidate_pairs
    ]
    results = await asyncio.gather(*tasks, return_exceptions=True)

    global_relations: list[TheoryRelation] = []
    for (a, b), result in zip(candidate_pairs, results):
        if isinstance(result, Exception):
            logger.error("ARC pair (%s, %s) failed: %s", a.id, b.id, result)
            continue
        if result is not None:
            global_relations.append(result)

    logger.info(
        "ARC: extracted %d global argument relations", len(global_relations)
    )
    return global_relations

fingerprint()

Return deterministic TAG ARC classifier configuration.

Returns

dict of str to Any Dictionary containing thresholds, subgraph depth, strategy, and fingerprints of LLM and embedding model.

Source code in packages/episteme-pipeline/episteme_pipeline/phases/phase4_argument_mining/arc_classifier.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic TAG ARC classifier configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing thresholds, subgraph depth, strategy,
        and fingerprints of LLM and embedding model.
    """
    from episteme_pipeline.runs.fingerprints import fingerprint_method

    return {
        "class": self.__class__.__name__,
        "strategy": str(getattr(self.strategy, "value", self.strategy)),
        "confidence_threshold": self.confidence_threshold,
        "subgraph_depth": self.subgraph_depth,
        "max_candidates_per_component": self.max_candidates_per_component,
        "use_priority_rank": self.use_priority_rank,
        "llm": fingerprint_method(self.llm),
        "embedding_model": fingerprint_method(self.embedding_model),
    }