pydefend 0.1.0__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.
Files changed (63) hide show
  1. pydefend-0.1.0/LICENSE +201 -0
  2. pydefend-0.1.0/PKG-INFO +239 -0
  3. pydefend-0.1.0/README.md +206 -0
  4. pydefend-0.1.0/defend_api/__init__.py +12 -0
  5. pydefend-0.1.0/defend_api/config.py +178 -0
  6. pydefend-0.1.0/defend_api/guard_session.py +48 -0
  7. pydefend-0.1.0/defend_api/logging.py +14 -0
  8. pydefend-0.1.0/defend_api/main.py +61 -0
  9. pydefend-0.1.0/defend_api/models/__init__.py +1 -0
  10. pydefend-0.1.0/defend_api/models/defend_qwen.py +94 -0
  11. pydefend-0.1.0/defend_api/models/intent.py +67 -0
  12. pydefend-0.1.0/defend_api/modules/__init__.py +135 -0
  13. pydefend-0.1.0/defend_api/modules/base.py +18 -0
  14. pydefend-0.1.0/defend_api/modules/custom/__init__.py +1 -0
  15. pydefend-0.1.0/defend_api/modules/custom/module.py +16 -0
  16. pydefend-0.1.0/defend_api/modules/custom/output_module.py +16 -0
  17. pydefend-0.1.0/defend_api/modules/injection/__init__.py +1 -0
  18. pydefend-0.1.0/defend_api/modules/injection/module.py +19 -0
  19. pydefend-0.1.0/defend_api/modules/pii/__init__.py +1 -0
  20. pydefend-0.1.0/defend_api/modules/pii/module.py +21 -0
  21. pydefend-0.1.0/defend_api/modules/pii/output_module.py +22 -0
  22. pydefend-0.1.0/defend_api/modules/prompt_leak/__init__.py +1 -0
  23. pydefend-0.1.0/defend_api/modules/prompt_leak/output_module.py +20 -0
  24. pydefend-0.1.0/defend_api/modules/topic/__init__.py +1 -0
  25. pydefend-0.1.0/defend_api/modules/topic/module.py +24 -0
  26. pydefend-0.1.0/defend_api/modules/topic/output_module.py +24 -0
  27. pydefend-0.1.0/defend_api/patterns.py +168 -0
  28. pydefend-0.1.0/defend_api/pipeline/__init__.py +1 -0
  29. pydefend-0.1.0/defend_api/pipeline/intent_fastpass.py +31 -0
  30. pydefend-0.1.0/defend_api/pipeline/normalization.py +105 -0
  31. pydefend-0.1.0/defend_api/pipeline/orchestrator.py +215 -0
  32. pydefend-0.1.0/defend_api/pipeline/regex_heuristics.py +99 -0
  33. pydefend-0.1.0/defend_api/pipeline/session_accumulator.py +73 -0
  34. pydefend-0.1.0/defend_api/providers/__init__.py +62 -0
  35. pydefend-0.1.0/defend_api/providers/base.py +41 -0
  36. pydefend-0.1.0/defend_api/providers/claude/__init__.py +1 -0
  37. pydefend-0.1.0/defend_api/providers/claude/provider.py +124 -0
  38. pydefend-0.1.0/defend_api/providers/defend/__init__.py +1 -0
  39. pydefend-0.1.0/defend_api/providers/defend/provider.py +41 -0
  40. pydefend-0.1.0/defend_api/providers/openai/__init__.py +1 -0
  41. pydefend-0.1.0/defend_api/providers/openai/provider.py +118 -0
  42. pydefend-0.1.0/defend_api/providers/orchestrator.py +47 -0
  43. pydefend-0.1.0/defend_api/routers/__init__.py +1 -0
  44. pydefend-0.1.0/defend_api/routers/guard.py +153 -0
  45. pydefend-0.1.0/defend_api/routers/health.py +40 -0
  46. pydefend-0.1.0/defend_api/routers/sessions.py +35 -0
  47. pydefend-0.1.0/defend_api/schemas.py +154 -0
  48. pydefend-0.1.0/defend_api/session.py +83 -0
  49. pydefend-0.1.0/pydefend.egg-info/PKG-INFO +239 -0
  50. pydefend-0.1.0/pydefend.egg-info/SOURCES.txt +61 -0
  51. pydefend-0.1.0/pydefend.egg-info/dependency_links.txt +1 -0
  52. pydefend-0.1.0/pydefend.egg-info/entry_points.txt +2 -0
  53. pydefend-0.1.0/pydefend.egg-info/requires.txt +25 -0
  54. pydefend-0.1.0/pydefend.egg-info/top_level.txt +2 -0
  55. pydefend-0.1.0/pyproject.toml +54 -0
  56. pydefend-0.1.0/sdk/python/defend/__init__.py +11 -0
  57. pydefend-0.1.0/sdk/python/defend/cli.py +333 -0
  58. pydefend-0.1.0/sdk/python/defend/client.py +312 -0
  59. pydefend-0.1.0/sdk/python/defend/exceptions.py +46 -0
  60. pydefend-0.1.0/sdk/python/defend/init_token.py +164 -0
  61. pydefend-0.1.0/sdk/python/defend/models.py +63 -0
  62. pydefend-0.1.0/sdk/python/defend/py.typed +1 -0
  63. pydefend-0.1.0/setup.cfg +4 -0
