-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretrieval.py
More file actions
1631 lines (1538 loc) · 61.6 KB
/
Copy pathretrieval.py
File metadata and controls
1631 lines (1538 loc) · 61.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
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
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import hashlib
import json
import re
import time
import uuid
from collections import defaultdict
from collections.abc import Awaitable, Callable, Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any, Protocol, cast
import tiktoken
from sqlalchemy import Date, Text, and_, case, func, literal, or_, select, tuple_
from sqlalchemy import cast as sql_cast
from sqlalchemy.dialects.postgresql import array
from sqlalchemy.ext.asyncio import AsyncSession
from vectorless_rag.config import Settings
from vectorless_rag.llm import UNTRUSTED_DOCUMENT_SYSTEM, StructuredLLM, wrap_untrusted_document
from vectorless_rag.models import (
Document,
DocumentMetadataVersion,
DocumentStatus,
IndexVersion,
ModelCallStage,
)
from vectorless_rag.pageindex_artifact import (
DerivedNode,
derive_nodes,
load_manifest_v2,
)
from vectorless_rag.schemas import (
CandidateSelection,
DocumentMetadata,
Evidence,
MetadataConstraints,
NodeChoice,
NodeSelection,
SufficiencyDecision,
)
from vectorless_rag.storage import ObjectStore
QUOTED_PHRASE = re.compile(r'"([^"\n]+)"|“([^”\n]+)”')
FALLBACK_SEARCH_EXCLUDED_TOKENS = frozenset({"or", "and", "not"})
MODEL_TEXT_TOKEN_LIMIT = 2_048
COMPARISON_TEXT_TOKEN_FLOOR = 8
COMPARISON_TEXT_TOKEN_LIMIT = 256
CATALOG_MAP_DETAIL_LIMIT = 256
CATALOG_MAP_OUTLINE_LIMIT = 16
@dataclass(frozen=True)
class CatalogRoutingLimiter:
maximum_concurrency: int
semaphore: asyncio.Semaphore = field(init=False)
def __post_init__(self) -> None:
if self.maximum_concurrency < 1:
raise ValueError("catalog routing concurrency must be positive")
object.__setattr__(
self,
"semaphore",
asyncio.Semaphore(self.maximum_concurrency),
)
async def _gather_or_cancel[ResultT](
operations: Sequence[Callable[[], Awaitable[ResultT]]],
limiter: CatalogRoutingLimiter,
) -> list[ResultT]:
missing = object()
results: list[ResultT | object] = [missing] * len(operations)
next_index = 0
failure: BaseException | None = None
stopped = asyncio.Event()
workers: list[asyncio.Task[None]] = []
async def work() -> None:
nonlocal failure, next_index
while not stopped.is_set() and next_index < len(operations):
index = next_index
next_index += 1
async with limiter.semaphore:
if stopped.is_set():
return
try:
results[index] = await operations[index]()
except BaseException as error:
if failure is None:
failure = error
stopped.set()
current = asyncio.current_task()
for worker in workers:
if worker is not current:
worker.cancel()
raise
workers.extend(
asyncio.create_task(work())
for _ in range(min(limiter.maximum_concurrency, len(operations)))
)
joined = asyncio.gather(*workers, return_exceptions=True)
try:
await asyncio.shield(joined)
except BaseException:
stopped.set()
for worker in workers:
worker.cancel()
await joined
raise
if failure is not None:
raise failure
if any(result is missing for result in results):
raise AssertionError("catalog routing operation did not produce a result")
return [cast(ResultT, result) for result in results]
def _canonical_json(value: object) -> str:
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
def _token_count(encoding: tiktoken.Encoding, value: object) -> int:
text = value if isinstance(value, str) else _canonical_json(value)
# disallowed_special=() throughout this module: these count and slice untrusted
# document text, and tiktoken otherwise raises on a page that merely contains the
# literal "<|endoftext|>". Special sequences are characters here, never controls.
return len(encoding.encode(text, disallowed_special=()))
def _wrapped_token_count(encoding: tiktoken.Encoding, value: object) -> int:
text = value if isinstance(value, str) else _canonical_json(value)
return len(encoding.encode(wrap_untrusted_document(text), disallowed_special=()))
def _truncate_text(
encoding: tiktoken.Encoding,
value: str,
limit: int,
cache: dict[str, list[int]],
) -> str:
if not value or limit <= 0:
return ""
tokens = cache.get(value)
if tokens is None:
character_limit = min(len(value), MODEL_TEXT_TOKEN_LIMIT * 16)
while True:
tokens = encoding.encode(value[:character_limit], disallowed_special=())
if len(tokens) >= MODEL_TEXT_TOKEN_LIMIT or character_limit == len(value):
break
character_limit = min(len(value), character_limit * 2)
tokens = tokens[:MODEL_TEXT_TOKEN_LIMIT]
cache[value] = tokens
return encoding.decode(tokens[:limit])
def candidate_search_text(question: str) -> str:
phrases = [next(value for value in match if value) for match in QUOTED_PHRASE.findall(question)]
return max(phrases, key=len) if phrases else question
def fallback_search_tokens(question: str) -> list[str]:
tokens = re.findall(r"[a-z0-9]+", question.lower())
return list(
dict.fromkeys(token for token in tokens if token not in FALLBACK_SEARCH_EXCLUDED_TOKENS)
)[:24]
@dataclass(frozen=True)
class CandidateDocument:
document: Document
fts_match: bool = False
lexical_rank: float = 0.0
exact_match: bool = False
description: str = ""
outline: list[dict[str, Any]] = field(default_factory=list)
index_digest: str = ""
configuration_hash: str | None = None
@property
def signals(self) -> tuple[str, ...]:
values: list[str] = []
if self.exact_match:
values.append("exact_match")
if self.fts_match or self.lexical_rank > 0:
values.append("lexical_match")
return tuple(values or ["catalog_reasoning"])
@dataclass(frozen=True)
class RankedDocument:
document: Document
rank: int
signals: tuple[str, ...]
reason: str
@dataclass(frozen=True)
class _CatalogBatch:
candidates: tuple[CandidateDocument, ...]
payload: tuple[dict[str, object], ...]
@dataclass(frozen=True)
class RetrievalResult:
evidence: list[Evidence]
candidate_ids: list[uuid.UUID]
selected_ids: list[uuid.UUID]
sufficient: bool
rounds: int
ranked_documents: tuple[RankedDocument, ...] = ()
unique_pages: int = 0
evidence_tokens: int = 0
overlap_pages_avoided: int = 0
content_truncated: bool = False
index_digests: dict[str, str] = field(default_factory=dict)
strategy: str = "pageindex-tree-v2"
strategy_version: str = "2"
configuration_hash: str | None = None
phase_timings_ms: dict[str, int] = field(default_factory=dict)
@property
def evidence_hash(self) -> str:
payload = "\n".join(item.content for item in self.evidence)
return hashlib.sha256(payload.encode()).hexdigest()
class Retriever(Protocol):
async def retrieve(
self,
session: AsyncSession,
question: str,
constraints: MetadataConstraints,
restrict_ids: list[uuid.UUID] | None = None,
*,
evidence_token_budget: int | None = None,
index_version_ids: Mapping[uuid.UUID, uuid.UUID] | None = None,
) -> RetrievalResult: ...
class CorpusRouter:
def __init__(
self,
settings: Settings,
llm: StructuredLLM,
*,
catalog_routing_limiter: CatalogRoutingLimiter | None = None,
) -> None:
self.settings = settings
self.llm = llm
self.encoding = tiktoken.get_encoding("cl100k_base")
self.catalog_routing_limiter = catalog_routing_limiter or CatalogRoutingLimiter(
settings.catalog_routing_concurrency
)
async def candidates(
self,
session: AsyncSession,
question: str,
constraints: MetadataConstraints,
restrict_ids: list[uuid.UUID] | None = None,
*,
index_version_ids: Mapping[uuid.UUID, uuid.UUID] | None = None,
) -> list[CandidateDocument]:
filters: list[Any] = []
if index_version_ids is None:
filters.extend(
[
Document.status == DocumentStatus.ready,
Document.active_index_version_id.is_not(None),
]
)
index_join = and_(
IndexVersion.id == Document.active_index_version_id,
IndexVersion.document_id == Document.id,
)
title = Document.title
abstract = Document.abstract
description = Document.description
topics = Document.topics
submitted_date = Document.submitted_date
search_vector = Document.search_vector
metadata_payload = literal(None)
metadata_page_count = literal(None)
else:
filters.append(
tuple_(Document.id, IndexVersion.id).in_(tuple(index_version_ids.items()))
)
index_join = IndexVersion.document_id == Document.id
metadata_payload = DocumentMetadataVersion.metadata_payload
metadata_page_count = DocumentMetadataVersion.page_count
title = metadata_payload["title"].astext
abstract = metadata_payload["abstract"].astext
description = metadata_payload["description"].astext
topics = metadata_payload["topics"]
submitted_date = sql_cast(
func.nullif(metadata_payload["submitted_date"].astext, ""),
Date,
)
search_vector = func.to_tsvector(
"english",
func.concat_ws(
" ",
title,
abstract,
description,
sql_cast(topics, Text),
),
)
if constraints.arxiv_ids:
filters.append(Document.arxiv_id.in_(constraints.arxiv_ids))
if constraints.authors:
filters.append(
Document.authors.overlap(constraints.authors)
if index_version_ids is None
else metadata_payload["authors"].op("?|")(array(constraints.authors))
)
if constraints.topics:
filters.append(
Document.topics.overlap(constraints.topics)
if index_version_ids is None
else topics.op("?|")(array(constraints.topics))
)
if constraints.date_from:
filters.append(submitted_date >= constraints.date_from)
if constraints.date_to:
filters.append(submitted_date <= constraints.date_to)
if restrict_ids is not None:
filters.append(Document.id.in_(restrict_ids))
search_text = candidate_search_text(question)
strict_query = func.websearch_to_tsquery("english", search_text)
tokens = fallback_search_tokens(search_text)
signal_query = (
func.websearch_to_tsquery("english", " or ".join(tokens)) if tokens else strict_query
)
rank = func.ts_rank_cd(search_vector, signal_query)
strict_match = search_vector.op("@@")(strict_query)
normalized_question = search_text.strip().casefold()
exact = or_(
func.lower(Document.arxiv_id) == normalized_question,
func.lower(title) == normalized_question,
)
statement = select(
Document,
IndexVersion.id,
IndexVersion.pageindex_description,
IndexVersion.top_level_outline,
IndexVersion.manifest_sha256,
IndexVersion.artifact_sha256,
IndexVersion.configuration_hash,
metadata_payload,
metadata_page_count,
rank.label("lexical_rank"),
strict_match.label("strict_match"),
exact.label("exact_match"),
).join(IndexVersion, index_join)
if index_version_ids is not None:
statement = statement.join(
DocumentMetadataVersion,
and_(
DocumentMetadataVersion.id == IndexVersion.metadata_version_id,
DocumentMetadataVersion.document_id == Document.id,
),
)
statement = statement.where(and_(*filters)).order_by(
case((exact, 0), else_=1),
case((strict_match, 0), else_=1),
rank.desc(),
func.coalesce(Document.arxiv_id, literal("")),
Document.id,
)
rows = (await session.execute(statement)).all()
result: list[CandidateDocument] = []
for (
document,
index_version_id,
pageindex_description,
top_level_outline,
manifest_sha256,
artifact_sha256,
configuration_hash,
raw_metadata,
raw_metadata_page_count,
raw_rank,
raw_strict,
raw_exact,
) in rows:
selected_document = document
if raw_metadata is not None:
frozen_metadata = DocumentMetadata.model_validate(raw_metadata)
selected_document = Document(
id=document.id,
sha256=document.sha256,
arxiv_id=document.arxiv_id,
original_filename=document.original_filename,
pdf_object_key=document.pdf_object_key,
title=frozen_metadata.title,
authors=frozen_metadata.authors,
abstract=frozen_metadata.abstract,
description=frozen_metadata.description,
topics=frozen_metadata.topics,
submitted_date=frozen_metadata.submitted_date,
status=DocumentStatus.ready,
page_count=int(raw_metadata_page_count),
active_index_version_id=index_version_id,
)
result.append(
CandidateDocument(
document=selected_document,
fts_match=bool(raw_strict),
lexical_rank=float(raw_rank or 0),
exact_match=bool(raw_exact),
description=pageindex_description
or selected_document.description
or selected_document.abstract
or "",
outline=list(top_level_outline or []),
index_digest=manifest_sha256 or artifact_sha256,
configuration_hash=configuration_hash,
)
)
return result
def _payload(
self,
candidate: CandidateDocument,
*,
text_token_limit: int = MODEL_TEXT_TOKEN_LIMIT,
title_token_limit: int | None = None,
outline_limit: int = 64,
cache: dict[str, list[int]] | None = None,
) -> dict[str, object]:
token_cache = cache if cache is not None else {}
def text(value: str, character_limit: int | None = None) -> str:
bounded = value if character_limit is None else value[:character_limit]
return _truncate_text(
self.encoding,
bounded,
text_token_limit,
token_cache,
)
outline: list[dict[str, object]] = []
for raw in candidate.outline[:outline_limit]:
value: dict[str, object] = {}
for key in ("node_id", "page_start", "page_end"):
if key in raw:
value[key] = raw[key]
for key in ("title", "summary"):
raw_text = raw.get(key)
if isinstance(raw_text, str):
value[key] = text(raw_text)
outline.append(value)
return {
"id": str(candidate.document.id),
"arxiv_id": candidate.document.arxiv_id,
"title": _truncate_text(
self.encoding,
(candidate.document.title or "")[:300],
title_token_limit if title_token_limit is not None else text_token_limit,
token_cache,
),
"description": text(candidate.description, 4_000),
"abstract": text(candidate.document.abstract or "", 1_200),
"topics": [
bounded for topic in candidate.document.topics[:8] if (bounded := text(topic, 80))
],
"outline": outline,
"signals": list(candidate.signals),
"fts_match": candidate.fts_match,
"lexical_rank": round(candidate.lexical_rank, 8),
}
def _map_payload(
self,
candidate: CandidateDocument,
*,
detail: int,
cache: dict[str, list[int]],
) -> dict[str, object]:
return self._payload(
candidate,
text_token_limit=detail,
title_token_limit=max(int(bool(candidate.document.title)), detail),
outline_limit=min(
len(candidate.outline),
CATALOG_MAP_OUTLINE_LIMIT,
detail // CATALOG_MAP_OUTLINE_LIMIT,
),
cache=cache,
)
def _batches(
self,
candidates: Sequence[CandidateDocument],
) -> list[_CatalogBatch]:
limit = self.settings.catalog_batch_token_limit
maximum_batch_size = self.settings.document_limit * 4
batches: list[_CatalogBatch] = []
offset = 0
while offset < len(candidates):
maximum_size = min(maximum_batch_size, len(candidates) - offset)
batch_window = tuple(candidates[offset : offset + maximum_size])
token_cache: dict[str, list[int]] = {}
def payloads(
size: int,
detail: int,
window: tuple[CandidateDocument, ...] = batch_window,
cache: dict[str, list[int]] = token_cache,
) -> list[dict[str, object]]:
return [
self._map_payload(candidate, detail=detail, cache=cache)
for candidate in window[:size]
]
low = 1
high = maximum_size
fitting_size = 0
while low <= high:
middle = (low + high) // 2
if _wrapped_token_count(self.encoding, payloads(middle, 0)) <= limit:
fitting_size = middle
low = middle + 1
else:
high = middle - 1
if fitting_size == 0:
raise ValueError("catalog batch token limit cannot fit a minimal candidate")
low = 0
high = CATALOG_MAP_DETAIL_LIMIT
detail = 0
while low <= high:
middle = (low + high) // 2
if _wrapped_token_count(self.encoding, payloads(fitting_size, middle)) <= limit:
detail = middle
low = middle + 1
else:
high = middle - 1
batch_candidates = tuple(batch_window[:fitting_size])
batches.append(
_CatalogBatch(
batch_candidates,
tuple(payloads(fitting_size, detail)),
)
)
offset += fitting_size
return batches
def _comparison_payload(
self,
candidate: CandidateDocument,
prior_reason: str,
*,
text_token_limit: int,
cache: dict[str, list[int]],
) -> dict[str, object]:
def text(value: str) -> str:
return _truncate_text(
self.encoding,
value,
text_token_limit,
cache,
)
return {
"id": str(candidate.document.id),
"arxiv_id": candidate.document.arxiv_id,
"title": text(candidate.document.title or candidate.document.original_filename),
"synopsis": text(
candidate.description
or candidate.document.abstract
or candidate.document.title
or ""
),
"prior_reason": text(prior_reason),
"signals": list(candidate.signals),
"fts_match": candidate.fts_match,
"lexical_rank": round(candidate.lexical_rank, 8),
}
def _comparison_batches(
self,
pool: Sequence[tuple[CandidateDocument, str]],
) -> list[_CatalogBatch]:
limit = self.settings.catalog_batch_token_limit
maximum_batch_size = self.settings.document_limit * 4
batches: list[_CatalogBatch] = []
offset = 0
while offset < len(pool):
remaining = len(pool) - offset
if remaining == 1:
candidate, reason = pool[offset]
payload = self._comparison_payload(
candidate,
reason,
text_token_limit=COMPARISON_TEXT_TOKEN_FLOOR,
cache={},
)
if _wrapped_token_count(self.encoding, [payload]) > limit:
raise ValueError(
"catalog batch token limit cannot fit a minimal reduction candidate"
)
batches.append(_CatalogBatch((candidate,), (payload,)))
break
maximum_size = min(maximum_batch_size, remaining)
def payloads(
size: int,
text_limit: int,
start: int = offset,
) -> list[dict[str, object]]:
cache: dict[str, list[int]] = {}
return [
self._comparison_payload(
candidate,
reason,
text_token_limit=text_limit,
cache=cache,
)
for candidate, reason in pool[start : start + size]
]
low = 2
high = maximum_size
fitting_size = 0
while low <= high:
middle = (low + high) // 2
if (
_wrapped_token_count(
self.encoding,
payloads(middle, COMPARISON_TEXT_TOKEN_FLOOR),
)
<= limit
):
fitting_size = middle
low = middle + 1
else:
high = middle - 1
if fitting_size < 2:
raise ValueError(
"catalog batch token limit cannot fit two minimal reduction candidates"
)
low = COMPARISON_TEXT_TOKEN_FLOOR
high = COMPARISON_TEXT_TOKEN_LIMIT
text_limit = COMPARISON_TEXT_TOKEN_FLOOR
while low <= high:
middle = (low + high) // 2
if (
_wrapped_token_count(
self.encoding,
payloads(fitting_size, middle),
)
<= limit
):
text_limit = middle
low = middle + 1
else:
high = middle - 1
batch_pool = pool[offset : offset + fitting_size]
batches.append(
_CatalogBatch(
tuple(candidate for candidate, _ in batch_pool),
tuple(payloads(fitting_size, text_limit)),
)
)
offset += fitting_size
return batches
async def _select_batch(
self,
question: str,
batch: _CatalogBatch,
*,
phase: str,
selection_limit: int,
) -> list[tuple[CandidateDocument, str]]:
candidates = batch.candidates
if len(candidates) == 1 and phase == "reduce":
return [
(candidate, "Retained by complete-catalog reduction.") for candidate in candidates
]
payload_json = _canonical_json(batch.payload)
selection = await self.llm.structured(
CandidateSelection,
UNTRUSTED_DOCUMENT_SYSTEM
+ f"\nReason over every supplied catalog entry. Select at most {selection_limit} "
"documents "
"likely to contain answer evidence. Lexical and exact-match fields are ranking "
"signals only; an entry without those signals remains eligible. "
"Prefer documents marked fts_match when relevance is otherwise equal.",
f"Question: {question}\nCatalog {phase} batch:\n"
+ wrap_untrusted_document(payload_json),
thinking=True,
stage=ModelCallStage.query_document_select,
)
allowed = {candidate.document.id: candidate for candidate in candidates}
result: list[tuple[CandidateDocument, str]] = []
for document_id in selection.document_ids:
candidate = allowed.get(document_id)
if candidate is None or candidate.document.id in {
item[0].document.id for item in result
}:
continue
result.append(
(
candidate,
selection.reasons.get(
str(document_id),
"Selected by complete-catalog document reasoning.",
)[:2_000],
)
)
if len(result) == selection_limit:
break
return result
async def select_ranked(
self,
question: str,
candidates: list[CandidateDocument],
) -> list[RankedDocument]:
if not candidates:
return []
if len(candidates) <= self.settings.document_limit:
return [
RankedDocument(
candidate.document,
index,
candidate.signals,
"Eligible catalog contains at most eight documents.",
)
for index, candidate in enumerate(candidates, 1)
]
mapped = [
item
for batch_result in await _gather_or_cancel(
[
lambda batch=batch: self._select_batch(
question,
batch,
phase="map",
selection_limit=self.settings.document_limit,
)
for batch in self._batches(candidates)
],
self.catalog_routing_limiter,
)
for item in batch_result
]
deduplicated: dict[uuid.UUID, tuple[CandidateDocument, str]] = {}
for candidate, reason in mapped:
deduplicated.setdefault(candidate.document.id, (candidate, reason))
pool = list(deduplicated.values())
while len(pool) > self.settings.document_limit:
reduced = [
item
for batch_result in await _gather_or_cancel(
[
lambda batch=batch: self._select_batch(
question,
batch,
phase="reduce",
selection_limit=min(
self.settings.document_limit,
len(batch.candidates) - 1,
),
)
for batch in self._comparison_batches(pool)
],
self.catalog_routing_limiter,
)
for item in batch_result
]
next_pool: dict[uuid.UUID, tuple[CandidateDocument, str]] = {}
for candidate, reason in reduced:
next_pool.setdefault(candidate.document.id, (candidate, reason))
if len(next_pool) >= len(pool):
raise AssertionError("catalog reduction did not shrink its candidate pool")
pool = list(next_pool.values())
return [
RankedDocument(candidate.document, rank, candidate.signals, reason)
for rank, (candidate, reason) in enumerate(pool, 1)
]
async def select(
self,
question: str,
candidates: list[CandidateDocument],
) -> list[Document]:
return [item.document for item in await self.select_ranked(question, candidates)]
@dataclass(frozen=True)
class _NodeView:
node_id: str
title: str
page_start: int
page_end: int
direct_summary: str
subtree_summary: str
parent_id: str | None
depth: int
section_path: tuple[str, ...]
children: tuple[str, ...]
@dataclass(frozen=True)
class _ArtifactView:
description: str
nodes: dict[str, _NodeView]
roots: tuple[str, ...]
pages: dict[int, str]
index_digest: str
configuration_hash: str | None
@dataclass(frozen=True)
class _SelectedNode:
document_id: uuid.UUID
node: _NodeView
reason: str
class PageIndexRetriever:
def __init__(self, settings: Settings, store: ObjectStore, llm: StructuredLLM) -> None:
self.settings = settings
self.store = store
self.llm = llm
self.encoding = tiktoken.get_encoding("cl100k_base")
@staticmethod
def _node_from_v2(item: DerivedNode) -> _NodeView:
node = item.node
return _NodeView(
node_id=node.node_id,
title=node.title,
page_start=node.subtree_page_range.page_start,
page_end=node.subtree_page_range.page_end,
direct_summary=node.direct_summary,
subtree_summary=node.subtree_summary,
parent_id=item.parent_id,
depth=item.depth,
section_path=item.section_path,
children=tuple(child.node_id for child in node.children),
)
async def _artifact(
self,
session: AsyncSession,
document: Document,
index_version_id: uuid.UUID | None = None,
) -> _ArtifactView:
selected_version_id = index_version_id or document.active_index_version_id
if selected_version_id is None:
raise ValueError(f"document {document.id} has no active index")
version = await session.get(IndexVersion, selected_version_id)
if version is None:
raise ValueError(f"index {selected_version_id} is missing")
if version.document_id != document.id:
raise ValueError(
f"index {selected_version_id} does not belong to document {document.id}"
)
if version.artifact_schema_version == 2:
if version.manifest_object_key is None or version.manifest_sha256 is None:
raise ValueError("PageIndex v2 version has no manifest")
loaded = await load_manifest_v2(
self.store,
version.manifest_object_key,
version.manifest_sha256,
)
derived = derive_nodes(loaded.manifest)
nodes = {item.node.node_id: self._node_from_v2(item) for item in derived}
roots = tuple(node.node_id for node in loaded.manifest.tree)
return _ArtifactView(
description=loaded.manifest.description,
nodes=nodes,
roots=roots,
pages={page: metric.text for page, metric in loaded.pages.items()},
index_digest=version.manifest_sha256,
configuration_hash=version.configuration_hash,
)
raw = await self.store.get_bytes(version.artifact_object_key)
if hashlib.sha256(raw).hexdigest() != version.artifact_sha256:
raise ValueError(f"artifact checksum mismatch for document {document.id}")
value: object = json.loads(raw)
if not isinstance(value, dict):
raise ValueError("invalid PageIndex v1 artifact")
artifact = cast(dict[str, Any], value)
if artifact.get("schema_version") != 1:
raise ValueError("unsupported PageIndex artifact schema")
raw_tree = artifact.get("tree")
raw_pages = artifact.get("pages")
if not isinstance(raw_tree, list) or not isinstance(raw_pages, list):
raise ValueError("invalid PageIndex v1 artifact")
nodes: dict[str, _NodeView] = {}
for raw_node in cast(list[dict[str, Any]], raw_tree):
node_id = str(raw_node["node_id"])
start = int(raw_node["page_start"])
end = int(raw_node["page_end"])
title = str(raw_node["title"])
summary = str(raw_node.get("summary") or title)
nodes[node_id] = _NodeView(
node_id=node_id,
title=title,
page_start=start,
page_end=end,
direct_summary=summary,
subtree_summary=summary,
parent_id=None,
depth=0,
section_path=(title,),
children=(),
)
pages = {
int(page["page"]): str(page["text"]) for page in cast(list[dict[str, Any]], raw_pages)
}
return _ArtifactView(
description=str(artifact.get("description") or ""),
nodes=nodes,
roots=tuple(nodes),
pages=pages,
index_digest=version.artifact_sha256,
configuration_hash=version.configuration_hash,
)
@staticmethod
def _coerce_artifact(value: object) -> _ArtifactView:
if isinstance(value, _ArtifactView):
return value
if not isinstance(value, dict):
raise ValueError("invalid PageIndex artifact view")
artifact = cast(dict[str, Any], value)
raw_tree = artifact.get("tree")
raw_pages = artifact.get("pages")
if not isinstance(raw_tree, list) or not isinstance(raw_pages, list):
raise ValueError("invalid PageIndex artifact view")
nodes: dict[str, _NodeView] = {}
for raw in cast(list[dict[str, Any]], raw_tree):
node_id = str(raw["node_id"])
title = str(raw.get("title") or node_id)
summary = str(raw.get("summary") or title)
nodes[node_id] = _NodeView(
node_id=node_id,
title=title,
page_start=int(raw["page_start"]),
page_end=int(raw["page_end"]),
direct_summary=summary,
subtree_summary=summary,
parent_id=None,
depth=0,
section_path=(title,),
children=(),
)
return _ArtifactView(
description=str(artifact.get("description") or ""),
nodes=nodes,
roots=tuple(nodes),
pages={
int(page["page"]): str(page["text"])
for page in cast(list[dict[str, Any]], raw_pages)
},
index_digest="legacy-v1",
configuration_hash=None,
)
def _tree_node_payload(
self,
artifact: _ArtifactView,
node_id: str,
*,
maximum_depth: int,
used: set[str],
text_token_limit: int,
text_cache: dict[str, list[int]],
visible_ids: set[str],
) -> dict[str, object]:
node = artifact.nodes[node_id]
visible_ids.add(node.node_id)
children = (
[
self._tree_node_payload(
artifact,
child,
maximum_depth=maximum_depth,
used=used,
text_token_limit=text_token_limit,
text_cache=text_cache,
visible_ids=visible_ids,
)
for child in node.children
]
if node.depth < maximum_depth
else []