langchain-obscate 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.
- langchain_obscate-0.1.0/.gitignore +12 -0
- langchain_obscate-0.1.0/LICENSE +21 -0
- langchain_obscate-0.1.0/PKG-INFO +187 -0
- langchain_obscate-0.1.0/README.md +163 -0
- langchain_obscate-0.1.0/examples/quickstart.py +83 -0
- langchain_obscate-0.1.0/pyproject.toml +29 -0
- langchain_obscate-0.1.0/src/langchain_obscate/__init__.py +16 -0
- langchain_obscate-0.1.0/src/langchain_obscate/_client.py +306 -0
- langchain_obscate-0.1.0/src/langchain_obscate/middleware.py +77 -0
- langchain_obscate-0.1.0/src/langchain_obscate/redactor.py +204 -0
- langchain_obscate-0.1.0/src/langchain_obscate/runnable.py +88 -0
- langchain_obscate-0.1.0/src/langchain_obscate/tools.py +75 -0
- langchain_obscate-0.1.0/tests/fake_api.py +157 -0
- langchain_obscate-0.1.0/tests/test_langchain_obscate.py +208 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Skycast
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: langchain-obscate
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Reversible PII redaction for LangChain: redact before the LLM, restore after (Obscate API)
|
|
5
|
+
Project-URL: Homepage, https://obscate.com
|
|
6
|
+
Project-URL: Documentation, https://obscate.com/docs/langchain
|
|
7
|
+
Author: Skycast
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,dpdp,gdpr,langchain,llm,pii,privacy,redaction
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Requires-Dist: httpx>=0.27
|
|
13
|
+
Requires-Dist: langchain-core<2,>=1.0
|
|
14
|
+
Provides-Extra: agents
|
|
15
|
+
Requires-Dist: langchain<2,>=1.0; extra == 'agents'
|
|
16
|
+
Provides-Extra: examples
|
|
17
|
+
Requires-Dist: langchain-anthropic>=1.0; extra == 'examples'
|
|
18
|
+
Requires-Dist: python-dotenv>=1.0; extra == 'examples'
|
|
19
|
+
Provides-Extra: test
|
|
20
|
+
Requires-Dist: anyio>=4; extra == 'test'
|
|
21
|
+
Requires-Dist: langchain<2,>=1.0; extra == 'test'
|
|
22
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# langchain-obscate
|
|
26
|
+
|
|
27
|
+
Keep personal data away from your LLM provider. You add one wrapper. User
|
|
28
|
+
input, prompt variables and tool results are redacted before they reach the
|
|
29
|
+
model, and the model's answer (including tool-call arguments) comes back with
|
|
30
|
+
the real values restored.
|
|
31
|
+
|
|
32
|
+
It is a thin wrapper over the [Obscate](https://obscate.com) HTTP API.
|
|
33
|
+
Detection runs in the API, not in this package. Full docs:
|
|
34
|
+
[obscate.com/docs/langchain](https://obscate.com/docs/langchain).
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
your input ──redact──▶ LLM sees "seab.yomog@tziwxuo.com", "[PERSON:…]" ──restore──▶ your user sees "ravi.kumar@example.com", "Ravi Kumar"
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Known limitation: partial values come back wrong
|
|
41
|
+
|
|
42
|
+
If the model quotes only **part** of a redacted value ("your card ending in
|
|
43
|
+
7588", "the email starting with…"), restore can't fix it: it matches whole
|
|
44
|
+
tokens, and a fragment isn't one. With `fpe` this fails **silently and
|
|
45
|
+
plausibly**. The fake card looks like a real card, so its last four digits
|
|
46
|
+
look like real digits, and your user sees a confident, wrong statement about
|
|
47
|
+
their own data. Assistants paraphrase values like this all the time, so expect
|
|
48
|
+
it in normal use.
|
|
49
|
+
|
|
50
|
+
What we measured with real Claude (`claude-haiku-5-5`, a support-reply prompt,
|
|
51
|
+
3 runs each; a small test, not a guarantee):
|
|
52
|
+
|
|
53
|
+
| setup | replies stating wrong card digits |
|
|
54
|
+
|---|---|
|
|
55
|
+
| `fpe`, plain prompt | 2 of 3 |
|
|
56
|
+
| `fpe` + the instruction below in the system prompt | 0 of 3 |
|
|
57
|
+
| `tokenize`, plain prompt | 0 of 3 |
|
|
58
|
+
|
|
59
|
+
For user-facing output where the model may paraphrase values:
|
|
60
|
+
|
|
61
|
+
- Add to your system prompt: *"When you mention a card number, email or phone
|
|
62
|
+
number, repeat it exactly and in full as given. Never abbreviate, mask or
|
|
63
|
+
quote part of it."*
|
|
64
|
+
- Or use `strategy="tokenize"`: models treat `[CREDIT_CARD_1]` as a unit and
|
|
65
|
+
don't split it, and restore only touches tokens in its map.
|
|
66
|
+
|
|
67
|
+
Partial references are a boundary of any reversible-redaction approach, not
|
|
68
|
+
only ours: once the model only sees a stand-in, a fragment of the stand-in can
|
|
69
|
+
never map back to a fragment of the original.
|
|
70
|
+
|
|
71
|
+
## Quickstart (under 5 minutes)
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
pip install "langchain-obscate[examples]"
|
|
75
|
+
export OBSCATE_API_KEY=ob_... # free: 1,000 requests/month at https://obscate.com, no card
|
|
76
|
+
export ANTHROPIC_API_KEY=sk-ant-... # optional: without it the example uses a local stand-in LLM
|
|
77
|
+
python examples/quickstart.py
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Output (real run with the stand-in LLM; the redacted values differ per key):
|
|
81
|
+
|
|
82
|
+
```text
|
|
83
|
+
1) Your input:
|
|
84
|
+
Customer Ravi Kumar (email ravi.kumar@example.com phone +91 98765 43210) says card 4242 4242 4242 4242 was charged twice. ...
|
|
85
|
+
2) What the LLM receives:
|
|
86
|
+
[human] [PERSON:rug3juf…] (email seab.yomog@tziwxuo.com phone +91 45671 58378) says card 7982 1772 2838 5004 was charged twice. ...
|
|
87
|
+
3) Restored answer for your user:
|
|
88
|
+
... will confirm by email to ravi.kumar@example.com.
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Use it
|
|
92
|
+
|
|
93
|
+
**Any chat model, LLM or chain:** wrap it with `with_obscate`.
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from langchain_obscate import with_obscate
|
|
97
|
+
|
|
98
|
+
safe_llm = with_obscate(ChatAnthropic(model="claude-haiku-5-5"))
|
|
99
|
+
safe_llm.invoke("Draft a reply to ravi@example.com about order 1182") # -> AIMessage, restored
|
|
100
|
+
|
|
101
|
+
chain = with_obscate(prompt | llm | StrOutputParser()) # prompt variables redacted
|
|
102
|
+
chain.invoke({"name": "Ravi Kumar", "email": "ravi@example.com"}) # -> str, restored
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
**Agents (`create_agent`):** add the middleware. It redacts every model call,
|
|
106
|
+
covering user messages, tool results, earlier turns and the system prompt. It
|
|
107
|
+
restores the model's reply before your tools run, so your tools receive real
|
|
108
|
+
values and the provider never does.
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
pip install "langchain-obscate[agents]"
|
|
112
|
+
|
|
113
|
+
from langchain.agents import create_agent
|
|
114
|
+
from langchain_obscate import ObscateMiddleware
|
|
115
|
+
|
|
116
|
+
agent = create_agent("anthropic:claude-haiku-5-5", tools=[send_email],
|
|
117
|
+
middleware=[ObscateMiddleware()])
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
**Explicit tools:** use `ObscateRedactTool` (fpe-redacts a text) and
|
|
121
|
+
`ObscateDetectTool` (labels and counts only). Use them when the agent itself
|
|
122
|
+
should scrub a record before passing it downstream. The agent's own LLM still
|
|
123
|
+
sees the tool input, so use the middleware to protect against the provider.
|
|
124
|
+
|
|
125
|
+
### Why middleware rather than a callback
|
|
126
|
+
|
|
127
|
+
LangChain callbacks are observers. They are told what is sent to the model
|
|
128
|
+
but cannot change it. Redaction has to rewrite the request, so it lives in a
|
|
129
|
+
Runnable wrapper (chains) and in agent middleware (agents). The quickstart
|
|
130
|
+
uses a callback only to *show* you what the provider receives.
|
|
131
|
+
|
|
132
|
+
## Strategies
|
|
133
|
+
|
|
134
|
+
| strategy | LLM sees | restore needs | notes |
|
|
135
|
+
|---|---|---|---|
|
|
136
|
+
| `fpe` (default) | `seab.yomog@tziwxuo.com`, `7982 1772 2838 5004`, `[PERSON:…]` | your API key only | formats kept (valid-looking card numbers, emails). Values that can't keep their format fall back to bracketed `[LABEL:…]` tokens |
|
|
137
|
+
| `tokenize` | `[EMAIL_1]`, `[PERSON_1]` | the token map (held in memory for one call) | clearest for the model; consistent across all messages of one call |
|
|
138
|
+
| `synthetic` | realistic fake names/emails | the token map | most natural prompts |
|
|
139
|
+
| `mask` / `hash` / `partial` | `****`, hashes, `****1234` | not restorable | output stays redacted |
|
|
140
|
+
|
|
141
|
+
More: [strategies](https://obscate.com/docs/strategies).
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
with_obscate(llm, strategy="tokenize", labels=["EMAIL", "PHONE"], min_confidence=0.5)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## What to expect
|
|
148
|
+
|
|
149
|
+
- **Detection quality.** Structured IDs (email, phone, credit card, Aadhaar,
|
|
150
|
+
PAN, GSTIN, IBAN, SSN, IP, AWS keys) are near-perfect because they use
|
|
151
|
+
patterns and checksums. Names and places use an NER model and are
|
|
152
|
+
best-effort, so some will get through. Use `labels` and test on your data.
|
|
153
|
+
([Detectors](https://obscate.com/docs/detectors), [benchmark](https://obscate.com/docs/benchmark).)
|
|
154
|
+
- **fpe caveat.** If the model *invents* a new email, phone or ID that was
|
|
155
|
+
never redacted, fpe restore cannot tell it from a token and turns it into a
|
|
156
|
+
different value. Use `tokenize` if your model makes up contact details.
|
|
157
|
+
- **Key versions are handled for you.** Each redaction records the
|
|
158
|
+
`key_version` of your account's key, and the wrapper sends it back on
|
|
159
|
+
restore. A round trip keeps working even if Obscate rotates keys mid-call.
|
|
160
|
+
If you keep a `RestoreContext` (or fpe output) to restore later, keep its
|
|
161
|
+
`key_version` too.
|
|
162
|
+
- **Cost.** One Obscate request per model call (the whole conversation goes
|
|
163
|
+
in one request, 1 unit per 100 KB). Restores are free. A 5-step agent run
|
|
164
|
+
uses 5 units, so the free tier covers about 200 such runs a month.
|
|
165
|
+
([Pricing](https://obscate.com/pricing).)
|
|
166
|
+
- **Streaming is buffered.** `stream()` on the wrapper yields one restored
|
|
167
|
+
chunk at the end. With the agent middleware, `stream_mode="messages"` shows
|
|
168
|
+
the raw, still-redacted tokens; the messages in agent state are restored.
|
|
169
|
+
- **Fails closed.** If Obscate errors (network, quota, 503), the LLM is not
|
|
170
|
+
called and `ObscateError` is raised.
|
|
171
|
+
- **Self-hosted.** Set `OBSCATE_BASE_URL` to your instance. The self-hosted
|
|
172
|
+
edition is in pilot; ask contact@obscate.com.
|
|
173
|
+
|
|
174
|
+
## Privacy
|
|
175
|
+
|
|
176
|
+
This package never logs, prints or writes the text, the detected values or
|
|
177
|
+
the token map. Token maps live in memory for one call and are hidden from
|
|
178
|
+
`repr()`. Errors carry the HTTP status and the API's fixed message only. This
|
|
179
|
+
is enforced by `tests/test_langchain_obscate.py::test_privacy_*`.
|
|
180
|
+
|
|
181
|
+
## Develop
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
pip install -e '.[test]' && pytest -q # unit tests against an in-process fake API (no network)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
License: MIT.
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# langchain-obscate
|
|
2
|
+
|
|
3
|
+
Keep personal data away from your LLM provider. You add one wrapper. User
|
|
4
|
+
input, prompt variables and tool results are redacted before they reach the
|
|
5
|
+
model, and the model's answer (including tool-call arguments) comes back with
|
|
6
|
+
the real values restored.
|
|
7
|
+
|
|
8
|
+
It is a thin wrapper over the [Obscate](https://obscate.com) HTTP API.
|
|
9
|
+
Detection runs in the API, not in this package. Full docs:
|
|
10
|
+
[obscate.com/docs/langchain](https://obscate.com/docs/langchain).
|
|
11
|
+
|
|
12
|
+
```text
|
|
13
|
+
your input ──redact──▶ LLM sees "seab.yomog@tziwxuo.com", "[PERSON:…]" ──restore──▶ your user sees "ravi.kumar@example.com", "Ravi Kumar"
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Known limitation: partial values come back wrong
|
|
17
|
+
|
|
18
|
+
If the model quotes only **part** of a redacted value ("your card ending in
|
|
19
|
+
7588", "the email starting with…"), restore can't fix it: it matches whole
|
|
20
|
+
tokens, and a fragment isn't one. With `fpe` this fails **silently and
|
|
21
|
+
plausibly**. The fake card looks like a real card, so its last four digits
|
|
22
|
+
look like real digits, and your user sees a confident, wrong statement about
|
|
23
|
+
their own data. Assistants paraphrase values like this all the time, so expect
|
|
24
|
+
it in normal use.
|
|
25
|
+
|
|
26
|
+
What we measured with real Claude (`claude-haiku-5-5`, a support-reply prompt,
|
|
27
|
+
3 runs each; a small test, not a guarantee):
|
|
28
|
+
|
|
29
|
+
| setup | replies stating wrong card digits |
|
|
30
|
+
|---|---|
|
|
31
|
+
| `fpe`, plain prompt | 2 of 3 |
|
|
32
|
+
| `fpe` + the instruction below in the system prompt | 0 of 3 |
|
|
33
|
+
| `tokenize`, plain prompt | 0 of 3 |
|
|
34
|
+
|
|
35
|
+
For user-facing output where the model may paraphrase values:
|
|
36
|
+
|
|
37
|
+
- Add to your system prompt: *"When you mention a card number, email or phone
|
|
38
|
+
number, repeat it exactly and in full as given. Never abbreviate, mask or
|
|
39
|
+
quote part of it."*
|
|
40
|
+
- Or use `strategy="tokenize"`: models treat `[CREDIT_CARD_1]` as a unit and
|
|
41
|
+
don't split it, and restore only touches tokens in its map.
|
|
42
|
+
|
|
43
|
+
Partial references are a boundary of any reversible-redaction approach, not
|
|
44
|
+
only ours: once the model only sees a stand-in, a fragment of the stand-in can
|
|
45
|
+
never map back to a fragment of the original.
|
|
46
|
+
|
|
47
|
+
## Quickstart (under 5 minutes)
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install "langchain-obscate[examples]"
|
|
51
|
+
export OBSCATE_API_KEY=ob_... # free: 1,000 requests/month at https://obscate.com, no card
|
|
52
|
+
export ANTHROPIC_API_KEY=sk-ant-... # optional: without it the example uses a local stand-in LLM
|
|
53
|
+
python examples/quickstart.py
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Output (real run with the stand-in LLM; the redacted values differ per key):
|
|
57
|
+
|
|
58
|
+
```text
|
|
59
|
+
1) Your input:
|
|
60
|
+
Customer Ravi Kumar (email ravi.kumar@example.com phone +91 98765 43210) says card 4242 4242 4242 4242 was charged twice. ...
|
|
61
|
+
2) What the LLM receives:
|
|
62
|
+
[human] [PERSON:rug3juf…] (email seab.yomog@tziwxuo.com phone +91 45671 58378) says card 7982 1772 2838 5004 was charged twice. ...
|
|
63
|
+
3) Restored answer for your user:
|
|
64
|
+
... will confirm by email to ravi.kumar@example.com.
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Use it
|
|
68
|
+
|
|
69
|
+
**Any chat model, LLM or chain:** wrap it with `with_obscate`.
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from langchain_obscate import with_obscate
|
|
73
|
+
|
|
74
|
+
safe_llm = with_obscate(ChatAnthropic(model="claude-haiku-5-5"))
|
|
75
|
+
safe_llm.invoke("Draft a reply to ravi@example.com about order 1182") # -> AIMessage, restored
|
|
76
|
+
|
|
77
|
+
chain = with_obscate(prompt | llm | StrOutputParser()) # prompt variables redacted
|
|
78
|
+
chain.invoke({"name": "Ravi Kumar", "email": "ravi@example.com"}) # -> str, restored
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
**Agents (`create_agent`):** add the middleware. It redacts every model call,
|
|
82
|
+
covering user messages, tool results, earlier turns and the system prompt. It
|
|
83
|
+
restores the model's reply before your tools run, so your tools receive real
|
|
84
|
+
values and the provider never does.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
pip install "langchain-obscate[agents]"
|
|
88
|
+
|
|
89
|
+
from langchain.agents import create_agent
|
|
90
|
+
from langchain_obscate import ObscateMiddleware
|
|
91
|
+
|
|
92
|
+
agent = create_agent("anthropic:claude-haiku-5-5", tools=[send_email],
|
|
93
|
+
middleware=[ObscateMiddleware()])
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
**Explicit tools:** use `ObscateRedactTool` (fpe-redacts a text) and
|
|
97
|
+
`ObscateDetectTool` (labels and counts only). Use them when the agent itself
|
|
98
|
+
should scrub a record before passing it downstream. The agent's own LLM still
|
|
99
|
+
sees the tool input, so use the middleware to protect against the provider.
|
|
100
|
+
|
|
101
|
+
### Why middleware rather than a callback
|
|
102
|
+
|
|
103
|
+
LangChain callbacks are observers. They are told what is sent to the model
|
|
104
|
+
but cannot change it. Redaction has to rewrite the request, so it lives in a
|
|
105
|
+
Runnable wrapper (chains) and in agent middleware (agents). The quickstart
|
|
106
|
+
uses a callback only to *show* you what the provider receives.
|
|
107
|
+
|
|
108
|
+
## Strategies
|
|
109
|
+
|
|
110
|
+
| strategy | LLM sees | restore needs | notes |
|
|
111
|
+
|---|---|---|---|
|
|
112
|
+
| `fpe` (default) | `seab.yomog@tziwxuo.com`, `7982 1772 2838 5004`, `[PERSON:…]` | your API key only | formats kept (valid-looking card numbers, emails). Values that can't keep their format fall back to bracketed `[LABEL:…]` tokens |
|
|
113
|
+
| `tokenize` | `[EMAIL_1]`, `[PERSON_1]` | the token map (held in memory for one call) | clearest for the model; consistent across all messages of one call |
|
|
114
|
+
| `synthetic` | realistic fake names/emails | the token map | most natural prompts |
|
|
115
|
+
| `mask` / `hash` / `partial` | `****`, hashes, `****1234` | not restorable | output stays redacted |
|
|
116
|
+
|
|
117
|
+
More: [strategies](https://obscate.com/docs/strategies).
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
with_obscate(llm, strategy="tokenize", labels=["EMAIL", "PHONE"], min_confidence=0.5)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## What to expect
|
|
124
|
+
|
|
125
|
+
- **Detection quality.** Structured IDs (email, phone, credit card, Aadhaar,
|
|
126
|
+
PAN, GSTIN, IBAN, SSN, IP, AWS keys) are near-perfect because they use
|
|
127
|
+
patterns and checksums. Names and places use an NER model and are
|
|
128
|
+
best-effort, so some will get through. Use `labels` and test on your data.
|
|
129
|
+
([Detectors](https://obscate.com/docs/detectors), [benchmark](https://obscate.com/docs/benchmark).)
|
|
130
|
+
- **fpe caveat.** If the model *invents* a new email, phone or ID that was
|
|
131
|
+
never redacted, fpe restore cannot tell it from a token and turns it into a
|
|
132
|
+
different value. Use `tokenize` if your model makes up contact details.
|
|
133
|
+
- **Key versions are handled for you.** Each redaction records the
|
|
134
|
+
`key_version` of your account's key, and the wrapper sends it back on
|
|
135
|
+
restore. A round trip keeps working even if Obscate rotates keys mid-call.
|
|
136
|
+
If you keep a `RestoreContext` (or fpe output) to restore later, keep its
|
|
137
|
+
`key_version` too.
|
|
138
|
+
- **Cost.** One Obscate request per model call (the whole conversation goes
|
|
139
|
+
in one request, 1 unit per 100 KB). Restores are free. A 5-step agent run
|
|
140
|
+
uses 5 units, so the free tier covers about 200 such runs a month.
|
|
141
|
+
([Pricing](https://obscate.com/pricing).)
|
|
142
|
+
- **Streaming is buffered.** `stream()` on the wrapper yields one restored
|
|
143
|
+
chunk at the end. With the agent middleware, `stream_mode="messages"` shows
|
|
144
|
+
the raw, still-redacted tokens; the messages in agent state are restored.
|
|
145
|
+
- **Fails closed.** If Obscate errors (network, quota, 503), the LLM is not
|
|
146
|
+
called and `ObscateError` is raised.
|
|
147
|
+
- **Self-hosted.** Set `OBSCATE_BASE_URL` to your instance. The self-hosted
|
|
148
|
+
edition is in pilot; ask contact@obscate.com.
|
|
149
|
+
|
|
150
|
+
## Privacy
|
|
151
|
+
|
|
152
|
+
This package never logs, prints or writes the text, the detected values or
|
|
153
|
+
the token map. Token maps live in memory for one call and are hidden from
|
|
154
|
+
`repr()`. Errors carry the HTTP status and the API's fixed message only. This
|
|
155
|
+
is enforced by `tests/test_langchain_obscate.py::test_privacy_*`.
|
|
156
|
+
|
|
157
|
+
## Develop
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
pip install -e '.[test]' && pytest -q # unit tests against an in-process fake API (no network)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
License: MIT.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""langchain-obscate end-to-end: redact in -> LLM -> restore out.
|
|
2
|
+
|
|
3
|
+
pip install "langchain-obscate[examples]"
|
|
4
|
+
export OBSCATE_API_KEY=ob_... # free key: https://obscate.com
|
|
5
|
+
export ANTHROPIC_API_KEY=sk-ant-... # optional; without it a local stand-in LLM is used
|
|
6
|
+
python examples/quickstart.py
|
|
7
|
+
|
|
8
|
+
Costs: 1 Obscate request per model call (the free tier is 1,000 a month) and
|
|
9
|
+
one small LLM call if ANTHROPIC_API_KEY is set.
|
|
10
|
+
"""
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from langchain_core.callbacks import BaseCallbackHandler
|
|
15
|
+
from langchain_core.messages import AIMessage
|
|
16
|
+
from langchain_core.prompts import ChatPromptTemplate
|
|
17
|
+
from langchain_core.output_parsers import StrOutputParser
|
|
18
|
+
|
|
19
|
+
from langchain_obscate import with_obscate
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def load_env() -> None:
|
|
23
|
+
"""Read KEY=VALUE lines from a .env next to this file or in a parent folder (never printed)."""
|
|
24
|
+
for d in [Path.cwd(), *Path(__file__).resolve().parents]:
|
|
25
|
+
f = d / ".env"
|
|
26
|
+
if f.is_file():
|
|
27
|
+
for line in f.read_text().splitlines():
|
|
28
|
+
if "=" in line and not line.lstrip().startswith("#"):
|
|
29
|
+
k, v = line.split("=", 1)
|
|
30
|
+
os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))
|
|
31
|
+
return
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ShowWhatTheLLMSees(BaseCallbackHandler):
|
|
35
|
+
"""Demo only: prints the prompt exactly as the LLM provider receives it."""
|
|
36
|
+
def on_chat_model_start(self, serialized, messages, **kw):
|
|
37
|
+
for m in messages[0]:
|
|
38
|
+
print(f" [{m.type}] {m.content}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def get_llm():
|
|
42
|
+
if os.environ.get("ANTHROPIC_API_KEY"):
|
|
43
|
+
from langchain_anthropic import ChatAnthropic
|
|
44
|
+
return ChatAnthropic(model=os.environ.get("ANTHROPIC_MODEL", "claude-haiku-5-5"), max_tokens=1024), True
|
|
45
|
+
# Offline stand-in so the example runs without an LLM key: it replies using what it received.
|
|
46
|
+
from langchain_core.language_models import BaseChatModel
|
|
47
|
+
from langchain_core.outputs import ChatGeneration, ChatResult
|
|
48
|
+
|
|
49
|
+
class StandInLLM(BaseChatModel):
|
|
50
|
+
@property
|
|
51
|
+
def _llm_type(self):
|
|
52
|
+
return "stand-in"
|
|
53
|
+
|
|
54
|
+
def _generate(self, messages, stop=None, run_manager=None, **kw):
|
|
55
|
+
words = messages[-1].content.split()
|
|
56
|
+
email = words[words.index("(email") + 1] if "(email" in words else "?"
|
|
57
|
+
return ChatResult(generations=[ChatGeneration(message=AIMessage(
|
|
58
|
+
f"(stand-in LLM) We are refunding the duplicate charge and will confirm by email to {email}."))])
|
|
59
|
+
return StandInLLM(), False
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def main() -> None:
|
|
63
|
+
load_env()
|
|
64
|
+
if not os.environ.get("OBSCATE_API_KEY"):
|
|
65
|
+
raise SystemExit("Set OBSCATE_API_KEY (free key at https://obscate.com) or put it in a .env file.")
|
|
66
|
+
llm, real = get_llm()
|
|
67
|
+
prompt = ChatPromptTemplate.from_messages([
|
|
68
|
+
("system", "You are a support agent. Reply in two sentences and repeat the customer's "
|
|
69
|
+
"email address and phone number exactly as given."),
|
|
70
|
+
("human", "{ticket}"),
|
|
71
|
+
])
|
|
72
|
+
chain = with_obscate(prompt | llm | StrOutputParser()) # strategy="fpe" by default
|
|
73
|
+
|
|
74
|
+
ticket = ("Customer Ravi Kumar (email ravi.kumar@example.com phone +91 98765 43210) "
|
|
75
|
+
"says card 4242 4242 4242 4242 was charged twice. Please draft a reply.")
|
|
76
|
+
print("1) Your input:\n ", ticket)
|
|
77
|
+
print("2) What the LLM receives:" + ("" if real else " (stand-in LLM, set ANTHROPIC_API_KEY for a real one)"))
|
|
78
|
+
answer = chain.invoke({"ticket": ticket}, config={"callbacks": [ShowWhatTheLLMSees()]})
|
|
79
|
+
print("3) Restored answer for your user:\n ", answer)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
if __name__ == "__main__":
|
|
83
|
+
main()
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "langchain-obscate"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Reversible PII redaction for LangChain: redact before the LLM, restore after (Obscate API)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Skycast" }]
|
|
13
|
+
keywords = ["langchain", "pii", "redaction", "privacy", "llm", "agents", "dpdp", "gdpr"]
|
|
14
|
+
dependencies = ["langchain-core>=1.0,<2", "httpx>=0.27"]
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
agents = ["langchain>=1.0,<2"]
|
|
18
|
+
examples = ["langchain-anthropic>=1.0", "python-dotenv>=1.0"]
|
|
19
|
+
test = ["pytest>=8", "anyio>=4", "langchain>=1.0,<2"]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://obscate.com"
|
|
23
|
+
Documentation = "https://obscate.com/docs/langchain"
|
|
24
|
+
|
|
25
|
+
[tool.hatch.build.targets.wheel]
|
|
26
|
+
packages = ["src/langchain_obscate"]
|
|
27
|
+
|
|
28
|
+
[tool.pytest.ini_options]
|
|
29
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Obscate for LangChain: reversible PII redaction around any LLM, chain or agent."""
|
|
2
|
+
from ._client import ObscateClient, ObscateError, RestoreContext
|
|
3
|
+
from .redactor import ObscateRedactor
|
|
4
|
+
from .runnable import ObscateRedaction, with_obscate
|
|
5
|
+
from .tools import ObscateDetectTool, ObscateRedactTool
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
__all__ = ["ObscateClient", "ObscateError", "RestoreContext", "ObscateRedactor", "ObscateRedaction",
|
|
9
|
+
"with_obscate", "ObscateMiddleware", "ObscateRedactTool", "ObscateDetectTool"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def __getattr__(name): # ObscateMiddleware needs the `langchain` package (agents), not just langchain-core
|
|
13
|
+
if name == "ObscateMiddleware":
|
|
14
|
+
from .middleware import ObscateMiddleware
|
|
15
|
+
return ObscateMiddleware
|
|
16
|
+
raise AttributeError(name)
|