Metadata-Version: 2.4
Name: langchain-maskena
Version: 0.1.0
Summary: LangChain integration for Maskena: block prompt injection in user input and retrieved documents, and load documents sanitized for RAG.
Author-email: Maskena <dev@maskena.com>
License-Expression: MIT
Project-URL: Homepage, https://maskena.com
Project-URL: Documentation, https://maskena.com/docs?lang=en
Keywords: langchain,prompt injection,llm,rag,security,pii
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: maskena<1,>=0.1.0
Requires-Dist: langchain-core<2,>=1.0
Dynamic: license-file

# langchain-maskena

[LangChain](https://python.langchain.com) integration for [Maskena](https://maskena.com/docs?lang=en): stop prompt
injection in user input and in retrieved documents, and load documents with hidden text and personal data removed.

| Component | Where it goes | What it does |
|---|---|---|
| `MaskenaGuard` | Before the prompt | Blocks dangerous user input; continues with the clean version when it is suspicious |
| `MaskenaDocumentCompressor` | After the retriever | Drops dangerous retrieved documents; cleans suspicious ones (indirect prompt injection) |
| `MaskenaLoader` | Ingestion | Loads files through RAG sanitization: only safe content, already split into chunks |

## Installation

```bash
pip install langchain-maskena
export MASKENA_API_KEY="sfk_..."     # create a key in the dashboard, under API
```

Requires Python 3.11 or later and `langchain-core` 1.x.

## Guarding user input

```python
from langchain_core.prompts import ChatPromptTemplate
from langchain_maskena import MaskenaBlockedError, MaskenaGuard

prompt = ChatPromptTemplate.from_messages([("system", "You are a support assistant."), ("human", "{question}")])
chain = {"question": MaskenaGuard()} | prompt | llm

try:
    answer = chain.invoke(user_message)
except MaskenaBlockedError as e:
    answer = "Sorry, I can't help with that request."
    log.warning("blocked: %s %s", e.outcome.verdict, [f.rule_id for f in e.outcome.findings])
```

`MaskenaGuard` accepts a string, a dict of prompt variables, a list of messages or a prompt value, and returns the
same type. With a dict, use `input_keys=["question"]` to check only some keys. With messages, only human messages are
checked unless `check_all_messages=True`.

## Guarding retrieved documents

Documents retrieved from a vector store can carry instructions planted by whoever wrote them. Check them before the
model reads them:

```python
from langchain_classic.retrievers import ContextualCompressionRetriever
from langchain_maskena import MaskenaDocumentCompressor

retriever = ContextualCompressionRetriever(
    base_compressor=MaskenaDocumentCompressor(),
    base_retriever=vector_store.as_retriever(),
)
docs = retriever.invoke("How long do refunds take?")
```

Kept documents carry `maskena_verdict`, `maskena_score` and `maskena_cleaned` in their metadata. You can also call
`compressor.compress_documents(docs, query)` directly, or `acompress_documents` for parallel checks
(`max_concurrency`, default 8).

## Loading documents for RAG

```python
from langchain_maskena import MaskenaLoader

docs = MaskenaLoader(["contract.pdf", "manual.docx"], policy="redact", chunk_size=1200).load()
vector_store.add_documents(docs)
```

Hidden text (white, microscopic, off-page or covered by other elements) is removed based on how each page renders,
before anything reaches your index. Each chunk becomes a `Document` with `source`, `page_start`, `page_end`,
`maskena_risk`, `maskena_status` and `maskena_job_id` in its metadata. Chunks in quarantine (`policy="drop"`) are not
returned.

## Decision rule

All components use the same rule:

| Option | Values | Default |
|---|---|---|
| `block_on` | `"dangerous"`, `"flagged"` (also suspicious), `"never"` | `"dangerous"` |
| `use_clean_text` | `"flagged"`, `"always"`, `"never"` | `"flagged"` |

Blocked input raises `MaskenaBlockedError`; blocked documents are dropped. The clean version removes dangerous passages
and replaces personal data with placeholders such as `[EMAIL 1]`. With `use_clean_text="always"`, personal data is
removed from every text, not only from flagged ones.

Texts longer than 32,000 characters are split and checked in parts.

## Configuration and costs

```python
MaskenaGuard(api_key="sfk_...", base_url="https://maskena.com", language="en", depth="standard")
```

Each guarded text or document uses one text check from the monthly quota, and `MaskenaLoader` uses one RAG page per
page. To reuse a configured client (proxies, retries), pass `client=maskena.Maskena(...)` and
`async_client=maskena.AsyncMaskena(...)`.

## Links

- [API documentation](https://maskena.com/docs?lang=en)
- [Detection accuracy](https://maskena.com/precisao?lang=en)
- [Python SDK](https://pypi.org/project/maskena/)

## License

MIT
