aicordon-haystack 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.
@@ -0,0 +1,199 @@
1
+ Metadata-Version: 2.5
2
+ Name: aicordon-haystack
3
+ Version: 0.1.0
4
+ Summary: Check what an LLM is given for prompt injection: material at ingest, and the turn it answers
5
+ Project-URL: Homepage, https://github.com/AICordon/aicordon/blob/main/integrations/haystack/README.md
6
+ Project-URL: Repository, https://github.com/AICordon/aicordon
7
+ Project-URL: Issues, https://github.com/AICordon/aicordon/issues
8
+ Project-URL: Changelog, https://github.com/AICordon/aicordon/blob/main/integrations/haystack/CHANGELOG.md
9
+ Author-email: Mikhail Gribov <mihail.gribov.rs@gmail.com>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: guardrails,haystack,jailbreak,llm-security,prompt-injection,rag
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Topic :: Security
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: aicordon>=1.1.0
20
+ Requires-Dist: haystack-ai>=3.0.0
21
+ Description-Content-Type: text/markdown
22
+
23
+ # AI Cordon Picket for Haystack
24
+
25
+ Check what an LLM is given for prompt injection — in both places it can arrive:
26
+
27
+ | component | reads | with |
28
+ |---|---|---|
29
+ | `PromptInjectionFilter` | **material**: documents at ingest, before they are chunked and embedded | Picket's `ipi` rules |
30
+ | `PromptInjectionGuard` | **the request**: the turn the model is about to answer | Picket's `dpi` rules |
31
+
32
+ The two rule sets are disjoint, and neither is a stricter version of the other — this is not a
33
+ sensitivity knob. Pick by role: material is what the model works on, the request is what it answers.
34
+ Your code knows which is which; it puts them in different places when it assembles the call.
35
+
36
+ The check is a rule, not a model: no GPU, no network, no key, a few hundred kilobytes of base, and a
37
+ fraction of a millisecond per turn on one core — see [what it costs](#what-it-costs).
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ pip install aicordon-haystack
43
+ ```
44
+
45
+ ## Material at ingest
46
+
47
+ ```python
48
+ from haystack import Pipeline
49
+ from haystack.components.preprocessors import DocumentSplitter
50
+ from haystack.components.writers import DocumentWriter
51
+ from haystack_integrations.components.preprocessors.aicordon import PromptInjectionFilter
52
+
53
+ pipe = Pipeline()
54
+ pipe.add_component("ipi_filter", PromptInjectionFilter(mode="redact"))
55
+ pipe.add_component("splitter", DocumentSplitter(split_by="word", split_length=200))
56
+ pipe.add_component("writer", DocumentWriter(document_store=store))
57
+
58
+ pipe.connect("converter.documents", "ipi_filter.documents")
59
+ pipe.connect("ipi_filter.documents", "splitter.documents")
60
+ pipe.connect("splitter.documents", "writer.documents")
61
+ pipe.connect("ipi_filter.rejected", "quarantine.documents") # optional; nothing disappears quietly
62
+ ```
63
+
64
+ The component sits **before the splitter**: a cut here takes the injection out of the chunks, the
65
+ embeddings and the store at once, with no offsets to reconcile across chunk boundaries.
66
+
67
+ ### What it does with a finding
68
+
69
+ | `mode` | the document | the length |
70
+ |---|---|---|
71
+ | `annotate` | indexed unchanged, the finding recorded in metadata | unchanged |
72
+ | `blank` | every character of the block becomes `blank_char` (default `*`) | **preserved** |
73
+ | `mask` | the block is replaced by `mask_with` | changes |
74
+ | `redact` *(default)* | the block is cut out | changes |
75
+ | `drop` | not indexed; it comes out of the `rejected` socket | — |
76
+ | `fail` | the run stops on the first finding | — |
77
+
78
+ `blank` is for pipelines that carry offsets, page maps or diffs downstream and cannot have a
79
+ document change length under them.
80
+
81
+ The cut takes **the line holding the span**, or the sentence when that line runs past 1500
82
+ characters: the span points at the injection, but what must leave the index is the whole utterance.
83
+ Measured on 1200 documents: the payload is gone entirely in 91% of catches, at a median 11.6% of the
84
+ document removed.
85
+
86
+ ## The turn the model answers
87
+
88
+ ```python
89
+ from haystack_integrations.components.validators.aicordon import PromptInjectionGuard
90
+
91
+ pipe.add_component("guard", PromptInjectionGuard()) # mode="drop" is the default
92
+ pipe.connect("prompt.messages", "guard.messages")
93
+ pipe.connect("guard.messages", "llm.messages") # the model is called on this path
94
+ pipe.connect("guard.blocked", "refusal.messages") # and not on this one
95
+ ```
96
+
97
+ **Two sockets, one value.** On a flagged exchange `run` returns `blocked` and no `messages` key, so
98
+ the generator is not called at all. Connect `blocked` to whatever answers the user instead.
99
+
100
+ The decision is for the **exchange**, not for one message: drop the offending turn and the model
101
+ answers the one before it.
102
+
103
+ ### What it reads, and what it does with a finding
104
+
105
+ `roles` maps a role to a rule set, default `{"user": "dpi"}`. `assistant` is the model's own text,
106
+ `system` the operator's. `tool` carries material and switches on with
107
+ `roles={"user": "dpi", "tool": "ipi"}` — measure your own tool output first: over live chat text the
108
+ `ipi` rules raise eight times as many alarms as over documents, and they fire on command lists and
109
+ code, which is what a tool result looks like.
110
+
111
+ | `mode` | the exchange |
112
+ |---|---|
113
+ | `drop` *(default)* | routed to the `blocked` socket; the model is not called |
114
+ | `annotate` | passed through, with the finding in each read message's metadata |
115
+ | `fail` | the run stops with `InjectionFound` |
116
+
117
+ No mode edits a turn, and asking for one raises. The cut above is fitted to an instruction spliced
118
+ into a document; a typed jailbreak is not spliced into anything — it *is* the turn, and cutting it
119
+ leaves the rest of the attack in place.
120
+
121
+ ## What lands in the metadata
122
+
123
+ Written on **every** document and every message whose role is read, so "checked and clean" is
124
+ distinguishable from "never checked". A role outside the map gets no fields — a third, distinct
125
+ fact.
126
+
127
+ ```python
128
+ {"ipi_flagged": False, "ipi_action": "none", "ipi_base": "20260817"}
129
+ {"ipi_flagged": True, "ipi_action": "redact", "ipi_base": "20260817",
130
+ "ipi_threats": ["IPI/Secret.Reveal.B"], "ipi_spans": [[812, 947]], "ipi_removed_chars": 163}
131
+
132
+ {"picket_flagged": True, "picket_action": "drop", "picket_base": "20260817",
133
+ "picket_threats": ["DPI/Policy.Cancel.M"], "picket_spans": [[0, 41]]}
134
+ ```
135
+
136
+ Findings are also logged through Haystack's own logger at `warning`, so the level is yours to set.
137
+
138
+ ## Measured
139
+
140
+ Not the detector's recall — that ships with the detector — but what the pipeline delivers with the
141
+ component and without.
142
+
143
+ **Material.** [Quadrat-IPI v1.0.1](https://huggingface.co/datasets/mihailgribov/quadrat-ipi),
144
+ 1000 injected and 1000 clean documents, `mode="redact"`; how much of a planted payload still reaches
145
+ the store:
146
+
147
+ | | whole corpus | injections that ask the model to **reveal** something |
148
+ |---|---|---|
149
+ | payload reaches the store intact, without the filter | 100% | 100% |
150
+ | payload reaches the store intact, with it | **85.4%** | **42.8%** |
151
+ | payload gone without a trace | 13.1% | **52.3%** |
152
+ | clean documents dropped or trimmed | 0 of 1000 | 0 of 1000 |
153
+
154
+ Both columns matter: the first is an arbitrary stream, the second is where the rule is strong. A
155
+ document cost 8.3 ms in that run — documents are long, and cost follows length.
156
+
157
+ **The request.** Held-out forum jailbreaks from
158
+ [TrustAIRLab in-the-wild](https://huggingface.co/datasets/TrustAIRLab/in-the-wild-jailbreak-prompts)
159
+ (537, near-duplicates of the fitting half removed) against 20 000 real user turns from
160
+ [WildChat](https://huggingface.co/datasets/allenai/WildChat-1M), `mode="drop"`:
161
+
162
+ | | |
163
+ |---|---|
164
+ | attacks reaching the model, without the guard | 100% (537 of 537) |
165
+ | attacks reaching the model, with it | **65.2%** |
166
+ | turns not answered, out of 20 000 real ones | 0.070% (14) |
167
+ | verdicts differing from the bare detector | **0** |
168
+
169
+ WildChat carries no attack labels and real jailbreaks sit inside it, so "turns not answered" is an
170
+ upper bound on the cost to a real user, not a false-alarm rate. The detector's working point, on a
171
+ labelled pool, is in its report.
172
+
173
+ Reproduce both with `eval/measure.py` and `eval/measure_dialog.py`.
174
+
175
+ ## What it costs
176
+
177
+ Adding the component to a pipeline costs **0.39 ms for a turn of median length**, and 1.65 ± 0.03 ms
178
+ averaged over ordinary traffic — 3000 real WildChat turns, each timed five times
179
+ (`eval/costturn.py`). Loading the base costs 15 ms, once per process.
180
+
181
+ The average is four times the median: cost follows turn length, and a chat pool has a long tail.
182
+ Find your row:
183
+
184
+ | turn length | turns in the pool | cost |
185
+ |---|---|---|
186
+ | under 200 characters | 1943 | 0.30 ms |
187
+ | 200–500 | 411 | 0.74 ms |
188
+ | 500–1500 | 321 | 1.62 ms |
189
+ | 1500–4000 | 182 | 4.09 ms |
190
+ | over 4000 | 143 | 13.20 ms |
191
+
192
+ Cost drifts with machine load. These were taken in one run by one procedure — the only way two
193
+ figures compare.
194
+
195
+ No findings does not mean no injection.
196
+
197
+ ## License
198
+
199
+ Apache-2.0, the same as the detector it wraps.
@@ -0,0 +1,8 @@
1
+ haystack_integrations/components/preprocessors/aicordon/__init__.py,sha256=Lf4jfiANubNCYu5lgRZbEx7KxE5hUPSBhWgTlFn12Eg,96
2
+ haystack_integrations/components/preprocessors/aicordon/prompt_injection_filter.py,sha256=gbqAB0sGhaxIQJcPMIDdKVfGgZp4G0nr40FOBNi5deE,4179
3
+ haystack_integrations/components/validators/aicordon/__init__.py,sha256=hwa4zx7Q-IzxaBtpAZsukCpHxkrRwmNBQ4TOhjkSb2s,93
4
+ haystack_integrations/components/validators/aicordon/prompt_injection_guard.py,sha256=_7yj6zgDCXAI4Vm-IeBgBEGTGR03YtftZBjHKmv1KIc,6416
5
+ aicordon_haystack-0.1.0.dist-info/METADATA,sha256=RNMwEI_b_HtlpNwuofx4JaV61zd3Ny4fzdAqydBKkZM,8938
6
+ aicordon_haystack-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
7
+ aicordon_haystack-0.1.0.dist-info/licenses/LICENSE,sha256=uEmWZek7CjsCTJkApsWk4Oq8XUDmvdCp1MIiiJq_xG8,11345
8
+ aicordon_haystack-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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 2026 Mikhail Gribov
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.
@@ -0,0 +1,3 @@
1
+ from .prompt_injection_filter import PromptInjectionFilter
2
+
3
+ __all__ = ["PromptInjectionFilter"]
@@ -0,0 +1,78 @@
1
+ """Check documents for indirect prompt injection before they are chunked and embedded.
2
+
3
+ The component sits between the converter and the splitter of an indexing pipeline. Everything it
4
+ decides comes from `aicordon.guard.InjectionGuard`; what lives here is the translation into
5
+ Haystack's types and its contract — nothing else, so the same policy serves the other frameworks
6
+ unchanged.
7
+
8
+ pipe.add_component("ipi_filter", PromptInjectionFilter(mode="redact"))
9
+ pipe.connect("converter.documents", "ipi_filter.documents")
10
+ pipe.connect("ipi_filter.documents", "splitter.documents")
11
+ pipe.connect("ipi_filter.rejected", "quarantine.documents") # optional, nothing is lost silently
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import replace
16
+ from typing import Any
17
+
18
+ from aicordon.guard import InjectionGuard
19
+ from haystack import Document, component, default_from_dict, default_to_dict, logging
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ @component
25
+ class PromptInjectionFilter:
26
+ """Two outputs on purpose: what goes on to be indexed, and what was taken out of the stream.
27
+
28
+ A component that only returned the survivors would drop documents where the pipeline diagram
29
+ shows a single arrow, and a reader of that diagram would never learn it. With `rejected` as its
30
+ own socket, removal is a connection someone chose to make — to a quarantine store, to a log, or
31
+ to nothing at all, but visibly.
32
+ """
33
+
34
+ def __init__(self, mode: str = "redact", meta_prefix: str = "ipi", blank_char: str = "*",
35
+ mask_with: str = "[prompt injection removed]") -> None:
36
+ # Only strings here: Haystack requires init parameters to be JSON-serialisable so that a
37
+ # pipeline can be saved and loaded. The detector is built in `warm_up()` instead, which is
38
+ # the hook the framework offers for state too heavy to raise during pipeline validation.
39
+ #
40
+ # KEPT ON THE INSTANCE UNDER THE PARAMETER NAMES, and serialised explicitly below. Without
41
+ # both, saving a pipeline loses the settings SILENTLY: with no `to_dict` the framework reads
42
+ # each init parameter back with `getattr(self, name)`, and when that fails it falls back to
43
+ # the default in the signature. A pipeline built with mode="annotate" came back out of YAML
44
+ # as "redact", with nothing raised anywhere.
45
+ self.mode = mode
46
+ self.meta_prefix = meta_prefix
47
+ self.blank_char = blank_char
48
+ self.mask_with = mask_with
49
+ self._guard = InjectionGuard(mode=mode, meta_prefix=meta_prefix, blank_char=blank_char,
50
+ mask_with=mask_with)
51
+
52
+ def to_dict(self) -> dict[str, Any]:
53
+ return default_to_dict(self, mode=self.mode, meta_prefix=self.meta_prefix,
54
+ blank_char=self.blank_char, mask_with=self.mask_with)
55
+
56
+ @classmethod
57
+ def from_dict(cls, data: dict[str, Any]) -> "PromptInjectionFilter":
58
+ return default_from_dict(cls, data)
59
+
60
+ def warm_up(self) -> None:
61
+ self._guard.warm_up()
62
+
63
+ @component.output_types(documents=list[Document], rejected=list[Document])
64
+ def run(self, documents: list[Document]) -> dict[str, Any]:
65
+ kept: list[Document] = []
66
+ rejected: list[Document] = []
67
+ for doc in documents:
68
+ verdict = self._guard.inspect(doc.content or "")
69
+ if verdict.flagged:
70
+ # Logged through the host's logger, at a level the host controls: "write it to the
71
+ # log" is not a mode — it is wanted under `drop` and under `annotate` alike.
72
+ logger.warning("prompt injection in a document at ingest: {threats}, action {mode}",
73
+ threats=", ".join(verdict.threats), mode=self.mode)
74
+ # A copy, never the input: the same list can be connected to a second branch of the
75
+ # pipeline, and editing in place would rewrite that branch's documents too.
76
+ out = replace(doc, content=verdict.text, meta={**doc.meta, **self._guard.meta(verdict)})
77
+ (kept if verdict.keep else rejected).append(out)
78
+ return {"documents": kept, "rejected": rejected}
@@ -0,0 +1,3 @@
1
+ from .prompt_injection_guard import PromptInjectionGuard
2
+
3
+ __all__ = ["PromptInjectionGuard"]
@@ -0,0 +1,114 @@
1
+ """Check the exchange for a jailbreak before the model is called.
2
+
3
+ The component sits between whatever assembles the messages and the chat generator. Everything it
4
+ decides comes from `aicordon.guard.DialogueGuard`; what lives here is the translation into
5
+ Haystack's types and its contract — nothing else, so the same policy serves the other frameworks
6
+ unchanged.
7
+
8
+ pipe.add_component("guard", PromptInjectionGuard()) # mode="drop" by default
9
+ pipe.connect("prompt.messages", "guard.messages")
10
+ pipe.connect("guard.messages", "llm.messages") # the model is called on this path
11
+ pipe.connect("guard.blocked", "refusal.messages") # and not on this one
12
+
13
+ TWO SOCKETS, AND ONLY ONE OF THEM CARRIES A VALUE. On a flagged exchange `run` returns `blocked` and
14
+ no `messages` key at all, which is how a Haystack component branches: a receiver whose socket got
15
+ nothing does not run. So the generator is not called with a mutilated message list — it is not
16
+ called. Whoever wants a reply for the user connects `blocked` to something that produces one.
17
+
18
+ THE COMPANION IS `PromptInjectionFilter`, and they are not variants of each other. That one reads
19
+ material at ingest with the `ipi` rules and may rewrite it; this one reads the request with the
20
+ `dpi` rules and never does. Which applies is decided by the role a string plays in the prompt — the
21
+ module docstrings in `aicordon.guard` set out why, and why nothing here cuts a hole in a turn.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import replace
26
+ from typing import Any
27
+
28
+ from aicordon.guard import DEFAULT_ROLES, DialogueGuard
29
+ from haystack import component, default_from_dict, default_to_dict, logging
30
+ from haystack.dataclasses import ChatMessage
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ #: What the guard reads of a message. A message can carry several text parts alongside images and
35
+ #: files; the parts are joined because that is what the model is given, and the non-text content is
36
+ #: not read at all — Picket is a rule over text.
37
+ PART_SEPARATOR = "\n\n"
38
+
39
+
40
+ @component
41
+ class PromptInjectionGuard:
42
+ """Decides for the exchange as a whole, not message by message.
43
+
44
+ :param mode: `drop` routes a flagged exchange to `blocked` instead of to the model; `annotate`
45
+ lets everything through with the finding in each read message's metadata, for a prompt or a
46
+ downstream router to act on; `fail` raises `InjectionFound`.
47
+ :param roles: role name to rule set — `dpi` for a typed request, `ipi` for material. Defaults to
48
+ `{"user": "dpi"}`. `tool` is left out on purpose: a tool result is material, but it reads
49
+ like agent prompts and code, where the `ipi` rules raise eight times the alarms they raise
50
+ on documents. Switch it on and measure your own tool outputs first.
51
+ :param meta_prefix: prefix for the metadata keys written on each message that was read.
52
+ """
53
+
54
+ def __init__(self, mode: str = "drop", roles: dict[str, str] | None = None,
55
+ meta_prefix: str = "picket") -> None:
56
+ # Only strings and plain dicts here: Haystack requires init parameters to be
57
+ # JSON-serialisable so that a pipeline can be saved and loaded. The detector is built in
58
+ # `warm_up()` instead, which is the hook the framework offers for state too heavy to raise
59
+ # during pipeline validation.
60
+ #
61
+ # KEPT ON THE INSTANCE UNDER THE PARAMETER NAMES, and serialised explicitly below. Without
62
+ # both, saving a pipeline loses the settings SILENTLY: with no `to_dict` the framework reads
63
+ # each init parameter back with `getattr(self, name)`, and when that fails it falls back to
64
+ # the default in the signature.
65
+ self.mode = mode
66
+ self.roles = dict(DEFAULT_ROLES if roles is None else roles)
67
+ self.meta_prefix = meta_prefix
68
+ self._guard = DialogueGuard(mode=mode, roles=self.roles, meta_prefix=meta_prefix)
69
+
70
+ def to_dict(self) -> dict[str, Any]:
71
+ return default_to_dict(self, mode=self.mode, roles=self.roles,
72
+ meta_prefix=self.meta_prefix)
73
+
74
+ @classmethod
75
+ def from_dict(cls, data: dict[str, Any]) -> "PromptInjectionGuard":
76
+ return default_from_dict(cls, data)
77
+
78
+ def warm_up(self) -> None:
79
+ self._guard.warm_up()
80
+
81
+ @component.output_types(messages=list[ChatMessage], blocked=list[ChatMessage])
82
+ def run(self, messages: list[ChatMessage]) -> dict[str, Any]:
83
+ verdict = self._guard.decide([(m.role.value, self._text(m)) for m in messages])
84
+ if verdict.flagged:
85
+ # Logged through the host's logger, at a level the host controls: "write it to the log"
86
+ # is not a mode — it is wanted under `drop` and under `annotate` alike.
87
+ logger.warning("prompt injection in a turn: {threats}, action {mode}",
88
+ threats=", ".join(verdict.threats), mode=self.mode)
89
+ # Copies, never the inputs: the same list can be connected to a second branch of the
90
+ # pipeline, and editing in place would rewrite that branch's messages too. Haystack warns
91
+ # on in-place mutation of a ChatMessage for exactly this reason.
92
+ out = [self._with_meta(m, self._guard.meta(verdict, i)) for i, m in enumerate(messages)]
93
+ # One key, not two. The socket that is absent is the branch that does not run.
94
+ return {"messages": out} if verdict.keep else {"blocked": out}
95
+
96
+ @staticmethod
97
+ def _text(message: ChatMessage) -> str:
98
+ """Everything of the message that is text the model will read.
99
+
100
+ `texts` alone is not that. A tool message carries its content in `tool_call_result.result`
101
+ and its `texts` is EMPTY, so a guard reading only `texts` would check tool results by
102
+ returning "nothing found" on an empty string — the quiet kind of wrong, since the role is in
103
+ the map and the metadata says it was read. Tool CALLS are left out on purpose: those are the
104
+ model's own output, not something handed to it.
105
+ """
106
+ parts = list(message.texts)
107
+ parts += [r.result for r in message.tool_call_results if r.result]
108
+ return PART_SEPARATOR.join(parts)
109
+
110
+ @staticmethod
111
+ def _with_meta(message: ChatMessage, extra: dict[str, Any]) -> ChatMessage:
112
+ if not extra:
113
+ return message
114
+ return replace(message, _meta={**message.meta, **extra})