llama-index-postprocessor-needlepath 0.1.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.
- llama_index/postprocessor/needlepath/__init__.py +3 -0
- llama_index/postprocessor/needlepath/base.py +408 -0
- llama_index/postprocessor/needlepath/version.py +3 -0
- llama_index_postprocessor_needlepath-0.1.0.dist-info/METADATA +125 -0
- llama_index_postprocessor_needlepath-0.1.0.dist-info/RECORD +7 -0
- llama_index_postprocessor_needlepath-0.1.0.dist-info/WHEEL +4 -0
- llama_index_postprocessor_needlepath-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
"""``NeedlepathPostprocessor`` — a ``BaseNodePostprocessor`` over retrieved nodes.
|
|
2
|
+
|
|
3
|
+
This is a RAG-retrieval seam. It never sees tool outputs, so it exercises the
|
|
4
|
+
weakest of our use cases (§8.1 says so plainly: a coverage checkbox, not a growth
|
|
5
|
+
bet). It is here because LlamaIndex is where a large number of developers already
|
|
6
|
+
have a postprocessor slot, and an integration that does not exist cannot be
|
|
7
|
+
evaluated.
|
|
8
|
+
|
|
9
|
+
What it does: given the retrieved nodes and the query, keep the nodes that carry
|
|
10
|
+
the answer and replace each one's text with the part of it that does. What it
|
|
11
|
+
never does: raise, or return fewer nodes than it was given when anything at all
|
|
12
|
+
went wrong.
|
|
13
|
+
|
|
14
|
+
Two LlamaIndex-specific decisions worth reading before you deploy it:
|
|
15
|
+
|
|
16
|
+
**Scores are not overwritten by default.** A reranker replaces
|
|
17
|
+
``NodeWithScore.score`` with its own. Ours is not calibrated against your
|
|
18
|
+
retriever's similarity, and silently substituting one for the other corrupts any
|
|
19
|
+
downstream threshold or ``similarity_cutoff``. Set ``update_scores=True`` if you
|
|
20
|
+
want reranker-like behaviour and know what your thresholds mean.
|
|
21
|
+
|
|
22
|
+
**Provenance metadata is excluded from what the model sees.** Node metadata is
|
|
23
|
+
interpolated into the prompt under ``MetadataMode.LLM`` and into embeddings under
|
|
24
|
+
``MetadataMode.EMBED``. Writing debug keys into ``node.metadata`` without
|
|
25
|
+
excluding them would put them in front of the model. Every key this package adds
|
|
26
|
+
is added to ``excluded_llm_metadata_keys`` and ``excluded_embed_metadata_keys``
|
|
27
|
+
on the copy.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
from typing import Any
|
|
33
|
+
|
|
34
|
+
from llama_index.core.bridge.pydantic import Field, PrivateAttr
|
|
35
|
+
from llama_index.core.postprocessor.types import BaseNodePostprocessor
|
|
36
|
+
from llama_index.core.schema import MetadataMode, NodeWithScore, QueryBundle
|
|
37
|
+
|
|
38
|
+
from needlepath import (
|
|
39
|
+
AsyncNeedlepathClient,
|
|
40
|
+
ContextRecord,
|
|
41
|
+
NeedlepathClient,
|
|
42
|
+
Reason,
|
|
43
|
+
RecordKind,
|
|
44
|
+
SelectionResult,
|
|
45
|
+
SelectionStats,
|
|
46
|
+
TaskSpec,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
from .version import __version__
|
|
50
|
+
|
|
51
|
+
USER_AGENT_SUFFIX = f"llama-index-postprocessor-needlepath/{__version__}"
|
|
52
|
+
|
|
53
|
+
#: Metadata keys this package writes onto a returned node. All of them are
|
|
54
|
+
#: excluded from the LLM and embedding views — see the module docstring.
|
|
55
|
+
METADATA_PREFIX = "needlepath_"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class NeedlepathPostprocessor(BaseNodePostprocessor):
|
|
59
|
+
"""Select and excerpt retrieved nodes against the query.
|
|
60
|
+
|
|
61
|
+
::
|
|
62
|
+
|
|
63
|
+
from llama_index.postprocessor.needlepath import NeedlepathPostprocessor
|
|
64
|
+
|
|
65
|
+
query_engine = index.as_query_engine(
|
|
66
|
+
node_postprocessors=[
|
|
67
|
+
NeedlepathPostprocessor(operating_point="np-2026-07-r2")
|
|
68
|
+
],
|
|
69
|
+
)
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
operating_point: str | None = Field(
|
|
73
|
+
default=None,
|
|
74
|
+
description="Immutable operating-point label, e.g. 'np-2026-07-r2'. "
|
|
75
|
+
"Required here or via NEEDLEPATH_OPERATING_POINT.",
|
|
76
|
+
)
|
|
77
|
+
max_context_tokens: int = Field(
|
|
78
|
+
default=4000, description="Token budget for the selected context."
|
|
79
|
+
)
|
|
80
|
+
trigger_tokens: int = Field(
|
|
81
|
+
default=0,
|
|
82
|
+
description="Skip the call when the retrieved nodes are smaller than this. "
|
|
83
|
+
"0 means the max_context_tokens budget is the trigger.",
|
|
84
|
+
)
|
|
85
|
+
shadow: bool = Field(default=False, description="Measure and report; never change the nodes.")
|
|
86
|
+
enabled: bool = Field(default=True, description="Kill switch; needs no credentials.")
|
|
87
|
+
update_scores: bool = Field(
|
|
88
|
+
default=False,
|
|
89
|
+
description="Replace NodeWithScore.score with the selection score. Off by "
|
|
90
|
+
"default: the two are not on the same scale.",
|
|
91
|
+
)
|
|
92
|
+
preserve_input_order: bool = Field(
|
|
93
|
+
default=False,
|
|
94
|
+
description="Return kept nodes in retrieval order rather than the order the "
|
|
95
|
+
"service ranked them.",
|
|
96
|
+
)
|
|
97
|
+
excerpt: bool = Field(
|
|
98
|
+
default=True,
|
|
99
|
+
description="Replace each kept node's text with its excerpt. False keeps the "
|
|
100
|
+
"node whole and only filters.",
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
_client: Any = PrivateAttr(default=None)
|
|
104
|
+
_async_client: Any = PrivateAttr(default=None)
|
|
105
|
+
_stats: Any = PrivateAttr(default=None)
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
*,
|
|
110
|
+
operating_point: str | None = None,
|
|
111
|
+
max_context_tokens: int = 4000,
|
|
112
|
+
trigger_tokens: int = 0,
|
|
113
|
+
shadow: bool = False,
|
|
114
|
+
enabled: bool = True,
|
|
115
|
+
update_scores: bool = False,
|
|
116
|
+
preserve_input_order: bool = False,
|
|
117
|
+
excerpt: bool = True,
|
|
118
|
+
client: NeedlepathClient | None = None,
|
|
119
|
+
async_client: AsyncNeedlepathClient | None = None,
|
|
120
|
+
**client_kwargs: Any,
|
|
121
|
+
) -> None:
|
|
122
|
+
super().__init__(
|
|
123
|
+
operating_point=operating_point,
|
|
124
|
+
max_context_tokens=max_context_tokens,
|
|
125
|
+
trigger_tokens=trigger_tokens,
|
|
126
|
+
shadow=shadow,
|
|
127
|
+
enabled=enabled,
|
|
128
|
+
update_scores=update_scores,
|
|
129
|
+
preserve_input_order=preserve_input_order,
|
|
130
|
+
excerpt=excerpt,
|
|
131
|
+
)
|
|
132
|
+
self._stats = SelectionStats()
|
|
133
|
+
if not enabled:
|
|
134
|
+
self._client = client
|
|
135
|
+
self._async_client = async_client
|
|
136
|
+
return
|
|
137
|
+
kwargs = dict(client_kwargs)
|
|
138
|
+
kwargs.setdefault("user_agent_suffix", USER_AGENT_SUFFIX)
|
|
139
|
+
if operating_point is not None:
|
|
140
|
+
kwargs["operating_point"] = operating_point
|
|
141
|
+
kwargs["shadow"] = shadow
|
|
142
|
+
self._client = client or NeedlepathClient(**kwargs)
|
|
143
|
+
self._async_client = async_client or (
|
|
144
|
+
None if client is not None else AsyncNeedlepathClient(**kwargs)
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
@classmethod
|
|
148
|
+
def class_name(cls) -> str:
|
|
149
|
+
"""The serde key. ``to_dict()`` emits it, so it has to be stable."""
|
|
150
|
+
return "NeedlepathPostprocessor"
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def stats(self) -> SelectionStats:
|
|
154
|
+
"""Counters for a shadow report or a health check."""
|
|
155
|
+
return self._stats
|
|
156
|
+
|
|
157
|
+
# ------------------------------------------------------------------ #
|
|
158
|
+
|
|
159
|
+
def _postprocess_nodes(
|
|
160
|
+
self,
|
|
161
|
+
nodes: list[NodeWithScore],
|
|
162
|
+
query_bundle: QueryBundle | None = None,
|
|
163
|
+
) -> list[NodeWithScore]:
|
|
164
|
+
try:
|
|
165
|
+
plan = self._plan(nodes, query_bundle)
|
|
166
|
+
if plan is None:
|
|
167
|
+
return nodes
|
|
168
|
+
result = self._client.select(
|
|
169
|
+
records=plan["records"],
|
|
170
|
+
task=plan["task"],
|
|
171
|
+
max_context_tokens=self.max_context_tokens,
|
|
172
|
+
shadow=True if self.shadow else None,
|
|
173
|
+
)
|
|
174
|
+
return self._apply(nodes, plan, result)
|
|
175
|
+
except Exception: # noqa: BLE001 - see the class docstring's fail-open rule
|
|
176
|
+
# The core client never raises, so this catches OUR OWN defects — a
|
|
177
|
+
# node type nobody anticipated, an index slip, a framework minor that
|
|
178
|
+
# changed a field's type. A postprocessor that raises fails the whole
|
|
179
|
+
# query engine; returning the caller's nodes is byte-identical to not
|
|
180
|
+
# having installed this at all.
|
|
181
|
+
self._note(Reason.UNEXPECTED_ERROR)
|
|
182
|
+
return nodes
|
|
183
|
+
|
|
184
|
+
async def _apostprocess_nodes(
|
|
185
|
+
self,
|
|
186
|
+
nodes: list[NodeWithScore],
|
|
187
|
+
query_bundle: QueryBundle | None = None,
|
|
188
|
+
) -> list[NodeWithScore]:
|
|
189
|
+
"""Overridden rather than inherited.
|
|
190
|
+
|
|
191
|
+
The base class's default is ``asyncio.to_thread(self._postprocess_nodes,
|
|
192
|
+
…)``, which is correct but burns a thread per query on what is a network
|
|
193
|
+
call. Nine call sites in llama-index-core reach the async path, so this
|
|
194
|
+
is the one most query engines actually take.
|
|
195
|
+
"""
|
|
196
|
+
try:
|
|
197
|
+
return await self._apostprocess(nodes, query_bundle)
|
|
198
|
+
except Exception: # noqa: BLE001 - see `_postprocess_nodes`
|
|
199
|
+
self._note(Reason.UNEXPECTED_ERROR)
|
|
200
|
+
return nodes
|
|
201
|
+
|
|
202
|
+
async def _apostprocess(
|
|
203
|
+
self,
|
|
204
|
+
nodes: list[NodeWithScore],
|
|
205
|
+
query_bundle: QueryBundle | None,
|
|
206
|
+
) -> list[NodeWithScore]:
|
|
207
|
+
plan = self._plan(nodes, query_bundle)
|
|
208
|
+
if plan is None:
|
|
209
|
+
return nodes
|
|
210
|
+
if self._async_client is None:
|
|
211
|
+
import asyncio
|
|
212
|
+
|
|
213
|
+
loop = asyncio.get_running_loop()
|
|
214
|
+
result = await loop.run_in_executor(
|
|
215
|
+
None,
|
|
216
|
+
lambda: self._client.select(
|
|
217
|
+
records=plan["records"],
|
|
218
|
+
task=plan["task"],
|
|
219
|
+
max_context_tokens=self.max_context_tokens,
|
|
220
|
+
shadow=True if self.shadow else None,
|
|
221
|
+
),
|
|
222
|
+
)
|
|
223
|
+
else:
|
|
224
|
+
result = await self._async_client.select(
|
|
225
|
+
records=plan["records"],
|
|
226
|
+
task=plan["task"],
|
|
227
|
+
max_context_tokens=self.max_context_tokens,
|
|
228
|
+
shadow=True if self.shadow else None,
|
|
229
|
+
)
|
|
230
|
+
return self._apply(nodes, plan, result)
|
|
231
|
+
|
|
232
|
+
# ------------------------------------------------------------------ #
|
|
233
|
+
|
|
234
|
+
def _plan(
|
|
235
|
+
self, nodes: list[NodeWithScore], query_bundle: QueryBundle | None
|
|
236
|
+
) -> dict[str, Any] | None:
|
|
237
|
+
if not self.enabled or self._client is None or not nodes:
|
|
238
|
+
return None
|
|
239
|
+
if query_bundle is None or not str(query_bundle.query_str).strip():
|
|
240
|
+
# Every shipped reranker raises here. We do not: a postprocessor
|
|
241
|
+
# that raises turns "no query was supplied" into a failed query for
|
|
242
|
+
# the whole engine, and the fail-open rule is binding at a framework
|
|
243
|
+
# boundary. Passing the nodes through is the honest degradation.
|
|
244
|
+
self._note(Reason.UNSUPPORTED)
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
records: list[ContextRecord] = []
|
|
248
|
+
index_by_id: dict[str, int] = {}
|
|
249
|
+
for index, node in enumerate(nodes):
|
|
250
|
+
text = _node_text(node)
|
|
251
|
+
if not text.strip():
|
|
252
|
+
continue
|
|
253
|
+
record_id = f"n{index}"
|
|
254
|
+
index_by_id[record_id] = index
|
|
255
|
+
records.append(
|
|
256
|
+
ContextRecord(
|
|
257
|
+
text=text,
|
|
258
|
+
kind=RecordKind.EXTERNAL_DATA,
|
|
259
|
+
id=record_id,
|
|
260
|
+
title=_node_title(node),
|
|
261
|
+
source=_node_source(node),
|
|
262
|
+
importance=float(node.score) if node.score is not None else 0.0,
|
|
263
|
+
)
|
|
264
|
+
)
|
|
265
|
+
if not records:
|
|
266
|
+
self._note(Reason.NO_RECORDS)
|
|
267
|
+
return None
|
|
268
|
+
|
|
269
|
+
trigger = self.trigger_tokens or self.max_context_tokens
|
|
270
|
+
if sum(len(r.text) // 4 + 1 for r in records) <= trigger:
|
|
271
|
+
self._note(Reason.BELOW_TRIGGER)
|
|
272
|
+
return None
|
|
273
|
+
|
|
274
|
+
return {
|
|
275
|
+
"records": records,
|
|
276
|
+
"index_by_id": index_by_id,
|
|
277
|
+
"task": TaskSpec(prompt=str(query_bundle.query_str)),
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
def _apply(
|
|
281
|
+
self,
|
|
282
|
+
nodes: list[NodeWithScore],
|
|
283
|
+
plan: dict[str, Any],
|
|
284
|
+
result: SelectionResult,
|
|
285
|
+
) -> list[NodeWithScore]:
|
|
286
|
+
self._stats.record(result)
|
|
287
|
+
# `self.shadow` is belt and braces — the core client already declines a
|
|
288
|
+
# shadow result — enforced here, at the point of mutation.
|
|
289
|
+
if not result.applied or self.shadow or result.response is None:
|
|
290
|
+
return nodes
|
|
291
|
+
|
|
292
|
+
index_by_id: dict[str, int] = plan["index_by_id"]
|
|
293
|
+
# (input index, node) pairs. The index is carried explicitly rather than
|
|
294
|
+
# recovered later: `_rewrite` returns a *copy* for any node it changes,
|
|
295
|
+
# so object identity is not a key that survives this loop.
|
|
296
|
+
kept: list[Any] = []
|
|
297
|
+
seen: set = set()
|
|
298
|
+
for selected in result.response.selected:
|
|
299
|
+
index = index_by_id.get(selected.record_id)
|
|
300
|
+
if index is None:
|
|
301
|
+
# A record id we did not send. Nothing safe to do with it.
|
|
302
|
+
continue
|
|
303
|
+
if index in seen:
|
|
304
|
+
# A duplicate id in the response would otherwise duplicate the
|
|
305
|
+
# node in the context.
|
|
306
|
+
continue
|
|
307
|
+
seen.add(index)
|
|
308
|
+
kept.append((index, self._rewrite(nodes[index], selected, result)))
|
|
309
|
+
|
|
310
|
+
if not kept:
|
|
311
|
+
# Belt and braces: the core client already classifies an empty
|
|
312
|
+
# selection as a passthrough, so reaching here means every id came
|
|
313
|
+
# back unrecognized. Returning [] would hand the query engine no
|
|
314
|
+
# context at all.
|
|
315
|
+
return nodes
|
|
316
|
+
|
|
317
|
+
if self.preserve_input_order:
|
|
318
|
+
kept.sort(key=lambda pair: pair[0])
|
|
319
|
+
return [node for _index, node in kept]
|
|
320
|
+
|
|
321
|
+
def _rewrite(
|
|
322
|
+
self, original: NodeWithScore, selected: Any, result: SelectionResult
|
|
323
|
+
) -> NodeWithScore:
|
|
324
|
+
text = _node_text(original)
|
|
325
|
+
excerpt = selected.excerpt or ""
|
|
326
|
+
use_excerpt = self.excerpt and excerpt.strip() != "" and len(excerpt) < len(text)
|
|
327
|
+
if not use_excerpt and not self.update_scores:
|
|
328
|
+
# Nothing to change: hand back the caller's own object rather than a
|
|
329
|
+
# copy, so node identity survives for anything downstream that keys
|
|
330
|
+
# on it.
|
|
331
|
+
return original
|
|
332
|
+
|
|
333
|
+
node = original.node.model_copy(deep=True)
|
|
334
|
+
if use_excerpt:
|
|
335
|
+
node.set_content(str(excerpt))
|
|
336
|
+
metadata = dict(node.metadata or {})
|
|
337
|
+
additions = {
|
|
338
|
+
f"{METADATA_PREFIX}applied": True,
|
|
339
|
+
f"{METADATA_PREFIX}request_id": result.request_id,
|
|
340
|
+
f"{METADATA_PREFIX}score": float(selected.score),
|
|
341
|
+
f"{METADATA_PREFIX}excerpted": bool(use_excerpt),
|
|
342
|
+
}
|
|
343
|
+
metadata.update(additions)
|
|
344
|
+
node.metadata = metadata
|
|
345
|
+
# Keep provenance out of the prompt and out of the embedding. Node
|
|
346
|
+
# metadata is interpolated into both by default.
|
|
347
|
+
node.excluded_llm_metadata_keys = _with_keys(
|
|
348
|
+
getattr(node, "excluded_llm_metadata_keys", None), additions
|
|
349
|
+
)
|
|
350
|
+
node.excluded_embed_metadata_keys = _with_keys(
|
|
351
|
+
getattr(node, "excluded_embed_metadata_keys", None), additions
|
|
352
|
+
)
|
|
353
|
+
score = float(selected.score) if self.update_scores else original.score
|
|
354
|
+
return NodeWithScore(node=node, score=score)
|
|
355
|
+
|
|
356
|
+
def _note(self, reason: str) -> None:
|
|
357
|
+
self._stats.calls += 1
|
|
358
|
+
self._stats.passthrough += 1
|
|
359
|
+
self._stats.reasons[reason] = self._stats.reasons.get(reason, 0) + 1
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
# --------------------------------------------------------------------------- #
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _with_keys(existing: list[str] | None, additions: dict[str, Any]) -> list[str]:
|
|
366
|
+
keys = list(existing or [])
|
|
367
|
+
for key in additions:
|
|
368
|
+
if key not in keys:
|
|
369
|
+
keys.append(key)
|
|
370
|
+
return keys
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _node_text(node: NodeWithScore) -> str:
|
|
374
|
+
"""Raw text, for any ``BaseNode`` subclass.
|
|
375
|
+
|
|
376
|
+
``get_content`` is abstract on ``BaseNode`` and therefore always present;
|
|
377
|
+
``node.text`` exists only on ``TextNode`` and raises on the newer ``Node``.
|
|
378
|
+
``metadata_mode`` is passed explicitly because ``BaseNode`` declares its
|
|
379
|
+
default as ``ALL`` while ``TextNode`` overrides it to ``NONE``.
|
|
380
|
+
"""
|
|
381
|
+
try:
|
|
382
|
+
return node.node.get_content(metadata_mode=MetadataMode.NONE) or ""
|
|
383
|
+
except Exception: # noqa: BLE001 - a node type we have never met
|
|
384
|
+
return ""
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _node_title(node: NodeWithScore) -> str | None:
|
|
388
|
+
metadata = node.node.metadata or {}
|
|
389
|
+
for key in ("title", "file_name", "document_title", "section"):
|
|
390
|
+
value = metadata.get(key)
|
|
391
|
+
if isinstance(value, str) and value.strip():
|
|
392
|
+
return value[:120]
|
|
393
|
+
return None
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _node_source(node: NodeWithScore) -> str | None:
|
|
397
|
+
metadata = node.node.metadata or {}
|
|
398
|
+
for key in ("file_path", "url", "source"):
|
|
399
|
+
value = metadata.get(key)
|
|
400
|
+
if isinstance(value, str) and value.strip():
|
|
401
|
+
return value[:200]
|
|
402
|
+
try:
|
|
403
|
+
return node.node.ref_doc_id
|
|
404
|
+
except Exception: # noqa: BLE001
|
|
405
|
+
return None
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
__all__ = ["NeedlepathPostprocessor", "USER_AGENT_SUFFIX", "METADATA_PREFIX"]
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llama-index-postprocessor-needlepath
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: llama-index postprocessor needlepath context selection integration
|
|
5
|
+
Project-URL: Homepage, https://nextmoca.com
|
|
6
|
+
Author: Next Moca Global, Inc.
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Python: <4.0,>=3.10
|
|
10
|
+
Requires-Dist: llama-index-core<0.15,>=0.13.0
|
|
11
|
+
Requires-Dist: needlepath<1.0.0,>=0.1.0
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
14
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
15
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# `llama-index-postprocessor-needlepath`
|
|
19
|
+
|
|
20
|
+
Needlepath context selection as a LlamaIndex `BaseNodePostprocessor`: given the
|
|
21
|
+
retrieved nodes and the query, keep the nodes that carry the answer and replace
|
|
22
|
+
each one's text with the part of it that does.
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install llama-index-postprocessor-needlepath
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from llama_index.postprocessor.needlepath import NeedlepathPostprocessor
|
|
30
|
+
|
|
31
|
+
query_engine = index.as_query_engine(
|
|
32
|
+
node_postprocessors=[NeedlepathPostprocessor(operating_point="np-2026-07-r2")],
|
|
33
|
+
)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The key comes from `NEEDLEPATH_API_KEY`. If the service is slow, down, or stands
|
|
37
|
+
down, the query engine gets the nodes it was given, unchanged.
|
|
38
|
+
|
|
39
|
+
## Scope, stated honestly
|
|
40
|
+
|
|
41
|
+
This is a RAG-retrieval seam. It never sees tool outputs, so it exercises the
|
|
42
|
+
weakest of Needlepath's use cases — retrieved chunks are already short and
|
|
43
|
+
already ranked. It exists because LlamaIndex is where a large number of
|
|
44
|
+
developers already have a postprocessor slot, and an integration that does not
|
|
45
|
+
exist cannot be evaluated. If you are choosing where to try Needlepath first and
|
|
46
|
+
you have an agent with tool calls, start there instead.
|
|
47
|
+
|
|
48
|
+
## Configuration
|
|
49
|
+
|
|
50
|
+
| Parameter | Default | What it does |
|
|
51
|
+
|---|---|---|
|
|
52
|
+
| `operating_point` | — | **Required.** Immutable label. Also `NEEDLEPATH_OPERATING_POINT`. |
|
|
53
|
+
| `max_context_tokens` | `4000` | Budget for the selected context, and the default trigger. |
|
|
54
|
+
| `trigger_tokens` | `0` | Skip the call below this. `0` means "use the budget". |
|
|
55
|
+
| `excerpt` | `True` | Replace kept nodes' text with their excerpt. `False` filters only. |
|
|
56
|
+
| `update_scores` | `False` | Replace `NodeWithScore.score` with the selection score. |
|
|
57
|
+
| `preserve_input_order` | `False` | Return kept nodes in retrieval order rather than ranked order. |
|
|
58
|
+
| `shadow` | `False` | Measure and report; change nothing. |
|
|
59
|
+
| `enabled` | `True` | Kill switch. Needs no credentials when `False`. |
|
|
60
|
+
|
|
61
|
+
Any other keyword is forwarded to the core client (`base_url`, `api_key`,
|
|
62
|
+
`timeout`, …).
|
|
63
|
+
|
|
64
|
+
## Two LlamaIndex-specific decisions
|
|
65
|
+
|
|
66
|
+
**Scores are not overwritten by default.** A reranker replaces
|
|
67
|
+
`NodeWithScore.score` with its own. Ours is not calibrated against your
|
|
68
|
+
retriever's similarity, and silently substituting one for the other corrupts any
|
|
69
|
+
downstream threshold or `similarity_cutoff`. The selection score is available as
|
|
70
|
+
node metadata; set `update_scores=True` if you want reranker-like behaviour and
|
|
71
|
+
know what your thresholds mean.
|
|
72
|
+
|
|
73
|
+
**Provenance metadata is hidden from the model.** Node metadata is interpolated
|
|
74
|
+
into the prompt under `MetadataMode.LLM` and into embeddings under
|
|
75
|
+
`MetadataMode.EMBED`. Every `needlepath_*` key this package writes is added to
|
|
76
|
+
`excluded_llm_metadata_keys` and `excluded_embed_metadata_keys` on the copy, so
|
|
77
|
+
debug data never reaches the model or an index.
|
|
78
|
+
|
|
79
|
+
## Node identity survives
|
|
80
|
+
|
|
81
|
+
A rewritten node is a `model_copy(deep=True)` with `set_content()` applied, so
|
|
82
|
+
`id_`, `metadata`, `relationships` and therefore `ref_doc_id` are carried over
|
|
83
|
+
verbatim. Building a fresh `TextNode` would mint a new random `id_` and drop
|
|
84
|
+
`relationships`, severing `ref_doc_id`, dedup and `PrevNextNodePostprocessor`.
|
|
85
|
+
|
|
86
|
+
The nodes you pass in are never mutated.
|
|
87
|
+
|
|
88
|
+
## Fail open
|
|
89
|
+
|
|
90
|
+
| What happens | What the query engine gets |
|
|
91
|
+
|---|---|
|
|
92
|
+
| Timeout, 5xx, throttling, contract violation | the original nodes, unchanged |
|
|
93
|
+
| The gate stands down, or selects nothing | the original nodes, unchanged |
|
|
94
|
+
| No `QueryBundle` | the original nodes, unchanged |
|
|
95
|
+
| Every returned id is unrecognized | the original nodes, unchanged |
|
|
96
|
+
|
|
97
|
+
The no-query case is worth calling out: every shipped reranker raises
|
|
98
|
+
`ValueError("Missing query bundle in extra info.")` there. This does not. A
|
|
99
|
+
postprocessor that raises turns a missing query into a failed query for the whole
|
|
100
|
+
engine, and the fail-open rule is binding at a framework boundary.
|
|
101
|
+
|
|
102
|
+
`postprocessor.stats.as_dict()` aggregates the counters.
|
|
103
|
+
|
|
104
|
+
## Async
|
|
105
|
+
|
|
106
|
+
`_apostprocess_nodes` is overridden rather than inherited. The base class's
|
|
107
|
+
default is `asyncio.to_thread(self._postprocess_nodes, …)`, which is correct but
|
|
108
|
+
burns a thread per query on what is a network call — and nine call sites in
|
|
109
|
+
`llama-index-core` reach the async path, including `RetrieverQueryEngine` and
|
|
110
|
+
every chat engine.
|
|
111
|
+
|
|
112
|
+
## Packaging
|
|
113
|
+
|
|
114
|
+
Named `llama-index-postprocessor-needlepath` rather than `needlepath-llamaindex`.
|
|
115
|
+
That is the one naming exception to Needlepath's vendor-first convention: a
|
|
116
|
+
package outside the host convention is not discoverable on LlamaHub at all.
|
|
117
|
+
|
|
118
|
+
PEP 420 namespace layout — `llama_index/` and `llama_index/postprocessor/` carry
|
|
119
|
+
no `__init__.py`, so this distribution coexists with `llama-index-core` and every
|
|
120
|
+
other integration under the same directories.
|
|
121
|
+
|
|
122
|
+
## Tested against
|
|
123
|
+
|
|
124
|
+
`llama-index-core==0.14.23`. Range `>=0.13.0,<0.15`, matching every shipped
|
|
125
|
+
`llama-index-postprocessor-*` package. CI runs against the newest minor.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
llama_index/postprocessor/needlepath/__init__.py,sha256=kv4z83oybYd28wKKoGoxpjkK05aYFXm1PK_wRovW9Gw,117
|
|
2
|
+
llama_index/postprocessor/needlepath/base.py,sha256=OWJ1SBoK3ePOjlcV_KC1saU25vXIZMn9DRkUyANT5-s,15824
|
|
3
|
+
llama_index/postprocessor/needlepath/version.py,sha256=tr2-zP7nAwYvPIwHWMSf1BmGnXbB-5N7mN_ONxhPZAw,49
|
|
4
|
+
llama_index_postprocessor_needlepath-0.1.0.dist-info/METADATA,sha256=WH5YT7aQC6McoJM_4-OD3UnHYuCwv4J3Cef5AI-gkDE,5455
|
|
5
|
+
llama_index_postprocessor_needlepath-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
6
|
+
llama_index_postprocessor_needlepath-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
7
|
+
llama_index_postprocessor_needlepath-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|