Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions backend/src/sentra/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,10 @@ class RetrievedChunk(BaseModel):
"""

aktenzeichen: str
# Which document, where the Aktenzeichen is empty: the harness numbers the
# retrieved documents the way the answer does, by Aktenzeichen or else by
# file (#280).
source_file: str = ""
section_title: str
chunk_index: int
score: float
Expand All @@ -392,6 +396,7 @@ class RetrievedChunk(BaseModel):
def from_domain(cls, hit: domain.Hit) -> "RetrievedChunk":
return cls(
aktenzeichen=hit.aktenzeichen,
source_file=hit.source_file,
section_title=hit.section_title,
chunk_index=hit.chunk_index,
score=hit.score,
Expand Down
15 changes: 13 additions & 2 deletions backend/src/sentra/rag/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,17 @@ def __call__(
}


def document_key(hit: Hit) -> str:
"""What tells one document from another among the hits.

The Aktenzeichen where there is one, so two files of the same paper stay
one source. The file name where there is none: 88 indexed documents (the
Aktueller Begriff and PE papers, and some EU ones) carry an empty
Aktenzeichen, and keyed on that they all became a single source (#280).
"""
return hit.aktenzeichen or hit.source_file


def source_numbers(hits: list[Hit]) -> dict[str, int]:
"""The number each document is cited by: its order of first appearance.

Expand All @@ -87,7 +98,7 @@ def source_numbers(hits: list[Hit]) -> dict[str, int]:
"""
numbers: dict[str, int] = {}
for hit in hits:
numbers.setdefault(hit.aktenzeichen, len(numbers) + 1)
numbers.setdefault(document_key(hit), len(numbers) + 1)
return numbers


Expand Down Expand Up @@ -122,7 +133,7 @@ def format_context(hits: list[Hit]) -> str:
parts = []
for hit in hits:
header = (
f"[Quelle {numbers[hit.aktenzeichen]}: {hit.aktenzeichen}, "
f"[Quelle {numbers[document_key(hit)]}: {document_key(hit)}, "
f"Abschnitt: {hit.section_title}"
)
location = format_location(hit)
Expand Down
11 changes: 6 additions & 5 deletions backend/src/sentra/services/explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
AnswerGenerator,
AnswerMethod,
cited_numbers,
document_key,
format_context,
source_numbers,
)
Expand All @@ -39,9 +40,9 @@ def _aggregate_docs(hits: list[Hit], top_k: int) -> list[ScoredDocument]:
"""Aggregate chunk-level hits into unique documents (best score wins)."""
best: dict[str, Hit] = {}
for hit in hits:
current = best.get(hit.aktenzeichen)
current = best.get(document_key(hit))
if current is None or hit.score > current.score:
best[hit.aktenzeichen] = hit
best[document_key(hit)] = hit

ranked = sorted(best.values(), key=lambda h: h.score, reverse=True)
return [
Expand Down Expand Up @@ -69,9 +70,9 @@ def _build_source_refs(hits: list[Hit]) -> list[SourceRef]:
seen: set[str] = set()
refs: list[SourceRef] = []
for hit in hits:
if hit.aktenzeichen in seen:
if document_key(hit) in seen:
continue
seen.add(hit.aktenzeichen)
seen.add(document_key(hit))
refs.append(
SourceRef(
aktenzeichen=hit.aktenzeichen,
Expand All @@ -83,7 +84,7 @@ def _build_source_refs(hits: list[Hit]) -> list[SourceRef]:
# which is the passage [n] stands for. See SourceRef.
page=hit.page_from,
paragraph=hit.paragraph_from,
nummer=numbers[hit.aktenzeichen],
nummer=numbers[document_key(hit)],
)
)
return refs
Expand Down
47 changes: 47 additions & 0 deletions backend/tests/test_cited_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,50 @@ def test_the_context_the_model_saw_is_numbered(self):
_, generator = _answer("[1]")

assert f"[Quelle 1: {AZ_A}" in generator.context


class TestDocumentsWithoutAnAktenzeichen:
"""88 indexed documents have none, and keyed on the empty string they all
became one source (#280). They are told apart by their file now."""

def _ab(self, name, score):
h = hit("", score)
h.source_file = name
h.title = f"Aktueller Begriff {name}"
return h

def test_two_of_them_are_two_sources(self):
hits = [self._ab("AB 04-24.pdf", 0.9), hit(AZ_A, 0.8), self._ab("AB 10-23.pdf", 0.7)]

assert source_numbers(hits) == {"AB 04-24.pdf": 1, AZ_A: 2, "AB 10-23.pdf": 3}

def test_the_model_reads_the_file_name_in_their_header(self):
out = format_context([self._ab("AB 04-24.pdf", 0.9)])

assert "[Quelle 1: AB 04-24.pdf" in out

def test_an_answer_citing_the_second_gets_the_second(self):
generator = _Generator("Laut [3] gilt das.")
hits = [self._ab("AB 04-24.pdf", 0.9), hit(AZ_A, 0.8), self._ab("AB 10-23.pdf", 0.7)]

class Store:
def search(self, **kwargs):
return hits

result = answer_question(
query="Frage?",
date_from=None,
date_to=None,
top_k=10,
store=Store(),
embedder=_Embedder(),
generator=generator,
)

assert [(s.source_file, s.nummer) for s in result.sources] == [("AB 10-23.pdf", 3)]

def test_two_files_of_one_paper_are_still_one_source(self):
first, second = hit(AZ_A, 0.9), hit(AZ_A, 0.8)
second.source_file = "WD 3-029-23 Anlage.pdf"

assert source_numbers([first, second]) == {AZ_A: 1}
2 changes: 2 additions & 0 deletions backend/tests/test_debug_payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@ def test_a_chunk_carries_what_a_check_needs(self, client_factory, path):

assert set(body["hits"][0]) == {
"aktenzeichen",
# Since #280: tells documents without an Aktenzeichen apart.
"source_file",
"section_title",
"chunk_index",
"score",
Expand Down
10 changes: 10 additions & 0 deletions backend/tests/test_explorer_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,13 @@ def test_the_location_is_german_like_the_prompt_around_it(self):

assert "page" not in out.lower()
assert "Seite 2" in out


def test_documents_without_an_aktenzeichen_are_not_merged_in_the_document_list():
"""The same grouping as the sources of an answer (#280)."""
first, second = hit("", 0.9), hit("", 0.8)
first.source_file, second.source_file = "AB 04-24.pdf", "AB 10-23.pdf"

docs = _aggregate_docs([first, second], top_k=10)

assert [d.source_file for d in docs] == ["AB 04-24.pdf", "AB 10-23.pdf"]
11 changes: 8 additions & 3 deletions evaluation/src/sentra_eval/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,14 @@ def _retrieved_numbers(hits: list) -> list[int]:
"""
seen: dict[str, int] = {}
for hit in hits:
az = hit.get("aktenzeichen") if isinstance(hit, dict) else None
if az:
seen.setdefault(az, len(seen) + 1)
if not isinstance(hit, dict):
continue
# Keyed as SENTRA keys them: by Aktenzeichen, or by file for the
# documents without one (#280). Older payloads carry no file and fall
# back to the Aktenzeichen alone, as before.
key = hit.get("aktenzeichen") or hit.get("source_file")
if key:
seen.setdefault(key, len(seen) + 1)
return list(seen.values())


Expand Down
15 changes: 15 additions & 0 deletions evaluation/tests/test_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,3 +684,18 @@ def test_without_a_debug_payload_the_sources_are_what_was_given(self):

assert outcome.belege["anzahl_abgerufen"] == 3
assert outcome.belege["quellen_ohne_marker"] == [2, 3]


def test_retrieved_documents_without_an_aktenzeichen_are_counted_apart():
"""Numbered as SENTRA numbers them: by Aktenzeichen, else by file (#280)."""
response = _cited_only("Laut [1].", ("A", 1))
response["hits"] = [
{"aktenzeichen": "A"},
{"aktenzeichen": "", "source_file": "AB 04-24.pdf"},
{"aktenzeichen": "", "source_file": "AB 10-23.pdf"},
]

outcome = checks.marker_ausrichtung(response)

assert outcome.belege["anzahl_abgerufen"] == 3
assert outcome.belege["quellen_ohne_marker"] == [2, 3]
Loading