> ## Documentation Index
> Fetch the complete documentation index at: https://silmaril.security/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Install the Python SDK, classify user input and tool output, and handle blocks with synchronous or asynchronous clients.

## Prerequisites

Use Python 3.10 or later.

Set `SILMARIL_API_KEY` and `SILMARIL_API_URL` from your [deployment access](https://silmaril.security/docs/start/access.md).

## Install

```sh theme={"theme":"github-light-default"}
pip install silmaril-security-sdk==0.10.0
```

## Classify your first request

Create one client per protected system and reuse it. Label each call with the boundary it checks.

```python theme={"theme":"github-light-default"}
import logging
import os

from silmaril_security.sdk import (
    Firewall,
    FirewallBlockedException,
    HookLabel,
    SilmarilApiError,
)

logging.basicConfig(level=logging.INFO)

fw = Firewall(
    api_key=os.environ["SILMARIL_API_KEY"],
    api_url=os.environ["SILMARIL_API_URL"],
)

try:
    result = fw.classify(
        "Summarize this release note.",
        hook=HookLabel.USER_INPUT,
    )
    logging.info("prediction=%s score=%.4f", result.prediction, result.score)
except FirewallBlockedException as exc:
    logging.warning("block score=%.4f threshold=%.4f", exc.score, exc.threshold)
except SilmarilApiError as exc:
    logging.error("Silmaril API error: %s", exc)
    raise
```

For tool output, pass the tool name as well.

```python theme={"theme":"github-light-default"}
fw.classify(
    tool_output,
    hook=HookLabel.TOOL_RESPONSE,
    tool_name="read_file",
)
```

### Expected result

A benign request logs `prediction=BENIGN` and its score. When the effective mode is Block, a malicious request raises `FirewallBlockedException`. Its `result` holds the full verdict. In Shadow or Warn mode the call returns the result instead, so route on `result.prediction`.

See [confidence scores](https://silmaril.security/docs/guides/enforcement.md#confidence-scores) for score meaning and threshold behavior.

A per-call `mode` override wins the client setting. Either local choice is sent with the request and preserved in `result.mode`. Without a local override, current classify responses omit `mode`. `result.mode` remains `None`, and the SDK uses Block as its enforcement fallback. Choose Shadow or Warn explicitly on the client or call when that boundary should be observational. Classification callbacks inherit the same effective behavior. Outcome meanings and recommended actions are in the [outcome taxonomy](https://silmaril.security/docs/sdk/outcomes.md#outcome-taxonomy).

`SilmarilApiError` means the API returned a non-2xx response after retries. Network failures raise the underlying `requests` exception. Neither is a verdict, so decide whether that boundary fails open or closed.

LangChain and LangGraph handlers for this client are documented in [Framework SDKs](https://silmaril.security/docs/integrations/frameworks.md).

## Caller-owned HTTP sessions

Starting with SDK 0.7.1, a supplied `requests.Session` keeps its default headers.
The SDK attaches its API key to each Firewall request, so unrelated calls through
that session do not inherit the key. Reuse a client for repeated classifications.

## Governance context

`GovernanceContext.agent` is caller attribution, not policy-authoritative
identity. Setting it does not activate agent-scoped rules. Those rules match
the authenticated principal binding configured by the server.
`GovernanceContext.resource` is serialized as the request's top-level
`resource` and matches canonical resource rules. A malicious prediction or an
explicit governance block raises `FirewallBlockedException` in Block mode.

```python theme={"theme":"github-light-default"}
from silmaril_security.sdk import GovernanceContext, GovernanceResource

context = GovernanceContext(
    agent="research-agent",  # Caller attribution.
    resource=GovernanceResource(  # Matches canonical resource rules.
        kind="tool",
        id="search",
    ),
)

try:
    result = fw.classify(
        "Search for the latest release notes",
        hook=HookLabel.TOOL_CALL,
        tool_name="search",
        governance=context,
    )
except FirewallBlockedException as exc:
    decision = exc.result.governance
    logging.warning(
        "blocked: prediction=%s action=%s rule=%s",
        exc.result.prediction,
        decision.action if decision else None,
        decision.rule_id if decision else None,
    )
    raise
else:
    if result.governance is not None:
        logging.info(
            "governance action=%s policy=%s",
            result.governance.action,
            result.governance.policy_version,
        )
```

For `classify_batch()`, pass one optional governance context per input using
`governance=[context, None, ...]`. Each item also keeps its own metadata,
including `metadata.conversationId`. That value is carried with the item.
The current batch classifier treats each input independently and neither reads
nor updates conversation history for that batch. See
[Batch calls and conversation history](#batch-calls-and-conversation-history).
In Warn or Shadow mode, inspect `result.prediction` and, only when
`result.governance is not None`, `result.governance.action` because the SDK
returns the verdict instead of raising. Older backends may omit
`result.governance`.

## Batch calls and conversation history

Pass `metadata={"conversationId": conversation_id}` on each ordered synchronous or asynchronous `classify()` call. Wait for and handle its verdict or error before sending the next event.

`classify_batch()` preserves per-item metadata and treats items independently of conversation history.

See [events and conversations](https://silmaril.security/docs/guides/events.md) for sequencing and [modes and enforcement](https://silmaril.security/docs/guides/enforcement.md) for returned verdicts in Warn and Shadow.

## Async classify

Install async support before using `AsyncFirewall`.

```sh theme={"theme":"github-light-default"}
pip install "silmaril-security-sdk[async]==0.10.0"
```

```python theme={"theme":"github-light-default"}
import asyncio
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from silmaril_security.sdk import AsyncFirewall, HookLabel

@asynccontextmanager
async def firewall_lifespan() -> AsyncIterator[AsyncFirewall]:
    async with AsyncFirewall(
        api_key=os.environ["SILMARIL_API_KEY"],
        api_url=os.environ["SILMARIL_API_URL"],
    ) as fw:
        yield fw  # share with request handlers until shutdown

async def handle_request(fw: AsyncFirewall, first_input: str, second_input: str):
    # Independent events in different conversations.
    return await asyncio.gather(
        fw.classify(
            first_input,
            hook=HookLabel.USER_INPUT,
            metadata={"conversationId": "conv-a"},
        ),
        fw.classify(
            second_input,
            hook=HookLabel.USER_INPUT,
            metadata={"conversationId": "conv-b"},
        ),
    )
```

Share one `AsyncFirewall` across tasks on one event loop for the service lifetime and close it at shutdown. The gathered calls are independent events or different conversations. Ordered events that share one `metadata.conversationId` wait for each `classify()` call before the next event is sent. Cancellation stops the calling task's request. Async calls raise the same block exceptions as the synchronous client. For a synchronous off-thread fallback, create one `Firewall` per worker thread.

## Classify in parallel

From SDK 0.10.0, `protect()` runs your call while its input is classified instead of waiting for the verdict first. It returns your call's result. Both `Firewall.protect()` and `AsyncFirewall.protect()` accept `hook`, `tool_name`, `metadata`, `governance`, `mode`, `review`, and `request_id` as classification options. Use `mode` to choose enforcement for the call. The legacy `shadow_mode` keyword is available on `classify()`.

```python theme={"theme":"github-light-default"}
answer = fw.protect(
    lambda: call_model(prompt),
    text=prompt,
    hook=HookLabel.USER_INPUT,
    metadata={"conversationId": conversation_id},
    output=lambda response: response.text,
)
```

`call_model`, `prompt`, and `conversation_id` belong to your application. With `AsyncFirewall`, pass a function that returns an awaitable and await `protect()`.

| Effective mode | Behavior |
| - | - |
| Block | Withholds the result until the verdict arrives. A would-block decision raises `FirewallBlockedException`. `AsyncFirewall` also cancels your call when the block arrives first; a synchronous call runs to completion and its result is discarded |
| Shadow or Warn | Returns your result immediately. The classification finishes in the background and reports through `on_classify` |

The optional `output` function extracts text from the result. That text is classified as `llm_output` before the result is returned in Block mode, and in the background in Shadow or Warn.

Use `protect()` for calls whose effect can be discarded, such as a model call. Classify the arguments of a tool that writes with `classify()` before running it.

Classifications that share one `metadata.conversationId` are sent in the order they started, so `protect()` keeps the conversation sequence without waiting between events. Two client options bound this work: `max_concurrent` (default 32) limits classifications in flight, and `max_queued` (default 64) limits unjoined background classifications per conversation. Background classifications are also capped at `max_concurrent * max_queued` across all conversations. A background classification retries once, and one that would exceed either limit is dropped with a logged warning. Metadata is copied when `protect()` starts, so changing it afterwards does not change a classification already under way.

Call `fw.flush()` to wait for background classifications, for example before a serverless handler returns. `AsyncFirewall` exposes `await fw.flush()`, and `aclose()` drains background work before closing. An async LangChain handler created from a synchronous `Firewall` tracks its own background checks, so await `handler.flush()` there. With the synchronous client, `on_classify` runs on a worker thread for classifications started by `protect()`.

## Shadow mode

An explicit local Shadow mode returns results instead of raising block exceptions, so you can measure would-block decisions while traffic continues. Per-call overrides let one boundary enforce before you change the client setting. Direct `classify()` calls still wait for and return each verdict. `protect()`, LangChain handlers, and Deep Agents middleware classify in the background in Shadow mode.

```python theme={"theme":"github-light-default"}
import logging
import os
from silmaril_security.sdk import ClassifyEvent, Firewall, HookLabel

def on_classify(event: ClassifyEvent) -> None:
    if event.blocked and event.shadow_mode:
        logging.info("would block %s score=%.4f", event.hook, event.result.score)

fw = Firewall(
    api_key=os.environ["SILMARIL_API_KEY"],
    api_url=os.environ["SILMARIL_API_URL"],
    shadow_mode=True,
    on_classify=on_classify,
)

result = fw.classify(text, hook=HookLabel.TOOL_RESPONSE)
```

### Enforce one boundary

```python theme={"theme":"github-light-default"}
fw.classify(text, hook=HookLabel.TOOL_RESPONSE, shadow_mode=False)
```

This call overrides Shadow mode and enforces its verdict.

## Errors

Direct calls raise `FirewallBlockedException` when a block is enforced. It carries `score`, `threshold`, and the full `result`.

```python theme={"theme":"github-light-default"}
try:
    fw.classify(user_input, hook=HookLabel.USER_INPUT)
except FirewallBlockedException as exc:
    logging.warning("blocked score=%.4f threshold=%.4f", exc.score, exc.threshold)
```

Read `exc.result` for the verdict, or use shadow mode when you need the result without a block exception. Outcome meanings and recommended actions are in the [outcome taxonomy](https://silmaril.security/docs/sdk/outcomes.md#outcome-taxonomy).

### HTTP 408 handling

Python retries HTTP `408` by default, including the direct runtime request-body timeout before classification. Configure `max_retries=0` to disable retries. This timeout closes the connection and produces no verdict. It does not establish replay safety for model or tool operations.

## Review depth

See [review depth](https://silmaril.security/docs/guides/review-depth.md) for minimum SDK versions and selection behavior.

The public `ReviewLevel` type accepts only `"standard"` or `"deep"`. Pass `review` to `Firewall` or `AsyncFirewall` for an explicit client default, and to synchronous or asynchronous `classify()` and `classify_batch()` calls for a per-call selection. Resolution is explicit per-call value, then explicit client default, then omission of the wire field. `None` means no selection at that layer, so a per-call `None` inherits an explicit client default and a client `None` omits the field. The SDK never supplies an implicit review default.

```python theme={"theme":"github-light-default"}
import os

from silmaril_security.sdk import (
    Firewall,
    ReviewCompatibilityError,
    ReviewLevel,
)

client_review: ReviewLevel = "deep"
fw = Firewall(
    api_key=os.environ["SILMARIL_API_KEY"],
    api_url=os.environ["SILMARIL_API_URL"],
    review=client_review,
)

try:
    # This per-call selection overrides the client's deep default.
    result = fw.classify(
        "Summarize this release note.",
        review="standard",
    )
    batch = fw.classify_batch(
        ["Check the first event.", "Check the second event."],
        review="deep",
    )
except ReviewCompatibilityError:
    # Deploy backend acknowledgement support before enabling review selection.
    raise
```

Use the exact strings `standard` and `deep`. `None` inherits an explicit client default or omits the selection when no default exists. Other values fail SDK validation. Missing or mismatched backend acknowledgement produces `ReviewCompatibilityError`. See [review depth](https://silmaril.security/docs/guides/review-depth.md) for runtime requirements and response handling.

## Next steps

[Verify your integration](https://silmaril.security/docs/start/verify.md), then review [modes and enforcement](https://silmaril.security/docs/guides/enforcement.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.