needlepath-litellm 0.2.0__tar.gz → 0.2.2__tar.gz

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.
@@ -1,11 +1,35 @@
1
1
  # Changelog
2
2
 
3
- Nothing in this tree has been published yet (`sdk/BLOCKED.md`), so there is no
4
- installed base to protect — this file exists anyway, because a breaking change
5
- should read like one whether or not a release ever shipped it, and because the
6
- constructor now raises pointing here by name.
3
+ All notable changes to the `needlepath-litellm` Python package are documented here.
7
4
 
8
- ## 0.2.0 — unreleased
5
+ ## 0.2.2 — 2026-11-04
6
+
7
+ ### Fixed
8
+
9
+ - **A `blocked` verdict withholds every record it covers.** When workspace
10
+ policy withholds the records (`outcome: "blocked"`, zero selected, empty
11
+ render), the core client used to classify the response as an empty
12
+ selection and this guardrail passed the original messages through. The
13
+ verdict is now installed: every tool result that was sent collapses to a
14
+ withheld notice naming the engine's categories, whatever its length (the
15
+ no-saving guards do not apply to a withhold), and the receipt reports
16
+ `reason: blocked`, `applied: true`. A blocked verdict is enforced in shadow
17
+ mode too: shadow never restores a withheld record (the receipt carries
18
+ `shadow: true`); shadow still installs nothing for every other reason.
19
+
20
+ ### Changed
21
+
22
+ - Dependency floor raised to `needlepath>=0.2.3`, the core release that adds
23
+ `Reason.BLOCKED`; a resolver can no longer pair this package with a core that
24
+ classifies a blocked verdict as an empty selection.
25
+
26
+ ## 0.2.1 — 2026-09-03
27
+
28
+ ### Changed
29
+
30
+ - Docs, docstrings and examples pin np-2026-08-r4. No behaviour change.
31
+
32
+ ## 0.2.0 — 2026-08-15
9
33
 
10
34
  ### Removed
11
35
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: needlepath-litellm
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Needlepath context selection as a LiteLLM proxy CustomGuardrail.
5
5
  Project-URL: Homepage, https://nextmoca.com
6
6
  Author: Next Moca Global, Inc.
@@ -14,7 +14,7 @@ Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Typing :: Typed
15
15
  Requires-Python: >=3.9
16
16
  Requires-Dist: litellm[proxy]<2.0.0,>=1.70.0
17
- Requires-Dist: needlepath<1.0.0,>=0.1.0
17
+ Requires-Dist: needlepath<1.0.0,>=0.2.3
18
18
  Provides-Extra: dev
19
19
  Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
20
20
  Requires-Dist: pytest>=7; extra == 'dev'
@@ -42,7 +42,7 @@ guardrails:
42
42
  guardrail: needlepath_litellm.NeedlepathGuardrail
43
43
  mode: "pre_call"
44
44
  default_on: true
45
- operating_point: "np-2026-07-r2" # required; immutable label
45
+ operating_point: "np-2026-08-r4" # required; immutable label
46
46
  history_max_tokens: 8000
47
47
  ```
48
48
 
@@ -173,7 +173,7 @@ Every request the guardrail touches carries a metadata-only blob:
173
173
  ```json
174
174
  {"metadata": {"needlepath": {
175
175
  "applied": true, "reason": "ok", "request_id": "np-…",
176
- "operating_point": "np-2026-07-r2", "tokens_saved": 6800,
176
+ "operating_point": "np-2026-08-r4", "tokens_saved": 6800,
177
177
  "rewrite_tokens_before": 7100, "rewrite_tokens_after": 900,
178
178
  "gate_reason": "engage:needle"}}}
179
179
  ```
@@ -19,7 +19,7 @@ guardrails:
19
19
  guardrail: needlepath_litellm.NeedlepathGuardrail
20
20
  mode: "pre_call"
21
21
  default_on: true
22
- operating_point: "np-2026-07-r2" # required; immutable label
22
+ operating_point: "np-2026-08-r4" # required; immutable label
23
23
  history_max_tokens: 8000
24
24
  ```
25
25
 
