Skip to main content

Blindsight Runtime Security: Python SDK

The official Python client for Blindsight Runtime Security. 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

pip install blindsight-security

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

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:

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.

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:

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:

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

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

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.

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:

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:

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:

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.
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

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.

Metadata

Release files for blindsight-security 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for blindsight-security 1.0.0
File Size Uploaded Provenance Actions
blindsight_security-1.0.0.tar.gz 27.6 kB Without provenance Details for blindsight_security-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for blindsight-security 1.0.0
File Interpreter ABI Platform Actions
blindsight_security-1.0.0-py3-none-any.whl Python 3 none any Details for blindsight_security-1.0.0-py3-none-any.whl

Total release size: 54.6 kB

Release files / blindsight_security-1.0.0.tar.gz

Download URL blindsight_security-1.0.0.tar.gz
Size 27.6 kB
Tags Source
SHA-256 checksum
How to use checksums
ef4d0aaf93eb450e073d501e39128ebd69bb3af3e4c381be88919383567b03c3
BLAKE2b-256 checksum
How to use checksums
b9258654601729836f06c39836d55516f13903677185e3c4cb06ff024b7e34da
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / blindsight_security-1.0.0-py3-none-any.whl

Download URL blindsight_security-1.0.0-py3-none-any.whl
Size 27.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
32809786ebd4ddd8eb0a7bc3f66a56f9984d7de4222cc53638820abe7ba951d8
BLAKE2b-256 checksum
How to use checksums
99f37eb27b4a20ac7df172fb509ece3226e206828b6a3d88dbb0f1f1f26f2bf8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Security for blindsight-security 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page