Repository navigation
Expand file tree
/
Copy pathdocument_notes.py
More file actions
447 lines (372 loc) · 13.4 KB
/
Copy pathdocument_notes.py
File metadata and controls
447 lines (372 loc) · 13.4 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
"""Shared reading, note-taking and citation checks for document tools.
Several registered tools read full documents by breaking them into
passage groups, asking the model for traceable notes, and checking the
passage citations. This private implementation prevents tools from
importing one another for reusable reading algorithms.
Key Features
------------
- **Deterministic planning**
Group passages by estimated token sizes.
- **Checked model notes**
Keep only notes citing passages included in their reading part.
- **Reusable model orchestration**
Report progress and trace notes using the caller's context.
Module Structure
----------------
- ``NOTHING``
Sentinel in a model reply when no relevant notes are found.
- ``plan_parts``, ``notes_prompt`` and ``clean_notes``
Group passages, construct prompts, and validate notes.
- ``answer_citations``
Find invalid passage citations in a generated answer.
- ``quote_citations``
Move the citation of a quoted phrase to the passage that contains it.
- ``take_notes``
Read each part using the caller's model and tracing callbacks.
Examples
--------
>>> from kilin.tools._shared.document_notes import clean_notes
>>> clean_notes("- Fact [2]", [1, 2])
['- Fact [2]']
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
import re
from time import perf_counter
from typing import Final
from kilin._model_completion import IncompleteModelResponse
from kilin.chunking import Chunk
from kilin.retrievals.document_reading import estimate_tokens
from kilin.tools._contract import ToolContext
from kilin.tools._shared.citations import inspect_citations
__all__ = [
"NOTHING",
"answer_citations",
"clean_notes",
"notes_prompt",
"plan_parts",
"quote_citations",
"take_notes",
]
NOTHING: Final[str] = "NOTHING"
# A citation group such as [3], [3, 5], or [3-5].
_CITATION_GROUP: Final[re.Pattern[str]] = re.compile(
r"\[\s*(\d[^\[\]\r\n]*)\]"
)
# A phrase in straight or curly double quotes.
_QUOTE: Final[re.Pattern[str]] = re.compile(r'["“]([^"“”]+)["”]')
# A sentence ends at ., !, or ? followed by space, or at a line break.
_SENTENCE_END: Final[re.Pattern[str]] = re.compile(r"(?<=[.!?])\s+|\n+")
# Fewer words than this are too common to place a quote ("BRAPH").
_QUOTE_MIN_WORDS: Final[int] = 3
def plan_parts(chunks: Sequence[Chunk], part_tokens: int) -> list[list[int]]:
"""Pack consecutive passages into parts by estimated tokens.
Parameters
----------
chunks: Sequence[Chunk]
The document's passages, in order.
part_tokens: int
Estimated tokens per part; a larger passage gets its own part.
Returns
-------
list[list[int]]
Passage indices per part, in order.
"""
parts: list[list[int]] = []
used = 0
for index, chunk in enumerate(chunks):
size = estimate_tokens(chunk.text)
if parts and used + size <= part_tokens:
parts[-1].append(index)
used += size
else:
parts.append([index])
used = size
return parts
def notes_prompt(
question: str,
name: str,
part: int,
parts: int,
passages: Sequence[tuple[int, str]],
) -> tuple[str, str]:
"""Return the prompts that take notes on one part.
Parameters
----------
question: str
The user's question.
name: str
The document's name.
part: int
This part's number, from one.
parts: int
Number of parts.
passages: Sequence[tuple[int, str]]
Passage numbers and texts of this part.
Returns
-------
tuple[str, str]
System prompt and user prompt.
"""
system = (
"You read one part of a document for KíLín and take notes. You do "
"not answer the question yet. You reply with short bullet notes "
"only."
)
text = "\n\n".join(
f"[{number}] {body.strip()}" for number, body in passages
)
user = f"""Question: {question}
Below is part {part} of {parts} of {name}. Its passages are numbered.
{text}
Write bullet notes with every fact in this part that helps answer the
question, each ending with its passage number, for example
"- The software was written in Python 3.11 [12]". Copy names, numbers, and
versions exactly. If this part has nothing relevant, reply exactly:
{NOTHING}"""
return system, user
def clean_notes(reply: str, numbers: Sequence[int]) -> list[str]:
"""Keep note lines that cite passages of their part.
Parameters
----------
reply: str
The model's notes.
numbers: Sequence[int]
Passage numbers in the part.
Returns
-------
list[str]
Note lines, each citing at least one passage of the part; empty for
``NOTHING`` or notes without valid citations.
"""
allowed = set(numbers)
kept: list[str] = []
for line in reply.splitlines():
line = line.strip().lstrip("-*• ").strip()
cited = inspect_citations(line, max(allowed, default=0))
if (
line and cited.valid and cited.valid <= allowed
and not cited.invalid_numbers and not cited.invalid_groups
):
kept.append(f"- {line}")
return kept
def answer_citations(answer: str, passages: int) -> list[int]:
"""Return citation numbers in an answer that match no passage.
Parameters
----------
answer: str
The final answer.
passages: int
Number of passages in the document.
Returns
-------
list[int]
Sorted invalid citation numbers; empty when all are valid.
"""
return list(inspect_citations(answer, passages).invalid_numbers)
def quote_citations(
answer: str, passages: Mapping[int, str]
) -> tuple[str, dict[str, int]]:
"""Move the citation of a quoted phrase to the passage that contains it.
Small models cite a neighbouring number ([1] for [10]). A sentence that
quotes a phrase of at least three words, and has one citation group,
is checked: when no cited passage contains the phrase, and exactly one
other passage the model was given does, the group cites that passage
instead. Text is compared ignoring case, spacing, and line-end
hyphenation.
Parameters
----------
answer: str
The generated answer.
passages: Mapping[int, str]
The citation numbers the model was given, with their passage text.
Returns
-------
tuple[str, dict[str, int]]
The answer with moved citations, and counts: ``moved`` citation
groups, and ``unplaced`` quotes that no given passage contains.
"""
texts = {number: _plain(text) for number, text in passages.items()}
counts = {"moved": 0, "unplaced": 0}
pieces: list[str] = []
position = 0
for end in [*_SENTENCE_END.finditer(answer), None]:
stop = end.start() if end is not None else len(answer)
sentence = answer[position:stop]
groups = list(_CITATION_GROUP.finditer(sentence))
quotes = [
_plain(quote)
for quote in _QUOTE.findall(sentence)
if len(quote.split()) >= _QUOTE_MIN_WORDS
]
if quotes and len(groups) == 1:
citation = inspect_citations(
groups[0].group(0), max(passages, default=0)
)
if (
not citation.valid or citation.invalid_numbers
or citation.invalid_groups
):
pieces.append(sentence)
if end is not None:
pieces.append(end.group(0))
position = end.end()
continue
cited = citation.valid
if not any(
quote in texts.get(number, "")
for quote in quotes for number in cited
):
found = {
number
for quote in quotes
for number, text in texts.items()
if quote in text
}
if len(found) == 1:
group = groups[0]
sentence = (
sentence[:group.start()]
+ f"[{found.pop()}]"
+ sentence[group.end():]
)
counts["moved"] += 1
elif not found:
counts["unplaced"] += len(quotes)
pieces.append(sentence)
if end is not None:
pieces.append(end.group(0))
position = end.end()
return "".join(pieces), counts
def _plain(text: str) -> str:
"""Return text for quote matching: no line-end hyphens, one space.
Parameters
----------
text: str
Passage or quoted text.
Returns
-------
str
Casefolded text with single spaces and words rejoined across
line-end hyphens ("advan- tage" becomes "advantage").
"""
text = re.sub(r"(\w)-\s+(\w)", r"\1\2", text)
text = text.replace("’", "'")
return " ".join(text.split()).casefold()
def take_notes(
task: str,
name: str,
texts: Sequence[str],
parts: Sequence[Sequence[int]],
context: ToolContext,
*,
what: str = "document",
whole: bool = True,
failures: list[dict[str, object]] | None = None,
) -> list[tuple[int, list[str]]]:
"""Take checked notes on each part of a document with the model.
Parameters
----------
task: str
What the notes are for: the user's question, or an instruction
such as the sections of a summary.
name: str
The document's name.
texts: Sequence[str]
Every passage's text; passage ``n`` is ``texts[n - 1]``.
parts: Sequence[Sequence[int]]
Passage indices per part, in reading order.
context: ToolContext
KíLín's services (``ask_model``, ``progress``, ``trace``).
what: str, optional
What is read, for progress messages: "paper", "file",
"function", ... Defaults to ``"document"``.
whole: bool, optional
True when the parts cover the whole document; False for a quick
reading of its most relevant passages. Defaults to ``True``.
failures: list[dict[str, object]] | None, optional
Collect independent failed parts and continue when supplied. Failed
parts are omitted from notes, never represented as NOTHING. None
retains strict failure propagation.
Returns
-------
list[tuple[int, list[str]]]
Part numbers with checked note lines. Explicit NOTHING replies
give empty parts. Failed calls or unparseable notes are omitted
when a failure collector is supplied; otherwise they raise
``IncompleteModelResponse``. They never imply a negative result.
Raises
------
IncompleteModelResponse
If a part returns incomplete or invalid notes and ``failures``
is ``None``. Supplying a collector records and skips that part.
"""
notes: list[tuple[int, list[str]]] = []
for number, part in enumerate(parts, start=1):
if not whole:
message = f"Reading the most relevant passages: {name}"
elif len(parts) == 1:
message = f"Reading the whole {what}: {name}"
else:
message = (
f"Reading the whole {what} (part {number} of "
f"{len(parts)}): {name}"
)
context.progress(message, current=number, total=len(parts))
started = perf_counter()
system, prompt = notes_prompt(
task,
name,
number,
len(parts),
[(index + 1, texts[index]) for index in part],
)
try:
reply = context.ask_model(system, prompt, None)
lines = clean_notes(reply, [index + 1 for index in part])
if not lines and reply.strip() != NOTHING:
raise IncompleteModelResponse(
"The model returned neither cited notes nor NOTHING.",
reason="invalid_output", raw_text=reply,
)
except IncompleteModelResponse as error:
if failures is None:
raise
failure = {
"item": f"{name}, reading part {number}",
"part": number, "passages": len(part),
"passage_numbers": [index + 1 for index in part],
**error.to_dict(),
}
failures.append(failure)
context.trace.emit(
"tool.part.failed", component="tool", data=failure,
turn_id=context.trace_turn_id,
)
continue
except Exception as error:
context.trace.emit(
"tool.part.failed", component="tool",
data={"part": number, "notes": 0, "error": str(error)},
turn_id=context.trace_turn_id,
)
raise IncompleteModelResponse(
f"Document reading failed in part {number}: {error}",
reason="model_error",
) from error
notes.append((number, lines))
data: dict[str, object] = {
"part": number,
"passages": [index + 1 for index in (part[0], part[-1])],
"notes": len(lines),
"seconds": round(perf_counter() - started, 2),
}
if context.trace.include_content:
data["raw"] = reply
context.trace.emit(
"tool.part.notes",
component="tool",
data=data,
turn_id=context.trace_turn_id,
)
return notes