@@ -150,7 +150,7 @@ Every request the guardrail touches carries a metadata-only blob:
150
150
  ```json
151
151
  {"metadata": {"needlepath": {
152
152
  "applied": true, "reason": "ok", "request_id": "np-…",
153
- "operating_point": "np-2026-07-r2", "tokens_saved": 6800,
153
+ "operating_point": "np-2026-08-r4", "tokens_saved": 6800,
154
154
  "rewrite_tokens_before": 7100, "rewrite_tokens_after": 900,
155
155
  "gate_reason": "engage:needle"}}}
156
156
  ```
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "needlepath-litellm"
7
- version = "0.2.0"
7
+ version = "0.2.2"
8
8
  description = "Needlepath context selection as a LiteLLM proxy CustomGuardrail."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -27,7 +27,7 @@ classifiers = [
27
27
  # package is for the proxy, so it asks for the proxy: a guardrail that imports
28
28
  # cleanly and is never invoked is the worst of both worlds.
29
29
  dependencies = [
30
- "needlepath>=0.1.0,<1.0.0",
30
+ "needlepath>=0.2.3,<1.0.0",
31
31
  "litellm[proxy]>=1.70.0,<2.0.0",
32
32
  ]
33
33
 
@@ -6,7 +6,7 @@
6
6
  guardrail: needlepath_litellm.NeedlepathGuardrail
7
7
  mode: "pre_call"
8
8
  default_on: true
9
- operating_point: "np-2026-07-r2"
9
+ operating_point: "np-2026-08-r4"
10
10
 
11
11
  Every client behind the proxy gets context selection with no client-side change
12
12
  at all — and if the selection service is slow or down, every one of them still
@@ -17,7 +17,7 @@ from __future__ import annotations
17
17
 
18
18
  from typing import Any, Dict, List, Optional, Sequence, Tuple
19
19
 
20
- from needlepath import ContextRecord, RecordKind
20
+ from needlepath import ContextRecord, RecordKind, SelectionResult
21
21
 
22
22
  #: Where the metadata-only warning is written. Deliberately **not** a new
23
23
  #: top-level key on the request body: unknown top-level keys are forwarded
@@ -152,6 +152,7 @@ def build_records(
152
152
  text=text,
153
153
  kind=message_kind(message),
154
154
  id=record_id,
155
+ source_kind=str(message.get("role", "")).strip().lower() or "unknown",
155
156
  title=str(name)[:120] if isinstance(name, str) and name else None,
156
157
  )
157
158
  )
@@ -197,9 +198,16 @@ def apply_selection(
197
198
  excerpts: Dict[str, str],
198
199
  index_by_id: Dict[str, int],
199
200
  placeholder: str,
201
+ withhold: bool = False,
200
202
  ) -> Tuple[List[Dict[str, Any]], int, int]:
201
203
  """Rewrite selected and unselected messages. Returns (messages, before, after).
202
204
 
205
+ ``withhold`` is the one exception to the length guards below, for a
206
+ ``blocked`` verdict: every record collapses to ``placeholder`` (the
207
+ withheld notice) whatever its length, because the original is the thing
208
+ that must not be kept. ``excerpts`` is ignored; a blocked response
209
+ carries none.
210
+
203
211
  Every rewritten message is a **new dict**. The caller's own message objects
204
212
  are never mutated: on a proxy they can be shared with logging, with a retry
205
213
  path, and with another guardrail in the same chain.
@@ -216,6 +224,12 @@ def apply_selection(
216
224
  original = out[index]
217
225
  original_text = content_text(original.get("content"))
218
226
  before += approx_tokens(original_text)
227
+ if withhold:
228
+ replacement = dict(original)
229
+ replacement["content"] = placeholder
230
+ out[index] = replacement
231
+ after += approx_tokens(placeholder)
232
+ continue
219
233
  excerpt = excerpts.get(record_id)
220
234
  if excerpt is None and not placeholder.strip():
221
235
  # Invariant 2, at the mutation boundary. A blank custom placeholder
@@ -240,6 +254,25 @@ def apply_selection(
240
254
  return out, before, after
241
255
 
242
256
 
257
+ def withheld_notice(result: SelectionResult) -> str:
258
+ """The model-facing text installed for records workspace policy withheld.
259
+
260
+ Built from the receipt only — the engine's category labels and the request
261
+ id — never from the records. The categories are the engine's own names for
262
+ what the policy matched; they are wire fields, read here as labels, not
263
+ evaluated.
264
+ """
265
+ response = result.response
266
+ governance = response.extra.get("governance") if response is not None else None
267
+ counts = governance.get("category_counts") if isinstance(governance, dict) else None
268
+ categories = ", ".join(sorted(str(k) for k in counts)) if isinstance(counts, dict) else ""
269
+ why = f" ({categories})" if categories else ""
270
+ return (
271
+ f"[WITHHELD by workspace policy: this tool result was not delivered to the model{why}. "
272
+ f"Request {result.request_id}.]"
273
+ )
274
+
275
+
243
276
  def metadata_field(data: Dict[str, Any]) -> str:
244
277
  """Which metadata field this route is using.
