citebound 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
citebound/grounding.py ADDED
@@ -0,0 +1,545 @@
1
+ """The deterministic grounding gate: the last check before a reader.
2
+
3
+ An LLM judge can be wrong. This adds deterministic string checks; they can
4
+ also miss errors and do not establish semantic entailment.
5
+ It answers one question per sentence: is there a retrieved passage that
6
+ actually supports this, and is the sentence pointing at it?
7
+
8
+ Three outcomes per sentence:
9
+
10
+ * supported by the passages it cites -> kept as written
11
+ * supported by a DIFFERENT retrieved passage -> citation repaired to that one
12
+ * supported by nothing retrieved -> stripped
13
+
14
+ If more than ``max_stripped_ratio`` of the sentences are stripped the answer
15
+ is untrustworthy and the verdict is ``ok=False``: refuse, or repair upstream.
16
+
17
+ An English operator guard also rejects explicit polarity changes when the
18
+ claim and an evidence sentence have matching normalized content anchors.
19
+ A unit guard rejects a passage that quotes the claim's own figure with a
20
+ different unit, so "3 days" cannot support "3 months". Both apply to the
21
+ original citations and to candidate citation repairs.
22
+
23
+ What this deliberately does NOT do is judge semantic entailment. Lexical
24
+ overlap is a weak signal, and a deterministic checker that tried to be clever
25
+ about paraphrase would produce false refusals on good answers. Entailment is
26
+ a judge's job; this gate catches claims with no evidentiary basis at all, and
27
+ makes sure every citation points where it says it does. In particular:
28
+ **every number in a claim must appear in a passage that claim cites.** For a
29
+ system answering questions about refund windows, notice periods and limits,
30
+ a plausible-but-wrong number is the most damaging thing it can say.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import re
36
+ from collections.abc import Sequence
37
+ from dataclasses import asdict, dataclass, field
38
+ from enum import Enum
39
+ from typing import Any
40
+
41
+ from .citations import (
42
+ CITATION_RE,
43
+ CitationStyle,
44
+ normalize_citations,
45
+ numeric_to_tags,
46
+ tags_to_numeric,
47
+ )
48
+ from .passages import Passage, _with_ids
49
+ from .polarity import PolarityGuard, statement
50
+ from .refusal import RefusalReason, is_refusal, refusal_text
51
+ from .units import UnitGuard, figures
52
+
53
+ # Refuse only if MOST of the answer is ungrounded. A single weak sentence in an
54
+ # otherwise-cited answer is stripped and the rest still ships.
55
+ MAX_STRIPPED_RATIO = 0.50
56
+
57
+ # Fraction of a claim's content words that must appear in its evidence. Low on
58
+ # purpose: see the module docstring.
59
+ MIN_LEXICAL_OVERLAP = 0.25
60
+
61
+ # A "sentence" that is only whitespace before its citation has no claim to
62
+ # falsify, so a degenerate generation (bare tags, no content) would sail
63
+ # through. Require at least this many real words to count as a claim.
64
+ MIN_WORDS_PER_SENTENCE = 2
65
+
66
+ _NUMBER_RE = re.compile(r"\d[\d,]*\.?\d*")
67
+ _WORD_RE = re.compile(r"[A-Za-z]{2,}")
68
+ # Markdown list markers. Stripped before numbers are extracted, so "1. The
69
+ # window is 30 days" is not read as a factual claim about the number one.
70
+ _LIST_MARKER_RE = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+")
71
+ # What may sit between two tags for them to be one group: whitespace and the
72
+ # punctuation a model puts around stacked tags ("[a] [b]", "[a], [b].").
73
+ _BETWEEN_TAGS_RE = re.compile(r"^[\s.,;:]*$")
74
+ # A sentence ends at terminal punctuation followed by whitespace, or at a line
75
+ # break (list items and table rows are claims in their own right).
76
+ _SENTENCE_SPLIT_RE = re.compile(r"(?<=[.!?])\s+|\n+")
77
+ # A passage id written INTO the prose rather than inside a tag: "the table in
78
+ # chunk a63a..._p0_s27_c0 lists...". Its digits would otherwise be read as
79
+ # figures the evidence must contain, and it means nothing to a reader anyway.
80
+ _CHUNK_REF_RE = re.compile(r"(?:\bchunks?\s*)?[\w-]*_(?:p\d+_)?s\d+_c\d+\b|(?<![\w])_c\d+\b")
81
+ _EMPTY_PARENS_RE = re.compile(r"\(\s*[,;\s]*\)")
82
+
83
+ _STOPWORDS = frozenset(
84
+ {
85
+ "a",
86
+ "an",
87
+ "and",
88
+ "are",
89
+ "as",
90
+ "at",
91
+ "be",
92
+ "been",
93
+ "but",
94
+ "by",
95
+ "can",
96
+ "do",
97
+ "does",
98
+ "for",
99
+ "from",
100
+ "had",
101
+ "has",
102
+ "have",
103
+ "if",
104
+ "in",
105
+ "into",
106
+ "is",
107
+ "it",
108
+ "its",
109
+ "may",
110
+ "must",
111
+ "not",
112
+ "of",
113
+ "on",
114
+ "or",
115
+ "should",
116
+ "that",
117
+ "the",
118
+ "their",
119
+ "there",
120
+ "these",
121
+ "this",
122
+ "to",
123
+ "was",
124
+ "were",
125
+ "will",
126
+ "with",
127
+ "you",
128
+ "your",
129
+ "we",
130
+ "our",
131
+ "they",
132
+ "them",
133
+ "he",
134
+ "she",
135
+ "his",
136
+ "her",
137
+ }
138
+ )
139
+
140
+
141
+ class ClaimStatus(str, Enum):
142
+ SUPPORTED = "supported" # kept, cited passages support it
143
+ REPAIRED = "repaired" # kept, citation re-pointed to the passage that supports it
144
+ STRIPPED = "stripped" # removed, nothing retrieved supports it
145
+
146
+ def __str__(self) -> str:
147
+ return self.value
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class Claim:
152
+ """One sentence of the answer and what happened to it."""
153
+
154
+ text: str
155
+ status: ClaimStatus
156
+ cited: tuple[str, ...] # passage ids the model cited for it
157
+ supported_by: tuple[str, ...] # passage ids that actually support it (empty if stripped)
158
+ unsupported_numbers: tuple[str, ...] = () # figures no cited passage contained
159
+
160
+
161
+ @dataclass(frozen=True)
162
+ class Verdict:
163
+ """What the gate decided. ``ok`` is the one bit that matters; the rest explains it."""
164
+
165
+ ok: bool
166
+ answer: str # the supported subset, re-cited; empty when nothing survived
167
+ claims: tuple[Claim, ...]
168
+ stripped_ratio: float
169
+ cited_ids: tuple[str, ...] # passages the surviving answer rests on, first-seen order
170
+ repaired_citations: int
171
+ refusal: RefusalReason | None # set when ok is False, or when the model refused
172
+ is_refusal: bool = False # the model itself said the evidence was insufficient
173
+
174
+ @property
175
+ def stripped(self) -> tuple[Claim, ...]:
176
+ return tuple(c for c in self.claims if c.status is ClaimStatus.STRIPPED)
177
+
178
+ @property
179
+ def passed(self) -> bool:
180
+ """True when a verified answer exists. False for refusals of any kind."""
181
+ return self.ok and not self.is_refusal and bool(self.answer.strip())
182
+
183
+ def safe_text(self) -> str:
184
+ """The verified answer, or refusal prose generated from the reason code.
185
+
186
+ Never the rejected draft: that is the one text the gate just decided
187
+ it could not stand behind.
188
+ """
189
+ if self.passed:
190
+ return self.answer
191
+ return refusal_text(self.refusal or RefusalReason.UNVERIFIABLE_ANSWER)
192
+
193
+ def to_dict(self) -> dict[str, Any]:
194
+ """A JSON-ready view of the verdict: plain strings, lists and numbers.
195
+
196
+ The same shape the CLI prints with ``--json`` and the playground
197
+ renders, so a verdict logged from any of them reads the same.
198
+ """
199
+ d = asdict(self, dict_factory=_json_dict)
200
+ d["refusal"] = self.refusal.value if self.refusal else None
201
+ d["passed"] = self.passed
202
+ d["safe_text"] = self.safe_text()
203
+ return d
204
+
205
+
206
+ def _json_dict(items: list[tuple[str, Any]]) -> dict[str, Any]:
207
+ """``asdict`` factory: tuples become lists and enums their values."""
208
+ out: dict[str, Any] = {}
209
+ for k, v in items:
210
+ if isinstance(v, tuple):
211
+ v = list(v)
212
+ elif isinstance(v, Enum):
213
+ v = v.value
214
+ out[k] = v
215
+ return out
216
+
217
+
218
+ @dataclass
219
+ class _Options:
220
+ max_stripped_ratio: float = MAX_STRIPPED_RATIO
221
+ min_lexical_overlap: float = MIN_LEXICAL_OVERLAP
222
+ question_numbers: set[str] = field(default_factory=set)
223
+
224
+
225
+ # ------------------------------------------------------------------ helpers
226
+
227
+
228
+ def _numbers_in(text: str) -> set[str]:
229
+ """Numeric tokens, comma separators removed so "1,200" matches "1200"."""
230
+ return {n.replace(",", "").rstrip(".") for n in _NUMBER_RE.findall(text)}
231
+
232
+
233
+ def _content_terms(text: str) -> set[str]:
234
+ return {w.lower() for w in _WORD_RE.findall(text) if w.lower() not in _STOPWORDS}
235
+
236
+
237
+ def _overlap(claim_terms: set[str], passage: Passage) -> float:
238
+ terms = _content_terms(passage.evidence)
239
+ if not terms or not claim_terms:
240
+ return 0.0
241
+ return len(claim_terms & terms) / len(claim_terms)
242
+
243
+
244
+ def _without_chunk_refs(sentence: str) -> str:
245
+ text = _CHUNK_REF_RE.sub(" ", sentence)
246
+ text = _EMPTY_PARENS_RE.sub("", text)
247
+ text = re.sub(r"\s+([,.;:])", r"\1", text)
248
+ return re.sub(r"\s{2,}", " ", text).strip()
249
+
250
+
251
+ def _is_lead_in(sentence: str) -> bool:
252
+ """ "The main ones are:" introduces the claims that follow and asserts nothing."""
253
+ return sentence.rstrip().endswith(":")
254
+
255
+
256
+ def _cited_units(answer: str) -> list[tuple[str, list[str]]]:
257
+ """Pair each GROUP of citation tags with the text before it.
258
+
259
+ Consecutive tags are one group: "...decisions. [a] [b] [c]" means these
260
+ three passages together support what came before, which is how a summary
261
+ drawing on several passages is naturally cited. Walking tag to tag means a
262
+ period inside the text (an abbreviation, a decimal) can never make a tag
263
+ unparseable, and every character before the last tag is accounted for.
264
+ """
265
+ units: list[tuple[str, list[str]]] = []
266
+ pos = 0
267
+ for m in CITATION_RE.finditer(answer):
268
+ between = answer[pos : m.start()]
269
+ if units and _BETWEEN_TAGS_RE.match(between):
270
+ if m.group(1) not in units[-1][1]:
271
+ units[-1][1].append(m.group(1))
272
+ else:
273
+ units.append((between, [m.group(1)]))
274
+ pos = m.end()
275
+ return units
276
+
277
+
278
+ def _sentences(text: str) -> list[str]:
279
+ """The individual claims before a citation group, each checked on its own.
280
+
281
+ Scoring a whole cited paragraph as one unit would let an invented sentence
282
+ ride along inside an otherwise-true paragraph, diluted by its neighbours.
283
+ A fragment too short to be a claim ("e.g.", "No.") is joined to the next
284
+ piece rather than scored.
285
+ """
286
+ text = text.strip().lstrip(".!?").strip()
287
+ out: list[str] = []
288
+ carry = ""
289
+ for piece in _SENTENCE_SPLIT_RE.split(text):
290
+ piece = piece.strip()
291
+ if not piece:
292
+ continue
293
+ if carry:
294
+ piece = f"{carry} {piece}"
295
+ if len(_WORD_RE.findall(piece)) < MIN_WORDS_PER_SENTENCE:
296
+ carry = piece
297
+ continue
298
+ carry = ""
299
+ out.append(piece)
300
+ if carry and out:
301
+ out[-1] = f"{out[-1]} {carry}"
302
+ return out
303
+
304
+
305
+ def _supported_by_group(
306
+ claim_terms: set[str], claim_numbers: set[str], passages: Sequence[Passage], opt: _Options
307
+ ) -> bool:
308
+ """Do the passages this claim cites, taken together, support it?
309
+
310
+ Together, because that is what citing several passages asserts: the
311
+ "90-day pilot" may come from one and "ISO 27001" from another. Every
312
+ figure must still appear in something the claim actually cites.
313
+ """
314
+ if not passages or not claim_terms:
315
+ return False
316
+ evidence_terms: set[str] = set()
317
+ evidence_numbers: set[str] = set()
318
+ for p in passages:
319
+ evidence_terms |= _content_terms(p.evidence)
320
+ evidence_numbers |= _numbers_in(p.evidence)
321
+ if len(claim_terms & evidence_terms) / len(claim_terms) < opt.min_lexical_overlap:
322
+ return False
323
+ return not (claim_numbers - evidence_numbers - opt.question_numbers)
324
+
325
+
326
+ def _minimal_support(
327
+ claim_terms: set[str], claim_numbers: set[str], passages: Sequence[Passage], opt: _Options
328
+ ) -> list[Passage] | None:
329
+ """The smallest set of these passages that together support the claim.
330
+
331
+ A group cited after a paragraph applies to every sentence in it, but each
332
+ sentence should keep only the passages it rests on, so a reader who clicks
333
+ a citation lands on text about THAT sentence. Greedy: take the passage
334
+ that supplies the most missing figures, then the most new words, until
335
+ the claim is supported. Deterministic, and exact for the two or three
336
+ passages a sentence cites in practice.
337
+ """
338
+ if not _supported_by_group(claim_terms, claim_numbers, passages, opt):
339
+ return None
340
+ needed_numbers = claim_numbers - opt.question_numbers
341
+ evidence = {p.id: (_content_terms(p.evidence), _numbers_in(p.evidence)) for p in passages}
342
+ chosen: list[Passage] = []
343
+ covered_terms: set[str] = set()
344
+ covered_numbers: set[str] = set()
345
+ remaining = list(passages)
346
+ while not _supported_by_group(claim_terms, claim_numbers, chosen, opt):
347
+ best = max(
348
+ remaining,
349
+ key=lambda p: (
350
+ len((needed_numbers - covered_numbers) & evidence[p.id][1]),
351
+ len((claim_terms - covered_terms) & evidence[p.id][0]),
352
+ ),
353
+ )
354
+ chosen.append(best)
355
+ remaining.remove(best)
356
+ covered_terms |= evidence[best.id][0] & claim_terms
357
+ covered_numbers |= evidence[best.id][1] & needed_numbers
358
+ return chosen
359
+
360
+
361
+ def _best_supporting(
362
+ claim_terms: set[str], claim_numbers: set[str], candidates: Sequence[Passage], opt: _Options
363
+ ) -> Passage | None:
364
+ """The retrieved passage that best supports this claim, or None.
365
+
366
+ Reached only after the cited passages have failed. Highest overlap wins,
367
+ because a reader will click the citation expecting to read exactly that.
368
+ """
369
+ supporting = [
370
+ p for p in candidates if _supported_by_group(claim_terms, claim_numbers, [p], opt)
371
+ ]
372
+ if not supporting:
373
+ return None
374
+ return max(supporting, key=lambda p: _overlap(claim_terms, p))
375
+
376
+
377
+ # --------------------------------------------------------------------- gate
378
+
379
+
380
+ def verify(
381
+ answer: str,
382
+ passages: Sequence[Passage],
383
+ question: str = "",
384
+ *,
385
+ citation_style: CitationStyle = "tag",
386
+ max_stripped_ratio: float = MAX_STRIPPED_RATIO,
387
+ min_lexical_overlap: float = MIN_LEXICAL_OVERLAP,
388
+ ) -> Verdict:
389
+ """Check an answer against the passages it was generated from.
390
+
391
+ ``question`` matters: numbers echoed from it are not fabrications. "Is 20
392
+ days within the window?" invites an answer that restates 20 while the
393
+ evidence contains only 30, and stripping that would refuse a correct answer.
394
+
395
+ ``citation_style="numeric"`` reads ``[1]``, ``[2, 3]`` as 1-based positions
396
+ in ``passages`` and writes the verified answer back in that style.
397
+
398
+ Thresholds must be finite numbers in [0, 1]; invalid options raise
399
+ ``ValueError`` before verification. Even at ``max_stripped_ratio=1``,
400
+ at least one claim must survive for the answer to pass.
401
+ """
402
+ if citation_style not in ("tag", "numeric"):
403
+ raise ValueError("citation_style must be 'tag' or 'numeric'")
404
+ for name, value in (
405
+ ("max_stripped_ratio", max_stripped_ratio),
406
+ ("min_lexical_overlap", min_lexical_overlap),
407
+ ):
408
+ # The bounded comparison rejects NaN/infinities as well as out-of-range
409
+ # values without coercing strings, booleans or other caller mistakes.
410
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0 <= value <= 1:
411
+ raise ValueError(f"{name} must be a finite number between 0 and 1")
412
+ passages = _with_ids(passages)
413
+ ids = [p.id for p in passages]
414
+ opt = _Options(max_stripped_ratio, min_lexical_overlap, _numbers_in(question))
415
+
416
+ text = normalize_citations(answer)
417
+ if citation_style == "numeric":
418
+ text = numeric_to_tags(text, ids)
419
+
420
+ if is_refusal(text):
421
+ return Verdict(
422
+ ok=True,
423
+ answer="",
424
+ claims=(),
425
+ stripped_ratio=0.0,
426
+ cited_ids=(),
427
+ repaired_citations=0,
428
+ refusal=RefusalReason.INSUFFICIENT_EVIDENCE,
429
+ is_refusal=True,
430
+ )
431
+
432
+ by_id = {p.id: p for p in passages}
433
+ units = _cited_units(text)
434
+ if not units: # no parseable citations at all: fail closed
435
+ return _failed(text, (), 1.0)
436
+
437
+ claims: list[Claim] = []
438
+ kept: list[str] = []
439
+ cited_ids: list[str] = []
440
+ stripped = repaired = total = 0
441
+ polarity_guard = PolarityGuard()
442
+ unit_guard = UnitGuard()
443
+
444
+ for prose, tag_ids in units:
445
+ # Tags naming passages that were never retrieved are fabricated; they
446
+ # cannot support anything, so they simply drop out of the group.
447
+ cited = [by_id[i] for i in tag_ids if i in by_id]
448
+ sentences = _sentences(prose)
449
+ if not sentences:
450
+ total += 1
451
+ stripped += 1 # degenerate: tags with nothing to stand behind
452
+ claims.append(Claim(prose.strip(" .,;:\n\t"), ClaimStatus.STRIPPED, tuple(tag_ids), ()))
453
+ continue
454
+
455
+ for raw in sentences:
456
+ sentence = _without_chunk_refs(raw)
457
+ if _is_lead_in(sentence) or len(_WORD_RE.findall(sentence)) < MIN_WORDS_PER_SENTENCE:
458
+ continue # not a claim; counts neither for nor against
459
+ total += 1
460
+ plain = _LIST_MARKER_RE.sub("", sentence)
461
+ terms = _content_terms(sentence)
462
+ numbers = _numbers_in(plain)
463
+ polarity = statement(plain)
464
+ quoted = figures(plain)
465
+ eligible = [
466
+ p
467
+ for p in cited
468
+ if polarity_guard.allows(polarity, p) and unit_guard.allows(quoted, p)
469
+ ]
470
+ support = _minimal_support(terms, numbers, eligible, opt)
471
+ status = ClaimStatus.SUPPORTED
472
+ if support is None:
473
+ # The passages it cites do not support it (or were never
474
+ # retrieved). Before stripping, look for one that does, and
475
+ # re-point the citation so that clicking it lands on the
476
+ # claim. Accepting the sentence with its wrong tag would read
477
+ # fine and break the moment anyone checked.
478
+ eligible = [
479
+ p
480
+ for p in passages
481
+ if polarity_guard.allows(polarity, p) and unit_guard.allows(quoted, p)
482
+ ]
483
+ found = _best_supporting(terms, numbers, eligible, opt)
484
+ if found is None:
485
+ stripped += 1
486
+ missing = tuple(sorted(numbers - opt.question_numbers - _all_numbers(cited)))
487
+ claims.append(
488
+ Claim(sentence, ClaimStatus.STRIPPED, tuple(tag_ids), (), missing)
489
+ )
490
+ continue
491
+ support = [found]
492
+ status = ClaimStatus.REPAIRED
493
+ repaired += 1
494
+
495
+ # In retrieval order, not the order the greedy cover found them,
496
+ # so "[1][2]" never comes out as "[2][1]" for the same evidence.
497
+ support.sort(key=lambda p: ids.index(p.id))
498
+ tags = " ".join(f"[chunk:{p.id}]" for p in support)
499
+ kept.append(f"{sentence.rstrip('.').strip()} {tags}")
500
+ claims.append(Claim(sentence, status, tuple(tag_ids), tuple(p.id for p in support)))
501
+ for p in support:
502
+ if p.id not in cited_ids:
503
+ cited_ids.append(p.id)
504
+
505
+ if total == 0:
506
+ # Nothing but lead-ins and passage references: no claim was made, so
507
+ # there is nothing to stand behind. Fail closed, as for no citations.
508
+ return _failed(text, tuple(claims), 1.0)
509
+
510
+ ratio = stripped / total
511
+ clean = ". ".join(kept) + ("." if kept else "")
512
+ if citation_style == "numeric":
513
+ clean = tags_to_numeric(clean, ids)
514
+ ok = bool(kept) and ratio <= opt.max_stripped_ratio
515
+ return Verdict(
516
+ ok=ok,
517
+ # A failed verdict carries no text at all. The surviving sentences are
518
+ # still in ``claims`` for diagnosis, but handing back a partial answer
519
+ # the gate just judged untrustworthy invites a caller to ship it.
520
+ answer=clean if ok else "",
521
+ claims=tuple(claims),
522
+ stripped_ratio=ratio,
523
+ cited_ids=tuple(cited_ids),
524
+ repaired_citations=repaired,
525
+ refusal=None if ok else RefusalReason.UNVERIFIABLE_ANSWER,
526
+ )
527
+
528
+
529
+ def _all_numbers(passages: Sequence[Passage]) -> set[str]:
530
+ out: set[str] = set()
531
+ for p in passages:
532
+ out |= _numbers_in(p.evidence)
533
+ return out
534
+
535
+
536
+ def _failed(text: str, claims: tuple[Claim, ...], ratio: float) -> Verdict:
537
+ return Verdict(
538
+ ok=False,
539
+ answer="",
540
+ claims=claims,
541
+ stripped_ratio=ratio,
542
+ cited_ids=(),
543
+ repaired_citations=0,
544
+ refusal=RefusalReason.UNVERIFIABLE_ANSWER,
545
+ )
citebound/passages.py ADDED
@@ -0,0 +1,148 @@
1
+ """The evidence an answer is checked against.
2
+
3
+ A :class:`Passage` is one retrieved piece of text. Only ``text`` is required;
4
+ the rest lets the gate do more: ``section`` is counted as evidence (a heading
5
+ like "Item 7.2 > Refunds" grounds both the topic and the figure 7.2), and the
6
+ span plus document checksum let anyone recompute the provenance hash.
7
+
8
+ Adapters at the bottom build passages from the objects other libraries hand
9
+ you. They are duck-typed on purpose, so this package imports nothing.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterable, Sequence
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from .provenance import provenance_hash
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Passage:
23
+ text: str
24
+ id: str = ""
25
+ section: str = ""
26
+ source: str = "" # filename, URL, title: whatever a reader would recognise
27
+ page: int | None = None
28
+ char_start: int | None = None
29
+ char_end: int | None = None
30
+ document_sha256: str = "" # checksum of the file the span was cut from
31
+ provenance_hash: str = ""
32
+ metadata: dict[str, Any] = field(default_factory=dict, compare=False, hash=False)
33
+
34
+ @property
35
+ def evidence(self) -> str:
36
+ """What a claim may be supported by: the section path plus the text."""
37
+ return f"{self.section}\n{self.text}" if self.section else self.text
38
+
39
+ def with_provenance(self) -> Passage:
40
+ """A copy whose ``provenance_hash`` is computed from the span.
41
+
42
+ Needs ``document_sha256``, ``char_start`` and ``char_end``; without
43
+ them there is nothing to prove and the passage is returned unchanged.
44
+ """
45
+ if not self.document_sha256 or self.char_start is None or self.char_end is None:
46
+ return self
47
+ return Passage(
48
+ **{
49
+ **self.__dict__,
50
+ "provenance_hash": provenance_hash(
51
+ self.document_sha256, self.char_start, self.char_end, self.text
52
+ ),
53
+ }
54
+ )
55
+
56
+
57
+ def _with_ids(passages: Iterable[Passage]) -> list[Passage]:
58
+ """Give every passage without an id a positional one (``p1``, ``p2``...).
59
+
60
+ Ids must be unique: two passages with the same id would make a citation
61
+ ambiguous, and the gate would silently check against the wrong one.
62
+ """
63
+ out: list[Passage] = []
64
+ seen: set[str] = set()
65
+ for i, p in enumerate(passages, start=1):
66
+ pid = p.id or f"p{i}"
67
+ if pid in seen:
68
+ raise ValueError(f"duplicate passage id {pid!r}")
69
+ seen.add(pid)
70
+ out.append(p if p.id else Passage(**{**p.__dict__, "id": pid}))
71
+ return out
72
+
73
+
74
+ def passages_from_texts(texts: Sequence[str], ids: Sequence[str] | None = None) -> list[Passage]:
75
+ """Passages from plain strings, for the simplest possible call site."""
76
+ if ids is not None and len(ids) != len(texts):
77
+ raise ValueError("ids and texts must have the same length")
78
+ return _with_ids(Passage(text=t, id=ids[i] if ids else "") for i, t in enumerate(texts))
79
+
80
+
81
+ # ----------------------------------------------------------------- adapters
82
+
83
+
84
+ def _meta(obj: Any) -> dict[str, Any]:
85
+ md = getattr(obj, "metadata", None)
86
+ return dict(md) if isinstance(md, dict) else {}
87
+
88
+
89
+ def from_langchain(documents: Iterable[Any]) -> list[Passage]:
90
+ """Passages from LangChain ``Document`` objects (``page_content`` + ``metadata``).
91
+
92
+ Recognised metadata keys, all optional: ``id``/``chunk_id``, ``source``,
93
+ ``page``, ``section``, ``start_index`` (what ``add_start_index=True`` on the
94
+ text splitters writes), ``char_start``/``char_end``, ``document_sha256``.
95
+ """
96
+ out: list[Passage] = []
97
+ for d in documents:
98
+ md = _meta(d)
99
+ text = getattr(d, "page_content", None)
100
+ if text is None:
101
+ raise TypeError("expected an object with .page_content (a LangChain Document)")
102
+ start = md.get("char_start", md.get("start_index"))
103
+ end = md.get("char_end")
104
+ if start is not None and end is None:
105
+ end = int(start) + len(text)
106
+ out.append(
107
+ Passage(
108
+ text=text,
109
+ id=str(md.get("id") or md.get("chunk_id") or getattr(d, "id", "") or ""),
110
+ section=str(md.get("section") or ""),
111
+ source=str(md.get("source") or md.get("title") or ""),
112
+ page=md.get("page"),
113
+ char_start=start,
114
+ char_end=end,
115
+ document_sha256=str(md.get("document_sha256") or ""),
116
+ metadata=md,
117
+ )
118
+ )
119
+ return _with_ids(out)
120
+
121
+
122
+ def from_llamaindex(nodes: Iterable[Any]) -> list[Passage]:
123
+ """Passages from LlamaIndex nodes, or the ``NodeWithScore`` wrappers a
124
+ retriever returns. Uses ``node_id``, ``get_content()``, ``start_char_idx``,
125
+ ``end_char_idx`` and the ``file_name``/``page_label`` metadata keys."""
126
+ out: list[Passage] = []
127
+ for n in nodes:
128
+ node = getattr(n, "node", n)
129
+ get_content = getattr(node, "get_content", None)
130
+ text = get_content() if callable(get_content) else getattr(node, "text", None)
131
+ if text is None:
132
+ raise TypeError("expected a LlamaIndex node or NodeWithScore")
133
+ md = _meta(node)
134
+ page = md.get("page_label")
135
+ out.append(
136
+ Passage(
137
+ text=text,
138
+ id=str(getattr(node, "node_id", "") or getattr(node, "id_", "") or ""),
139
+ section=str(md.get("section") or ""),
140
+ source=str(md.get("file_name") or md.get("source") or ""),
141
+ page=int(page) if isinstance(page, (int, str)) and str(page).isdigit() else None,
142
+ char_start=getattr(node, "start_char_idx", None),
143
+ char_end=getattr(node, "end_char_idx", None),
144
+ document_sha256=str(md.get("document_sha256") or ""),
145
+ metadata=md,
146
+ )
147
+ )
148
+ return _with_ids(out)