needlepath-litellm 0.2.1__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.
@@ -2,6 +2,27 @@
2
2
 
3
3
  All notable changes to the `needlepath-litellm` Python package are documented here.
4
4
 
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
+
5
26
  ## 0.2.1 — 2026-09-03
6
27
 
7
28
  ### Changed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: needlepath-litellm
3
- Version: 0.2.1
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'
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "needlepath-litellm"
7
- version = "0.2.1"
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
 
@@ -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__
@@ -137,6 +139,7 @@ class NeedlepathGuardrail(CustomGuardrail):
137
139
  placeholder: str = DEFAULT_PLACEHOLDER,
138
140
  selection_strategy: str = "fast",
139
141
  support_contract: str = "auto",
142
+ security_mode: Optional[str] = None,
140
143
  base_url: Optional[str] = None,
141
144
  api_key: Optional[str] = None,
142
145
  timeout: Optional[float] = None,
@@ -184,6 +187,8 @@ class NeedlepathGuardrail(CustomGuardrail):
184
187
  client_kwargs["api_key"] = api_key
185
188
  if timeout is not None:
186
189
  client_kwargs["timeout"] = float(timeout)
190
+ if security_mode is not None:
191
+ client_kwargs["security_mode"] = security_mode
187
192
  client_kwargs["shadow"] = self.shadow
188
193
  self._client = client or AsyncNeedlepathClient(**client_kwargs)
189
194
 
@@ -208,13 +213,16 @@ class NeedlepathGuardrail(CustomGuardrail):
208
213
  data: dict,
209
214
  call_type: str,
210
215
  ) -> Optional[dict]:
211
- """Select context, mutate ``data`` in place, return it. **Never raises.**
216
+ """Select context; mandatory guardrail failures stop the LLM request.
212
217
 
213
218
  Returns ``None`` — LiteLLM's "no change" — on every path where we do not
214
219
  apply a selection, so a passthrough costs the request nothing at all.
215
220
  """
216
221
  try:
217
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
218
226
  except Exception as exc: # noqa: BLE001
219
227
  # Rule 3. A raised exception here is raised to the client. A failure
220
228
  # in a context optimizer must never be a failed LLM request.
@@ -293,8 +301,11 @@ class NeedlepathGuardrail(CustomGuardrail):
293
301
  # `self.shadow` is belt and braces — the core client already declines a
294
302
  # shadow result — but a proxy operator running this over production
295
303
  # traffic was promised that measuring changes nothing, and that promise
296
- # is enforced at the point of mutation rather than inherited.
297
- 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):
298
309
  # Nothing is installed on this path, so the ACTUAL before/after is
299
310
  # the size of what was considered, unchanged — not the engine's own
300
311
  # numbers, which describe a selection that was never applied.
@@ -309,9 +320,16 @@ class NeedlepathGuardrail(CustomGuardrail):
309
320
  messages,
310
321
  excerpts=result.excerpts,
311
322
  index_by_id=index_by_id,
312
- 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,
313
328
  )
314
- 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.
315
333
  declined = result.declined(Reason.NO_SAVING)
316
334
  # Nothing is installed here either: `selected` is computed but
317
335
  # never written to `data["messages"]`, so actual after == before.
@@ -1,3 +1,3 @@
1
- __version__ = "0.2.1"
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
  # --------------------------------------------------------------------------- #
@@ -123,6 +221,21 @@ async def test_advanced_r4_controls_reach_the_core_client_wire():
123
221
 
124
222
  assert transport.bodies[0]["selection_strategy"] == "auto"
125
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"
126
239
 
127
240
 
128
241
  @pytest.mark.asyncio
@@ -281,6 +394,78 @@ def two_tool_body():
281
394
  return body
282
395
 
283
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
+
284
469
  def keeping(*record_ids):
285
470
  """A service that selects only the named records."""
286
471