245
278
 
@@ -37,6 +37,7 @@ from typing import Any, Dict, Optional
37
37
 
38
38
  from needlepath import (
39
39
  AsyncNeedlepathClient,
40
+ NeedlepathGuardrailError,
40
41
  Reason,
41
42
  SelectionResult,
42
43
  SelectionStats,
@@ -53,6 +54,7 @@ from ._openai import (
53
54
  messages_of,
54
55
  prior_user_prompts,
55
56
  reject_removed_options,
57
+ withheld_notice,
56
58
  write_metadata,
57
59
  )
58
60
  from .version import __version__
@@ -85,7 +87,7 @@ class NeedlepathGuardrail(CustomGuardrail):
85
87
  guardrail: needlepath_litellm.NeedlepathGuardrail
86
88
  mode: "pre_call"
87
89
  default_on: true
88
- operating_point: "np-2026-07-r2"
90
+ operating_point: "np-2026-08-r4"
89
91
  history_max_tokens: 8000
90
92
 
91
93
  Everything under ``litellm_params`` other than ``guardrail``, ``mode`` and
@@ -135,6 +137,9 @@ class NeedlepathGuardrail(CustomGuardrail):
135
137
  include_assistant: bool = False,
136
138
  include_user: bool = False,
137
139
  placeholder: str = DEFAULT_PLACEHOLDER,
140
+ selection_strategy: str = "fast",
141
+ support_contract: str = "auto",
142
+ security_mode: Optional[str] = None,
138
143
  base_url: Optional[str] = None,
139
144
  api_key: Optional[str] = None,
140
145
  timeout: Optional[float] = None,
@@ -158,6 +163,8 @@ class NeedlepathGuardrail(CustomGuardrail):
158
163
  self.include_assistant = bool(include_assistant)
159
164
  self.include_user = bool(include_user)
160
165
  self.placeholder = placeholder
166
+ self.selection_strategy = selection_strategy
167
+ self.support_contract = support_contract
161
168
  #: What this guardrail actually did to `data["messages"]` — real
162
169
  #: before/after token counts. See the module docstring's "Two stats
163
170
  #: objects, two truths" note.
@@ -180,6 +187,8 @@ class NeedlepathGuardrail(CustomGuardrail):
180
187
  client_kwargs["api_key"] = api_key
181
188
  if timeout is not None:
182
189
  client_kwargs["timeout"] = float(timeout)
190
+ if security_mode is not None:
191
+ client_kwargs["security_mode"] = security_mode
183
192
  client_kwargs["shadow"] = self.shadow
184
193
  self._client = client or AsyncNeedlepathClient(**client_kwargs)
185
194
 
@@ -204,13 +213,16 @@ class NeedlepathGuardrail(CustomGuardrail):
204
213
  data: dict,
205
214
  call_type: str,
206
215
  ) -> Optional[dict]:
207
- """Select context, mutate ``data`` in place, return it. **Never raises.**
216
+ """Select context; mandatory guardrail failures stop the LLM request.
208
217
 