pydefend-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Defend
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,239 @@
1
+ Metadata-Version: 2.4
2
+ Name: pydefend
3
+ Version: 0.1.0
4
+ Summary: AI security guardrails for LLM applications.
5
+ Author: Defend maintainers
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.12
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: httpx>=0.27
11
+ Requires-Dist: pydantic>=2.9
12
+ Requires-Dist: pyyaml>=6.0
13
+ Requires-Dist: typer>=0.12
14
+ Provides-Extra: server
15
+ Requires-Dist: fastapi>=0.115; extra == "server"
16
+ Requires-Dist: uvicorn[standard]>=0.30; extra == "server"
17
+ Requires-Dist: prometheus-fastapi-instrumentator>=7.0; extra == "server"
18
+ Requires-Dist: pydantic-settings>=2.5; extra == "server"
19
+ Requires-Dist: regex>=2024.9.11; extra == "server"
20
+ Requires-Dist: bleach>=6.2; extra == "server"
21
+ Requires-Dist: ftfy>=6.2; extra == "server"
22
+ Requires-Dist: openai>=1.57; extra == "server"
23
+ Requires-Dist: anthropic>=0.42; extra == "server"
24
+ Requires-Dist: transformers>=4.46; extra == "server"
25
+ Requires-Dist: sentence-transformers>=3.2; extra == "server"
26
+ Provides-Extra: benchmark
27
+ Requires-Dist: datasets>=2.20; extra == "benchmark"
28
+ Requires-Dist: scikit-learn>=1.5; extra == "benchmark"
29
+ Requires-Dist: langdetect>=1.0.9; extra == "benchmark"
30
+ Provides-Extra: all
31
+ Requires-Dist: pydefend[benchmark,server]; extra == "all"
32
+ Dynamic: license-file
33
+
34
+ <p align="center">
35
+ <img src="assets/header.jpg" alt="Defend - AI security guardrails for LLM applications" width="100%" />
36
+ </p>
37
+
38
+ <p align="center"><strong>AI security guardrails for LLM applications</strong></p>
39
+
40
+ <p align="center">
41
+ <img src="https://img.shields.io/badge/license-Apache--2.0-blue" alt="License: Apache-2.0" />
42
+ <img src="https://img.shields.io/badge/python-3.12%2B-blue" alt="Python: 3.12+" />
43
+ <img src="https://img.shields.io/badge/docker-ready-blue" alt="Docker ready" />
44
+ </p>
45
+
46
+ - **Guards inputs and outputs**: checks user text before your LLM call and the LLM response before you return it to users/tools.
47
+ - **Maintains conversation context**: link turns with `session_id` so risk can accumulate across a session.
48
+ - **Configurable policies**: use built-in modules (PII/topic/injection) or define your own plain-language rules (`custom` / `custom_output`) via a `prompt:` string.
49
+
50
+ ---
51
+
52
+ ## Quick links
53
+
54
+ - [Getting started](GETTING_STARTED.md)
55
+ - [Modules](#modules)
56
+ - [How it works](#how-it-works)
57
+ - [Benchmarks](#benchmark-comparison)
58
+
59
+ ---
60
+
61
+ ## Easy setup (HTTP-first)
62
+
63
+ ```bash
64
+ pip install "pydefend[server]"
65
+ ```
66
+
67
+ Create `defend.config.yaml` (minimal, verifiable):
68
+
69
+ ```yaml
70
+ provider:
71
+ primary: defend
72
+
73
+ api_keys:
74
+ anthropic_env: ANTHROPIC_API_KEY
75
+ openai_env: OPENAI_API_KEY
76
+
77
+ guards:
78
+ input:
79
+ provider: defend
80
+ modules: []
81
+
82
+ output:
83
+ enabled: true
84
+ provider: claude # claude or openai
85
+ modules: []
86
+ on_fail: block # block | flag
87
+
88
+ session_ttl_seconds: 300
89
+ ```
90
+
91
+ Run the API:
92
+
93
+ ```bash
94
+ defend serve
95
+ ```
96
+
97
+ Guard input (before your LLM call):
98
+
99
+ ```bash
100
+ curl -X POST http://localhost:8000/v1/guard/input \
101
+ -H "Content-Type: application/json" \
102
+ -d '{"text":"Tell me how to bypass our security controls."}'
103
+ ```
104
+
105
+ Guard output (before returning to the user/tools):
106
+
107
+ ```bash
108
+ curl -X POST http://localhost:8000/v1/guard/output \
109
+ -H "Content-Type: application/json" \
110
+ -d '{"text":"<LLM response here>","session_id":"<session_id from /v1/guard/input>"}'
111
+ ```
112
+
113
+ Handling semantics:
114
+
115
+ - If `action == "block"`: stop the flow (don’t call the LLM on input; don’t return the output verbatim on output).
116
+ - If `action == "flag"`: you decide (log, require user confirmation, rerun with safer prompt, etc.).
117
+ - Always persist/forward `session_id` to link turns and enable multi-turn accumulation.
118
+
119
+ For a fuller local runbook (health check, `uvicorn`, and more `curl` examples), see `GETTING_STARTED.md`.
120
+
121
+ ### Security & privacy (non-goals included)
122
+
123
+ - Defend helps **detect** common LLM risks (prompt injection, prompt leaks, PII, out-of-scope content) but cannot make strong guarantees against all attacks or model failures.
124
+ - If you enable output guarding with `claude`/`openai`, your guarded text may be sent to that provider for evaluation. Avoid sending secrets you can’t disclose; scrub or minimize sensitive context before calling external providers.
125
+
126
+ ### Use the Python SDK
127
+
128
+ ```python
129
+ from defend import Client
130
+
131
+ guard = Client(
132
+ api_key="dev",
133
+ base_url="http://localhost:8000", # client normalizes to /v1 automatically
134
+ )
135
+
136
+ user_text = "Tell me how to bypass our security controls."
137
+
138
+ in_res = guard.input(user_text)
139
+ if in_res.blocked:
140
+ raise RuntimeError(in_res.error_response())
141
+
142
+ raw_llm_output = your_llm_call(user_text) # your LLM provider, unchanged
143
+
144
+ out_res = guard.output(raw_llm_output, session_id=in_res.session_id)
145
+ if out_res.blocked:
146
+ raise RuntimeError(out_res.error_response())
147
+ ```
148
+
149
+ ### Use the TypeScript SDK
150
+
151
+ ```ts
152
+ import { DefendClient, isBlocked, toBlockedErrorPayload } from "defendts";
153
+
154
+ const guard = new DefendClient({
155
+ apiKey: "dev",
156
+ baseUrl: "http://localhost:8000", // client normalizes to /v1 automatically
157
+ });
158
+
159
+ const userText = "Tell me how to bypass our security controls.";
160
+
161
+ const inRes = await guard.input(userText);
162
+ if (isBlocked(inRes)) {
163
+ throw new Error(JSON.stringify(toBlockedErrorPayload(inRes)));
164
+ }
165
+
166
+ const rawLlmOutput = await yourLlmCall(userText); // your LLM provider, unchanged
167
+
168
+ const outRes = await guard.output(rawLlmOutput, { sessionId: inRes.session_id });
169
+ if (isBlocked(outRes)) {
170
+ throw new Error(JSON.stringify(toBlockedErrorPayload(outRes)));
171
+ }
172
+ ```
173
+
174
+ ---
175
+
176
+ ## Modules
177
+
178
+ - `injection` (input only): Detect likely prompt-injection or instruction-override attempts in user text.
179
+ - `prompt_leak` (output only): Detect system prompt or internal instruction exposure in model output.
180
+ - `pii` / `pii_output`: Detect PII in user input and prevent PII leakage in model output.
181
+ - `topic` / `topic_output`: Enforce topic boundaries on both user requests and model responses.
182
+ - `custom` / `custom_output`: Add plain-language rules with `prompt:` for input and output checks.
183
+
184
+ Use input modules under `guards.input.modules` and output modules under `guards.output.modules` in `defend.config.yaml`.
185
+
186
+ ---
187
+
188
+ ## How it works
189
+
190
+ <p align="center">
191
+ <img src="assets/pipeline.jpg" alt="Defend pipeline overview: input guard → LLM → output guard" width="100%" />
192
+ </p>
193
+
194
+ ### Input guard
195
+
196
+ ```text
197
+ User → Your app → /v1/guard/input → (pass | flag | block) → Your app → LLM
198
+ └─ session_id (save this)
199
+ ```
200
+
201
+ Input guard checks the inbound text and can block early. If you receive a `session_id`, pass it to `/v1/guard/output` so Defend can apply multi-turn risk.
202
+
203
+ ### Output guard
204
+
205
+ ```text
206
+ LLM → Your app → /v1/guard/output (session_id) → (pass | flag | block) → Your app → User
207
+ ```
208
+
209
+ Output guard reviews the model output in context (using the same `session_id`) and applies output checks (prompt leaks, PII, topic, and your custom rules). Use the returned `action` to decide whether to return the text, flag it, or block it.
210
+
211
+ ---
212
+
213
+ ## Evaluation model
214
+
215
+ Defend always runs the same flow: input guard → your LLM → output guard.
216
+
217
+ For semantic evaluation, Defend can use:
218
+
219
+ - `defend` ([local fine-tuned model](https://huggingface.co/Adaxer/defend)): fast, offline input-only checks.
220
+ - `claude` / `openai` (LLM): stronger evaluation; required for output guarding and module-based checks.
221
+
222
+ In `defend.config.yaml`, you select which provider to use for input evaluation, and (when output guarding is enabled) which LLM provider to use for output evaluation. `claude/openai` calls consume API tokens.
223
+
224
+ ### Benchmark comparison
225
+
226
+ Using the local `defend` pipeline, Defend ranks among the highest-performing models on [GenTel-Bench](https://gentellab.github.io/gentel-safe.github.io/).
227
+
228
+
229
+ | Model | Accuracy | Precision | Recall | F1 |
230
+ | ---------------------- | --------- | --------- | --------- | --------- |
231
+ | **Defend (this repo)** | **95.96** | **94.83** | **97.10** | **95.94** |
232
+ | GenTel-Shield | 97.45 | 98.97 | 95.98 | 97.44 |
233
+ | ProtectAI | 91.55 | 99.72 | 83.56 | 90.88 |
234
+ | Lakera AI | 85.96 | 91.27 | 79.51 | 84.11 |
235
+ | Prompt Guard | 50.59 | 50.59 | 98.96 | 66.95 |
236
+ | Deepset | 63.63 | 58.54 | 98.36 | 73.39 |
237
+
238
+
239
+ The model was evaluated on a representative subset of jailbreak, goal-hijacking, and prompt-leaking attack scenarios.
@@ -0,0 +1,206 @@
1
+ <p align="center">
2
+ <img src="assets/header.jpg" alt="Defend - AI security guardrails for LLM applications" width="100%" />
3
+ </p>
4
+
5
+ <p align="center"><strong>AI security guardrails for LLM applications</strong></p>
6
+
7
+ <p align="center">
8
+ <img src="https://img.shields.io/badge/license-Apache--2.0-blue" alt="License: Apache-2.0" />
9
+ <img src="https://img.shields.io/badge/python-3.12%2B-blue" alt="Python: 3.12+" />
10
+ <img src="https://img.shields.io/badge/docker-ready-blue" alt="Docker ready" />
11
+ </p>
12
+
13
+ - **Guards inputs and outputs**: checks user text before your LLM call and the LLM response before you return it to users/tools.
14
+ - **Maintains conversation context**: link turns with `session_id` so risk can accumulate across a session.
15
+ - **Configurable policies**: use built-in modules (PII/topic/injection) or define your own plain-language rules (`custom` / `custom_output`) via a `prompt:` string.
16
+
17
+ ---
18
+
19
+ ## Quick links
20
+
21
+ - [Getting started](GETTING_STARTED.md)
22
+ - [Modules](#modules)
23
+ - [How it works](#how-it-works)
24
+ - [Benchmarks](#benchmark-comparison)
25
+
26
+ ---
27
+
28
+ ## Easy setup (HTTP-first)
29
+
30
+ ```bash
31
+ pip install "pydefend[server]"
32
+ ```
33
+
34
+ Create `defend.config.yaml` (minimal, verifiable):
35
+
36
+ ```yaml
37
+ provider:
38
+ primary: defend
39
+
40
+ api_keys:
41
+ anthropic_env: ANTHROPIC_API_KEY
42
+ openai_env: OPENAI_API_KEY
43
+
44
+ guards:
45
+ input:
46
+ provider: defend
47
+ modules: []
48
+
49
+ output:
50
+ enabled: true
51
+ provider: claude # claude or openai
52
+ modules: []
53
+ on_fail: block # block | flag
54
+
55
+ session_ttl_seconds: 300
56
+ ```
57
+
58
+ Run the API:
59
+
60
+ ```bash
61
+ defend serve
62
+ ```
63
+
64
+ Guard input (before your LLM call):
65
+
66
+ ```bash
67
+ curl -X POST http://localhost:8000/v1/guard/input \
68
+ -H "Content-Type: application/json" \
69
+ -d '{"text":"Tell me how to bypass our security controls."}'
70
+ ```
71
+
72
+ Guard output (before returning to the user/tools):
73
+
74
+ ```bash
75
+ curl -X POST http://localhost:8000/v1/guard/output \
76
+ -H "Content-Type: application/json" \
77
+ -d '{"text":"<LLM response here>","session_id":"<session_id from /v1/guard/input>"}'
78
+ ```
79
+
80
+ Handling semantics:
81
+
82
+ - If `action == "block"`: stop the flow (don’t call the LLM on input; don’t return the output verbatim on output).
83
+ - If `action == "flag"`: you decide (log, require user confirmation, rerun with safer prompt, etc.).
84
+ - Always persist/forward `session_id` to link turns and enable multi-turn accumulation.
85
+
86
+ For a fuller local runbook (health check, `uvicorn`, and more `curl` examples), see `GETTING_STARTED.md`.
87
+
88
+ ### Security & privacy (non-goals included)
89
+
90
+ - Defend helps **detect** common LLM risks (prompt injection, prompt leaks, PII, out-of-scope content) but cannot make strong guarantees against all attacks or model failures.
91
+ - If you enable output guarding with `claude`/`openai`, your guarded text may be sent to that provider for evaluation. Avoid sending secrets you can’t disclose; scrub or minimize sensitive context before calling external providers.
92
+
93
+ ### Use the Python SDK
94
+
95
+ ```python
96
+ from defend import Client
97
+
98
+ guard = Client(
99
+ api_key="dev",
100
+ base_url="http://localhost:8000", # client normalizes to /v1 automatically
101
+ )
102
+
103
+ user_text = "Tell me how to bypass our security controls."
104
+
105
+ in_res = guard.input(user_text)
106
+ if in_res.blocked:
107
+ raise RuntimeError(in_res.error_response())
108
+
109
+ raw_llm_output = your_llm_call(user_text) # your LLM provider, unchanged
110
+
111
+ out_res = guard.output(raw_llm_output, session_id=in_res.session_id)
112
+ if out_res.blocked:
113
+ raise RuntimeError(out_res.error_response())
114
+ ```
115
+
116
+ ### Use the TypeScript SDK
117
+
118
+ ```ts
119
+ import { DefendClient, isBlocked, toBlockedErrorPayload } from "defendts";
120
+
121
+ const guard = new DefendClient({
122
+ apiKey: "dev",
123
+ baseUrl: "http://localhost:8000", // client normalizes to /v1 automatically
124
+ });
125
+
126
+ const userText = "Tell me how to bypass our security controls.";
127
+
128
+ const inRes = await guard.input(userText);
129
+ if (isBlocked(inRes)) {
130
+ throw new Error(JSON.stringify(toBlockedErrorPayload(inRes)));
131
+ }
132
+
133
+ const rawLlmOutput = await yourLlmCall(userText); // your LLM provider, unchanged
134
+
135
+ const outRes = await guard.output(rawLlmOutput, { sessionId: inRes.session_id });
136
+ if (isBlocked(outRes)) {
137
+ throw new Error(JSON.stringify(toBlockedErrorPayload(outRes)));
138
+ }
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Modules
144
+
145
+ - `injection` (input only): Detect likely prompt-injection or instruction-override attempts in user text.
146
+ - `prompt_leak` (output only): Detect system prompt or internal instruction exposure in model output.
147
+ - `pii` / `pii_output`: Detect PII in user input and prevent PII leakage in model output.
148
+ - `topic` / `topic_output`: Enforce topic boundaries on both user requests and model responses.
149
+ - `custom` / `custom_output`: Add plain-language rules with `prompt:` for input and output checks.
150
+
151
+ Use input modules under `guards.input.modules` and output modules under `guards.output.modules` in `defend.config.yaml`.
152
+
153
+ ---
154
+
155
+ ## How it works
156
+
157
+ <p align="center">
158
+ <img src="assets/pipeline.jpg" alt="Defend pipeline overview: input guard → LLM → output guard" width="100%" />
159
+ </p>
160
+
161
+ ### Input guard
162
+
163
+ ```text
164
+ User → Your app → /v1/guard/input → (pass | flag | block) → Your app → LLM
165
+ └─ session_id (save this)
166
+ ```
167
+
168
+ Input guard checks the inbound text and can block early. If you receive a `session_id`, pass it to `/v1/guard/output` so Defend can apply multi-turn risk.
169
+
170
+ ### Output guard
171
+
172
+ ```text
173
+ LLM → Your app → /v1/guard/output (session_id) → (pass | flag | block) → Your app → User
174
+ ```
175
+
176
+ Output guard reviews the model output in context (using the same `session_id`) and applies output checks (prompt leaks, PII, topic, and your custom rules). Use the returned `action` to decide whether to return the text, flag it, or block it.
177
+
178
+ ---
179
+
180
+ ## Evaluation model
181
+
182
+ Defend always runs the same flow: input guard → your LLM → output guard.
183
+
184
+ For semantic evaluation, Defend can use:
185
+
186
+ - `defend` ([local fine-tuned model](https://huggingface.co/Adaxer/defend)): fast, offline input-only checks.
187
+ - `claude` / `openai` (LLM): stronger evaluation; required for output guarding and module-based checks.
188
+
189
+ In `defend.config.yaml`, you select which provider to use for input evaluation, and (when output guarding is enabled) which LLM provider to use for output evaluation. `claude/openai` calls consume API tokens.
190
+
191
+ ### Benchmark comparison
192
+
193
+ Using the local `defend` pipeline, Defend ranks among the highest-performing models on [GenTel-Bench](https://gentellab.github.io/gentel-safe.github.io/).
194
+
195
+
196
+ | Model | Accuracy | Precision | Recall | F1 |
197
+ | ---------------------- | --------- | --------- | --------- | --------- |
198
+ | **Defend (this repo)** | **95.96** | **94.83** | **97.10** | **95.94** |
199
+ | GenTel-Shield | 97.45 | 98.97 | 95.98 | 97.44 |
200
+ | ProtectAI | 91.55 | 99.72 | 83.56 | 90.88 |
201
+ | Lakera AI | 85.96 | 91.27 | 79.51 | 84.11 |
202
+ | Prompt Guard | 50.59 | 50.59 | 98.96 | 66.95 |
203
+ | Deepset | 63.63 | 58.54 | 98.36 | 73.39 |
204
+
205
+
206
+ The model was evaluated on a representative subset of jailbreak, goal-hijacking, and prompt-leaking attack scenarios.
@@ -0,0 +1,12 @@
1
+ """
2
+ Internal Defend API namespace.
3
+
4
+ This module exposes the FastAPI server under `defend_api`, which is the canonical
5
+ import path for the Defend microservice in this repository layout.
6
+ """
7
+
8
+ from .main import create_app
9
+
10
+ __all__ = ["create_app"]
11
+
12
+