Metadata-Version: 2.4
Name: blindsight-security
Version: 1.0.0
Summary: Official Python SDK for Blindsight Runtime Security: scan prompts, responses, files and tool-calls, or route your LLM traffic through the guardrail reverse proxy.
Author: Blindsight Technologies AG
License-Expression: Apache-2.0
Project-URL: Homepage, https://blindsight.io
Project-URL: Documentation, https://docs.blindsight.io
Keywords: blindsight,runtime-security,llm,guardrails,dlp,prompt-injection,pii
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: httpx>=0.27
Provides-Extra: openai
Requires-Dist: openai>=1.0; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.25; extra == "anthropic"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: mypy>=1.8; extra == "dev"
Dynamic: license-file

# Blindsight Runtime Security: Python SDK

The official Python client for [Blindsight Runtime Security](https://blindsight.io).
Inspect prompts, responses, files, and agent tool-calls for prompt injection and
sensitive data, or route your existing LLM client through the guardrail proxy.

## Requirements

- Python 3.9 or later
- A single runtime dependency (`httpx`)

## Installation

```bash
pip install blindsight-security
```

Optional extras add convenience factories that return a preconfigured vendor client:

```bash
pip install "blindsight-security[openai]"      # rs.proxy.openai_client()
pip install "blindsight-security[anthropic]"   # rs.proxy.anthropic_client()
```

## Quick start

Scan the prompt before it reaches the model, and the response before it reaches
the user:

```python
from openai import OpenAI
from blindsight_security import RuntimeSecurity

rs = RuntimeSecurity(
    base_url="https://platform.blindsight.io",
    api_key="ak_…",
    app_id="<App id>",          # optional
)
openai = OpenAI()

verdict = rs.scan_input(user_text, provider="openai", model="gpt-4o")
if verdict.blocked:
    raise PermissionError(verdict.blocked_reason)
safe_prompt = verdict.safe_text          # redacted when the prompt carries PII

completion = openai.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": safe_prompt}],
)
answer = completion.choices[0].message.content

result = rs.scan_output(answer, prompt=safe_prompt)
final = result.safe_text                 # empty when blocked
```

## Scanning

### Content the user did not write

If the prompt is assembled from more than the user's own words, say so. Pass the
retrieved documents, tool results, fetched pages or email bodies as untrusted
spans and the firewall judges them as data: inside a declared span an
instruction aimed at the assistant is a finding however ordinary it sounds,
because the user never asked for it.

```python
from blindsight_security import UntrustedSpan

verdict = rs.scan_input(
    prompt,
    untrusted=[
        UntrustedSpan.retrieved(chunk, label="kb-8842"),
        UntrustedSpan.tool_result(tool_output, label="calendar"),
    ],
)

for i in verdict.flagged_span_indices:
    logger.warning("span %s was steering the model; dropping it", i)
```

Why it matters: the hardest indirect injections are not menacing. "Summarize
the main findings of the 2020 climate report" is the most ordinary request there
is from a user, and an attack from inside a retrieved document. Nothing in the
text separates the two, only where it came from.

`tool_result` and `web` are strict by default, because a tool returning prose
that tells the assistant what to do next is compromised or misdesigned. The
others are balanced, because retrieved prose legitimately contains imperatives
and questions. Override per span with `strictness="strict"` or `"balanced"`.
A bare string is accepted and defaults to `retrieval`. At most 32 spans, and
only `scan_input` takes them.

Findings come back per span on `verdict.untrusted`, so an offending document can
be dropped or re-fetched without failing the whole request. `verdict.untrusted`
is `None` when no spans were declared, which is not the same as declared and
clean.

### Conversations

An App can act on one kind of personal data only when another has been part of
the same conversation, for example mask a person's name only once a national
ID or an account number has appeared, in an earlier turn or a later one. Name
the conversation with `session_id` and, optionally, number the turns:

```python
result = rs.scan_input(prompt, session_id=conversation_id, turn=3)

conv = result.conversation  # None when the App has no conversation conditions
if conv and conv["exposed_earlier"]:
    # An earlier turn sent a value out before this turn's trigger arrived.
    for item in conv["exposed_earlier"]:
        purge_turn(item["turn"])
```

`conv["state"]` is `new`, `continued`, `unknown` (a later turn of a
conversation the platform no longer remembers), `saturated` or `unavailable`.
In the last three the App's setting decides: by default every target is masked
as if its trigger had been seen. A retried call with the same `turn` is not
counted twice. The platform remembers keyed hashes and data-type labels, never
the values or the conversation id.

### Pseudonymize and restore

On an App set to pseudonymize, personal data comes back as placeholders such
as `<PERSON_1>` and `<EMAIL_ADDRESS_1>`, with a mapping to the real values in
`result.pseudonyms`. Send the placeholders to your model and put the values
back in its reply:

```python
inp = rs.scan_input(user_text, session_id=conversation_id)
reply = call_your_model(inp.safe_text)            # the model sees placeholders only
out = rs.scan_output(reply, prompt=inp.safe_text, session_id=conversation_id)
if out.blocked:
    return "Sorry, I can't help with that."
safe = out.safe_text
for token in (out.pseudonyms or {}):              # data the model wrote on its own
    safe = safe.replace(token, "[hidden]")
final = inp.restore(safe)                         # the user's own values go back in
```

Each call numbers its placeholders from 1, so `<PERSON_1>` in two calls can
be two people. If your model is given the earlier turns too, renumber each
turn into one numbering for the conversation before you send it, and restore
with that conversation's mapping.

Send the same `session_id` for a whole conversation and the text the model
saw as `prompt`. Hiding the output's own placeholders before restoring means a
value the model wrote itself is never replaced by one of your user's values.
A placeholder is `<KIND_n>`, sometimes with a short tag before the number
(`<PERSON_T3_1>`); `restore` handles both. The mapping is in the response
only. Keep it server-side and never log it.

### Files

```python
with open("resume.pdf", "rb") as f:
    result = rs.scan_file(f.read(), filename="resume.pdf", media_type="application/pdf")

if result.was_redacted:
    open("resume.clean.pdf", "wb").write(result.file_bytes)
```

### Agent tool-calls

```python
gate = rs.scan_tool_call("delete_file", {"path": requested_path})
gate.raise_for_block()                   # raises ContentBlocked on a block verdict
delete_file(**gate.safe_arguments)
```

### MCP tool verification

Verify an MCP tool's integrity before you trust it. This scans the description
for poisoning, pins its description/schema on first use to catch a later
**rug-pull** or **schema poisoning**, flags cross-server **shadowing**, and can
scan a tool's returned output for injected content. The verdict honours the
App's configured enforcement mode.

```python
check = rs.verify_tool(
    server="example-mcp",
    name="send_email",
    description=tool.description,
    schema=tool.input_schema,        # optional; enables schema-poisoning detection
)
check.raise_for_block()              # blocks a rug-pulled / shadowed tool
if check.rug_pull or check.shadowed:
    ...                              # or handle it yourself

# Scan a result the tool returned (indirect prompt injection, ASCII smuggling):
rs.verify_tool("example-mcp", "search", tool_result=result_text).raise_for_block()
```

`MCPVerifyResult` exposes `verdict`, `reasons`, `registry`, `shadowing`,
`description_scan`, `result_scan`, `max_severity`, `blocked_reason`, the
convenience flags `allowed` / `flagged` / `blocked` / `rug_pull` / `shadowed`,
and `raise_for_block()`.

### Batch

Up to 32 texts in a single round-trip:

```python
results = rs.scan_batch([
    {"text": doc_a, "direction": "input"},
    {"text": doc_b, "direction": "input"},
])
```

### Result fields

Every result exposes `uuid`, `verdict`, `injection`, `pii`, `redacted_text`,
`blocked_reason`, `latency_ms`, and `text_length`, along with the convenience
accessors `allowed` / `flagged` / `was_redacted` / `blocked`, `safe_text`,
`injection_score`, `pii_categories`, `raise_for_block()`, and `raw` (the full
JSON response).

## Reverse proxy

Route an existing vendor client through the guardrail without writing explicit
scan calls:

```python
from openai import OpenAI
client = OpenAI(api_key=OPENAI_KEY, **rs.proxy.openai())

from anthropic import Anthropic
anthropic = Anthropic(api_key=ANTHROPIC_KEY, **rs.proxy.anthropic())
```

Additional providers are available via `rs.proxy.gemini()`, `rs.proxy.vertex()`,
`rs.proxy.bedrock()`, and `rs.proxy.openai_compatible(provider="groq")`.

### LangChain and LlamaIndex

Both frameworks wrap the OpenAI client, so the proxy configuration applies
directly:

```python
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o", api_key=OPENAI_KEY, **rs.proxy.openai())

from llama_index.llms.openai import OpenAI as LlamaOpenAI
cfg = rs.proxy.openai()
llm = LlamaOpenAI(
    model="gpt-4o",
    api_key=OPENAI_KEY,
    api_base=cfg["base_url"],
    default_headers=cfg["default_headers"],
)
```

## Error handling

All exceptions derive from `BlindsightError`:

- `BlindsightAPIError`: a non-2xx answer, with `.status_code`, `.code` (for
  example `APP_NOT_ALLOWED`) and `.retry_after` when the answer gave one
  - `BlindsightAuthError` (401 / 403): a wrong, revoked or expired key, or a
    key not allowed for this App
  - `BlindsightQuotaError` (402 / 429). A 429 with code
    `DAILY_ALLOWANCE_SOFT_LIMIT` is temporary: requests are paced, so wait
    `.retry_after` seconds and send the same call again
- `BlindsightConnectionError`: no answer (network failure or timeout)
- `ContentBlocked`: raised by `raise_for_block()` on a block verdict

Error messages never contain your key or the text you sent.

### When Blindsight cannot answer

The client never answers for you. Every failure is an exception, so nothing
reaches your model unscanned unless your own code decides to send it. Choose
what your application does in that case: refusing to answer is the safe
default; answering without protection sends personal data to your model.

- `timeout` (default 10 seconds) bounds each request.
- `max_retries` (default 2) retries a 429 or a 503, and a connection
  that never reached the server, with a growing pause and `Retry-After`
  honoured. A timeout is never retried, because the scan may already have run.
- `max_retry_wait` (default 30 seconds) caps the time all retries of one call
  may wait. A longer `Retry-After` is not waited for: the error is raised at
  once, with `.retry_after` set.

```python
rs = RuntimeSecurity(base_url=..., api_key=..., timeout=5, max_retries=2, max_retry_wait=10)
try:
    verdict = rs.scan_input(user_text)
except BlindsightConnectionError:
    return "The assistant is unavailable for a moment."   # fail closed
```

## Development

```bash
pip install -e ".[dev]"
pytest
```

## License

Apache-2.0, Copyright 2026 Blindsight Technologies AG: see `LICENSE` and
`NOTICE`. The license covers this client library; the Blindsight service it connects to stays under Blindsight's own
terms of service.