209
218
  Returns ``None`` — LiteLLM's "no change" — on every path where we do not
210
219
  apply a selection, so a passthrough costs the request nothing at all.
211
220
  """
212
221
  try:
213
222
  return await self._pre_call(user_api_key_dict, cache, data, call_type)
223
+ except NeedlepathGuardrailError:
224
+ # Mandatory protection failures must stop the framework call.
225
+ raise
214
226
  except Exception as exc: # noqa: BLE001
215
227
  # Rule 3. A raised exception here is raised to the client. A failure
216
228
  # in a context optimizer must never be a failed LLM request.
@@ -277,6 +289,8 @@ class NeedlepathGuardrail(CustomGuardrail):
277
289
  ),
278
290
  max_context_tokens=self.history_max_tokens,
279
291
  shadow=True if self.shadow else None,
292
+ selection_strategy=self.selection_strategy,
293
+ support_contract=self.support_contract,
280
294
  )
281
295
  # The raw engine receipt, exactly as returned — see the class
282
296
  # docstring's "Two stats objects, two truths" note. `.stats` is
@@ -287,8 +301,11 @@ class NeedlepathGuardrail(CustomGuardrail):
287
301
  # `self.shadow` is belt and braces — the core client already declines a
288
302
  # shadow result — but a proxy operator running this over production
289
303
  # traffic was promised that measuring changes nothing, and that promise
290
- # is enforced at the point of mutation rather than inherited.
291
- if not result.applied or self.shadow:
304
+ # is enforced at the point of mutation rather than inherited. A blocked
305
+ # verdict is the one delivery shadow does not suppress: shadow never
306
+ # restores a withheld record, so it is installed below, shadow or not.
307
+ blocked = result.reason == Reason.BLOCKED
308
+ if not result.applied or (self.shadow and not blocked):
292
309
  # Nothing is installed on this path, so the ACTUAL before/after is
293
310
  # the size of what was considered, unchanged — not the engine's own
294
311
  # numbers, which describe a selection that was never applied.
@@ -303,9 +320,16 @@ class NeedlepathGuardrail(CustomGuardrail):
303
320
  messages,
304
321
  excerpts=result.excerpts,
305
322
  index_by_id=index_by_id,
306
- placeholder=self.placeholder,
323
+ # A blocked verdict covers every record that was sent: each one
324
+ # collapses to the withheld notice, which names the policy's
325
+ # categories, rather than to the selection placeholder.
326
+ placeholder=withheld_notice(result) if blocked else self.placeholder,
327
+ withhold=blocked,
307
328
  )
308
- if after >= before:
329
+ if after >= before and not blocked:
330
+ # The guard refuses a rewrite that saves nothing. A withheld
331
+ # record is not a saving, and refusing on length would keep the
332
+ # original — exactly what a blocked verdict forbids.
309
333
  declined = result.declined(Reason.NO_SAVING)
310
334
  # Nothing is installed here either: `selected` is computed but
311
335
  # never written to `data["messages"]`, so actual after == before.
@@ -1,3 +1,3 @@
1
- __version__ = "0.2.0"
1
+ __version__ = "0.2.2"
2
2
 
3
3
  __all__ = ["__version__"]
@@ -9,7 +9,12 @@ from __future__ import annotations
9
9
  import json
10
10
 
11
11
  import pytest
12
- from needlepath import AsyncNeedlepathClient, NeedlepathTimeoutError, Reason
12
+ from needlepath import (
13
+ AsyncNeedlepathClient,
14
+ NeedlepathGuardrailError,
15
+ NeedlepathTimeoutError,
16
+ Reason,
17
+ )
13
18
  from needlepath.testing import FakeAsyncTransport, error, ok, response_payload
14
19
 
15
20
  from needlepath_litellm import NeedlepathGuardrail
@@ -85,6 +90,99 @@ async def call(g, data, call_type="acompletion"):
85
90
  )
86
91
 
87
92
 
93
+ @pytest.mark.asyncio
94
+ @pytest.mark.parametrize(
95
+ "response",
96
+ [
97
+ pytest.param(error(503, "guardrails_unavailable"), id="unavailable"),
98
+ pytest.param(
99
+ echoing(
100
+ governance={"enabled": True, "policies_applied": 1},
101
+ ),
102
+ id="malformed-evidence",
103
+ ),
104
+ ],
105
+ )
106
+ @pytest.mark.parametrize("shadow", [False, True])
107
+ async def test_guardrail_failure_stops_the_llm_request(response, shadow):
108
+ g, _ = guardrail([response], shadow=shadow)
109
+ with pytest.raises(NeedlepathGuardrailError):
110
+ await call(g, chat_body())
111
+
112
+
113
+ @pytest.mark.asyncio
114
+ @pytest.mark.parametrize("shadow", [False, True])
115
+ async def test_a_blocked_verdict_is_installed_never_raised(shadow):
116
+ """The counterpart of the test above for ``outcome: blocked``: not an
117
+ enforcement failure but an applied verdict. Live, the tool result is the
118
+ withheld notice and the LLM request proceeds without the record. Shadow
119
+ installs nothing and the receipt still says what the engine decided."""
120
+ g, _ = guardrail(
121
+ [
122
+ echoing(
123
+ selected=[],
124
+ records_selected=0,
125
+ rendered_context="",
126
+ outcome="blocked",
127
+ governance={
128
+ "enabled": True,
129
+ "policies_applied": 1,
130
+ "records_blocked": 1,
131
+ "raw_context_fallback_allowed": False,
132
+ "category_counts": {"scope:source:hr": 1},
133
+ },
134
+ )
135
+ ],
136
+ shadow=shadow,
137
+ )
138
+ secret = "employee Marcus Lee, SSN 123-45-6789. " * 200
139
+ data = chat_body(tool_content=secret)
140
+ out = await call(g, data)
141
+ # Shadow or live: shadow never restores a withheld record.
142
+ assert out is not None
143
+ text = out["messages"][3]["content"]
144
+ assert "123-45-6789" not in text
145
+ assert "withheld" in text.lower()
146
+ assert "scope:source:hr" in text
147
+ assert data["metadata"][METADATA_KEY]["reason"] == Reason.BLOCKED
148
+ assert data["metadata"][METADATA_KEY]["shadow"] is shadow
149
+ assert g.stats.applied == 1
150
+
151
+
152
+ @pytest.mark.asyncio
153
+ async def test_shadow_still_withholds_a_blocked_tool_result():
154
+ """A proxy operator measuring in shadow was promised that measuring
155
+ changes nothing the model could have had anyway. A withheld record is not
156
+ one of those: the guardrail's own shadow flag does not restore it."""
157
+ g, transport = guardrail(
158
+ [
159
+ echoing(
160
+ selected=[],
161
+ records_selected=0,
162
+ rendered_context="",
163
+ outcome="blocked",
164
+ governance={
165
+ "enabled": True,
166
+ "policies_applied": 1,
167
+ "records_blocked": 1,
168
+ "raw_context_fallback_allowed": False,
169
+ "category_counts": {"scope:source:hr": 1},
170
+ },
171
+ )
172
+ ],
173
+ shadow=True,
174
+ )
175
+ data = chat_body()
176
+ out = await call(g, data)
177
+ assert len(transport.calls) == 1
178
+ assert out is not None
179
+ assert BIG not in out["messages"][3]["content"]
180
+ assert "withheld" in out["messages"][3]["content"].lower()
181
+ assert data["metadata"][METADATA_KEY]["reason"] == Reason.BLOCKED
182
+ assert data["metadata"][METADATA_KEY]["shadow"] is True
183
+ assert g.stats.reasons == {Reason.BLOCKED: 1}
184
+
185
+
88
186
  # --------------------------------------------------------------------------- #
89
187
  # Rule 1 — apply_guardrail must stay undefined
90
188
  # --------------------------------------------------------------------------- #
@@ -111,6 +209,35 @@ async def test_a_selection_mutates_the_body_in_place():
111
209
  assert len(transport.calls) == 1
112
210
 
113
211
 
212
+ @pytest.mark.asyncio
213
+ async def test_advanced_r4_controls_reach_the_core_client_wire():
214
+ g, transport = guardrail(
215
+ [echoing()],
216
+ selection_strategy="auto",
217
+ support_contract="nli",
218
+ )
219
+
220
+ await call(g, chat_body())
221
+
222
+ assert transport.bodies[0]["selection_strategy"] == "auto"
223
+ assert transport.bodies[0]["support_contract"] == "nli"
224
+ assert transport.bodies[0]["records"][0]["source_kind"] == "tool"
225
+
226
+
227
+ def test_security_mode_reaches_a_guardrail_owned_core_client():
228
+ guardrail = NeedlepathGuardrail(
229
+ guardrail_name="np",
230
+ event_hook="pre_call",
231
+ operating_point=OP,
232
+ api_key="",
233
+ base_url="http://localhost:9",
234
+ security_mode="audit",
235
+ )
236
+
237
+ assert guardrail._client is not None
238
+ assert guardrail._client.security_mode == "audit"
239
+
240
+
114
241
  @pytest.mark.asyncio
115
242
  async def test_every_other_request_key_survives():
116
243
  g, _ = guardrail([echoing()])
@@ -267,6 +394,78 @@ def two_tool_body():
267
394
  return body
268
395
 
269
396
 
397
+ @pytest.mark.asyncio
398
+ async def test_a_blocked_response_never_delivers_the_withheld_tool_result():
399
+ """`outcome: blocked`: workspace policy withheld every record. Nothing the
400
+ caller sent may reach the model; the tool result collapses to the
401
+ placeholder, and the receipt says the verdict was applied."""
402
+ g, _ = guardrail(
403
+ [
404
+ echoing(
405
+ selected=[],
406
+ records_selected=0,
407
+ rendered_context="",
408
+ outcome="blocked",
409
+ governance={
410
+ "enabled": True,
411
+ "policy_scope": "workspace",
412
+ "policy_revision": 20,
413
+ "records_before": 1,
414
+ "records_after": 0,
415
+ "records_blocked": 1,
416
+ "policies_applied": 2,
417
+ "raw_context_fallback_allowed": False,
418
+ "category_counts": {"scope:source:hr": 1},
419
+ },
420
+ )
421
+ ]
422
+ )
423
+ data = chat_body(tool_content="employee Marcus Lee, SSN 123-45-6789. " * 200)
424
+ out = await call(g, data)
425
+ assert out is not None
426
+ tool = out["messages"][3]
427
+ assert "123-45-6789" not in tool["content"]
428
+ assert g.stats.reasons == {Reason.BLOCKED: 1}
429
+ assert g.stats.applied == 1
430
+
431
+
432
+ @pytest.mark.asyncio
433
+ async def test_a_blocked_response_withholds_a_record_shorter_than_the_placeholder():
434
+ """The per-message length guard keeps an original the placeholder would
435
+ lengthen. A withheld record is not a saving: it is withheld whatever its
436
+ length, and the notice names the engine's categories."""
437
+ g, _ = guardrail(
438
+ [
439
+ echoing(
440
+ selected=[],
441
+ records_selected=0,
442
+ rendered_context="",
443
+ outcome="blocked",
444
+ governance={
445
+ "enabled": True,
446
+ "policy_scope": "workspace",
447
+ "policy_revision": 20,
448
+ "records_before": 2,
449
+ "records_after": 0,
450
+ "records_blocked": 2,
451
+ "policies_applied": 2,
452
+ "raw_context_fallback_allowed": False,
453
+ "category_counts": {"scope:source:hr": 2},
454
+ },
455
+ )
456
+ ]
457
+ )
458
+ data = two_tool_body()
459
+ data["messages"][3]["content"] = "SSN 123-45-6789"
460
+ out = await call(g, data)
461
+ assert out is not None
462
+ for index in (3, 5):
463
+ text = out["messages"][index]["content"]
464
+ assert "123-45-6789" not in text
465
+ assert "withheld" in text.lower()
466
+ assert "scope:source:hr" in text
467
+
468
+
270
469
  def keeping(*record_ids):
271
470
  """A service that selects only the named records."""
272
471