Skip to main content

Enkrypt AI Python SDK

A Python SDK with Guardrails, Code of Conduct Policies, Endpoints (Models), Deployments, AI Proxy, Datasets, Red Team, etc. functionality for API interactions. See https://pypi.org/project/enkryptai-sdk Also see the API documentation at https://docs.enkryptai.com

Table of Contents

Installation

Environment Variables

Set the following environment variables:
  • OPENAI_API_KEY: Your OpenAI API key
  • ENKRYPTAI_API_KEY: Your EnkryptAI API key
  • ENKRYPTAI_BASE_URL: The base URL for the EnkryptAI API

Helper functions for all response classes

to_dict

We can use the to_dict method to convert the response objects to dictionaries.
Python

Setup

Python
The Red Team classes were renamed. RedTeamClient is now the run-based /rt client, and the task-based one it used to name is RedTeamLegacyClient. Every request/response DTO lost its v2 infix at the same time — RTv2ModelConfig is now RTModelConfig, and so on for the whole family. Importing the old names raises ImportError; calling a task-based method on RedTeamClient raises an AttributeError that names the replacement.

Sample Variables

Python

Sample Configurations

Sample Guardrails Detector Config

Python

Sample Model Config

Python

Sample Deployment Config

Python

Sample Dataset Config

Python

Sample Redteam Model Health Config (Legacy V3)

Python

Sample Redteam Target Config (Legacy V3)

Python

Sample Redteam Model Config (Legacy V3)

Python

Sample Redteam Risk Mitigation Guardrails Policy Config

Python

Sample Redteam Risk Mitigation System Prompt Config

Python

Health Checks

Guardrails Health

Python

Guardrails Status

Python

Guardrails Models Loaded

Python

Red Team Health

Python

Red Team Model Health

Verifies Enkrypt AI can reach and call your target, as opposed to the liveness of the Red Team service itself.
Python
The archived RedTeamLegacyClient equivalents — redteam_legacy_client.get_health() and redteam_legacy_client.check_model_health_v3(...) — remain available for existing integrations. See the Redteam (Archived) section below.

Guardrails Quickstart

Python

Guardrails Response Objects

The SDK provides wrapper classes for API responses that provides additional functionality.

GuardrailsDetectResponse

The GuardrailsDetectResponse class wraps detect and policy_detect responses:
Python

GuardrailsBatchDetectResponse

The GuardrailsBatchDetectResponse class wraps batch_detect response:
Python

Available Guardrails Detectors

  • injection_attack: Detect prompt injection attempts
  • bias: Detect biased content
  • policy_violation: Check against custom policy rules
  • topic_detection: Detect specific topics
  • nsfw: Filter inappropriate content
  • toxicity: Detect toxic language
  • pii: Detect personal information
  • copyright_ip: Check for copyright/IP violations (Coming soon)
  • system_prompt: Detect system prompt leaks (Coming soon)
  • keyword_detector: Check for specific keywords
  • sponge_attack: Detect infinite loops
Each detector can be enabled/disabled and configured with specific options as documented in the API docs.

Guardrails Configs

Instead of using a dictionary to configure detectors directly, you can also use GuardrailsConfig to create configurations for each detector.

Injection Attack

Python

Policy Violation

Python
We can also pass structured rules generated by the Policy Wizard instead of (or alongside) policy_text. Each rule can be a plain dict or a GenerateRulesRule instance:
Python

Toxicity

Python

NSFW

Python

Bias

Python

PII

Python

Topic Detection

Python

Keyword Detector

Python
  • (Coming soon)
Python

System Prompt

  • (Coming soon)
Python

Sponge Attack

Python

Detect with config

Python

Batch Detect

Batch detect threats in multiple texts.

Guardrail Management

Guardrails allow you to save and reuse detection configurations with separate input (prompt) and output (response) detector settings.

Create a Guardrail

Python

Get a Guardrail

Python

Modify a Guardrail

Python

Delete a Guardrail

Python

List Guardrails

Python

Detect Using a Guardrail

Use mode="prompt" for input detectors or mode="response" for output detectors.
Python

Batch Detect Using a Guardrail

Python

Detect Image Using a Guardrail

Use mode="prompt" for input detectors or mode="response" for output detectors.
Python

Detect Audio Using a Guardrail

Use mode="prompt" for input detectors or mode="response" for output detectors.
Python

Guardrails Policy Management (Legacy)

Legacy: The Policy Management API is legacy. Use the Guardrail Management section above for new integrations, which supports separate input/output detector configurations.
Policies allow you to save and reuse guardrails configurations.

Create a Policy

Python

Modify a Policy

Python

Get Policy Details

Python

List Policies

Python

Delete a Policy

Python

Use a Policy to Detect

Python

Batch Policy Detect

Batch detect threats in multiple texts using a specific policy.

Scan a URL with a Policy

Scan a URL using a specific saved policy.

Scan a PDF with a Policy

Scan a PDF file using a specific saved policy.

Detect Image with a Policy

Detect unsafe content in an image using a specific saved policy.

Detect Audio with a Policy

Detect unsafe content in audio using a specific saved policy.

Guardrails Evals

The Guardrails Client also provides functionality to evaluate LLM responses for scanning URLs, adherence to context, relevancy to questions and deetecting hallucinations.

Scan a URL for Threats

Scan a URL for security threats such as injection attacks and policy violations.

Scan a PDF for Threats

Scan a PDF file for security threats such as injection attacks and policy violations.

Check Context Adherence

Evaluate if an LLM’s response adheres to the provided context:
Python

Check Question Relevancy

Evaluate if an LLM’s response is relevant to the asked question:
Python

Check Hallucination

  • (Coming soon)
Detect hallucinations in an LLM’s response:
Python

Guardrails PII anonymization and de-anonymization

The Guardrails Client also provides functionality to redact and unredact PII in text.
Python

Policy Wizard (v2)

The Policy Wizard is a two-step, structured alternative to the legacy free-text/atomizer flow above. First, infer_document reads a policy document (or pasted text) and infers a short questionnaire (the profile) describing its purpose, prohibited actions, user types, data access, actions, and decision impact. Then generate_rules turns that questionnaire into a structured, machine-checkable set of rules (with risk categories, severities, and framework mappings) that can be used with GuardrailsConfig.policy_violation(rules=...) (see Policy Violation above) or stored on a v2 Code of Conduct policy (see Code of Conduct Policies below).

Infer a Policy Document

Python

Generate Structured Rules

Python

Code of Conduct Policies

Code of Conduct policies help enforce organizational guidelines and standards.

Atomize a Policy Document or Text

Python

Add a Code of Conduct Policy

Python

Add a Code of Conduct Policy (v2 - Policy Wizard)

Instead of the legacy policy_rules/policy_text arguments above, a Code of Conduct policy can also be created from a Policy Wizard questionnaire + generated rules config (see Policy Wizard (v2)). v2_questionnaire and v2_config must be provided together, and are mutually exclusive with the legacy policy_rules/total_rules/policy_text arguments. policy_file may still be attached alongside them for archival storage.
Python

Get Code of Conduct Policy Details

Python

List Code of Conduct Policies

Python

Modify a Code of Conduct Policy

Python

Delete a Code of Conduct Policy

Python

Endpoints (Models)

Add a Model

Python

Saved Model Health

Python

Get Model Details

Python

List Models

Python

Modify a Model

Python

Delete a Model

Python

Deployments

Add a Deployment

Python

Get Deployment Details

Python

List Deployments

Python

Modify a Deployment

Python

Delete a Deployment

Python

AI Proxy with Deployments

We can proxy to the AI model configured in the deployment using the OpenAI SDK.
Python

Datasets

Datasets are used for red teaming evaluations. Instead of using “standard” dataset, you can create custom datasets and use them in red teaming evaluations.

Add a Dataset

Python

Get Dataset Details

Python

List Datasets

Python

Get Dataset Task Status

Python

Get Datacard

Python

Get Dataset Summary

Python

Redteam (Archived)

Redteam evaluations are used to test models for security vulnerabilities.
This is the original task-based Red Team API, kept working for existing integrations — its endpoints are grouped under Archived in the API reference. New work should use the run-based Red Team API below.

Add a Redteam Custom Task with Endpoint Config (V3)

Python

Add a Redteam Custom Task with a saved model (V3)

Python

Get Redteam Task Status

Python

Get Redteam Task

Python

List Redteam Tasks

Python
Python

Get Redteam Task Results Summary

Python

Get Redteam Task Results Summary of Test Type

Python

Get Redteam Task Results Details

Python

Get Redteam Task Results Details of Test Type

Python

Get Redteam Findings

Python

Mitigate Risks with Guardrails Policy

Python

Mitigate Risks with System Prompt

Python

Red Team

The Red Team API (RedTeamClient in the SDK) is the current, run-based API and the successor to the task-based API above, which is now archived as RedTeamLegacyClient. Instead of add_custom_task_v3/status/get_task-style task management, every submission endpoint (run_redteam, run_threat_modeling*, run_playground, submit_eval) returns a run_id, and a single, shared set of run endpoints (get_run_status, get_run_records, get_run_results, get_compliance_report, send_signal, resume_run, stream_run_events, stream_logs) is used to poll, drive signals into, follow, and fetch results for that run, regardless of which endpoint created it.
RedTeamClient covers the whole run-based surface: the submission and run endpoints below, plus model health, findings, risk mitigation, service health, and the saved-model (/rt/model/...) variants.

Submitting runs

Submit a Redteam Run

Python
Using a saved Code of Conduct policy. Rather than writing the rules out yourself, send the policy’s name in the X-Enkrypt-Policy header. The gateway resolves it into context for you and labels the run with that name in the dashboard. Both policy formats are handled, and they land on different fields: a v2 (Policy Wizard) policy arrives as context.policy_rules, its enabled rules passed through whole in stored order, one object per rule; a v1 (Policy Atomizer) policy arrives as the free-text context.policy_description.The two are mutually exclusive - whichever the gateway writes, it clears the other. Naming a policy overrides whatever you set in either field yourself, so a run is never labelled with one policy but generated from another’s rules. Omit the header if you want your own wording to stand.The header is the only way to do this - there is no policy_name body field. The request models are extra: forbid, so sending one rejects the whole request with a 422.

Submit a Threat Modeling Run

Python

Discover Threat Modeling Categories

Use this to discover which risk categories apply to a system, before running full threat modeling or a redteam against it.
Python

Submit Threat Modeling with Data Generation

Same as threat modeling above, but also generates an attack/eval dataset for the discovered risks, using the shared RTGenerationConfig/RTSeedPrompt machinery.
Python

Submit a Playground Run

The playground runs a single, goal-directed attack (or set of attack methods) against a target interactively - useful for ad hoc probing of a specific target/tool-calling agent, rather than a full redteam sweep.
Python

Submit an Eval

Evaluate a set of pre-collected query/response pairs (e.g. from your own logs or an offline red team) against Enkrypt’s judges, instead of having Enkrypt generate and send the prompts itself.
Python

Polling and managing runs

The endpoints below manage an asynchronous run using the run_id returned by the queued submit endpoints (run_redteam and submit_eval). Threat modeling and playground return their results synchronously, so they don’t need polling.
Use run_id, not the *_url fields. A queued submission comes back with status_url, results_url and websocket_url, and the results payload carries a records_url. All four are emitted with the Red Team service’s internal /v1/... spelling rather than the /rt/... prefix the API is published under, so following them verbatim returns a 400. The client methods below take run_id and build the right address for you — /v1/runs/{run_id}/records is a 400, /rt/runs/{run_id}/records is the same resource and returns 200.

Get Run Status

Python

Get Run Records

Python

Get Run Results

Python

Get Compliance Report

Python

Send a Signal to a Run

Python

Resume a Run

Python

Stream Run Events

Python

Stream Run Logs

The engine’s own log lines over a WebSocket, as the run produces them — the same log the dashboard’s run view shows. This is a different stream from stream_run_events above: that one is structured progress (Server-Sent Events), this one is log text.
Python
Python (asyncio)
Lines already produced are replayed before the stream tails, so connecting part-way through still gives you the run from the beginning.
Python
logs_url() returns a URL with your API key embedded as a query parameter — the key cannot ride in a header because a WebSocket handshake carries none. Treat the result as a secret: do not print it, log it, or paste it into a bug report.
A 403 on the handshake almost always means ownership, not a bad key: a run started by another account cannot be streamed with your key, and a run started with an organization key is owned by the organization. Connections are also rate limited per IP and shared with the dashboard, so open one socket per run rather than one per attempt.

Datasets

Get a Dataset

Python

Saved models

The /rt/model/... variants take the target from a model you already saved (see the Models section above) instead of inlining it, so their request DTOs have no target field at all.
The Red Team target has no home for custom cURL commands, custom headers or payloads, JWT auth, provider-specific auth data or metadata, or outbound proxying. A saved model that relies on any of those is rejected with a 400 naming the model — use the inline target form for those. This applies to check_saved_model_health too: it takes the same projected target as the other /rt/model/... endpoints.Relay routing is the one exception to the metadata rule. A model saved with model_config.connect_via_relay and a model_config.metadata.relay block is projected onto target.connect_via_relay and target.metadata.relay — the same spelling — and runs through your bridge — see Relay bridge below. A saved model carrying metadata.relay alongside other provider metadata is still rejected, and so is one that sets only half of the pair.

Submit a Redteam Run with a Saved Model

Python

Submit a Playground Run with a Saved Model

Python

Model health

Check Model Health

Python

Check Saved Model Health

Python
Neither health endpoint works for a relay target. Both dial the target’s endpoint directly, and on a relay target that field is only a placeholder for an address inside your own network — so the probe reports unhealthy however healthy the bridge is. Check reachability with the bridge status endpoint under Relay bridge instead. Submitting a relay run is unaffected: the gateway knows not to health-probe a relay target on the way in.

Relay bridge

Red-team a model that has no inbound network exposure. You run a small bridge process inside your own network; it holds one long-lived outbound WSS connection to Enkrypt on port 443. Enkrypt pushes OpenAI-shaped chat.completions requests down that socket, the bridge calls your intranet LLM over your own network, and the response returns the same way. Your firewall only ever sees one outbound HTTPS connection, and the target’s address never has to resolve from outside.
Spelling rollout. target.metadata.relay is being rolled out. If a run returns 422 naming target.metadata.relay, your environment is on the previous release — send the relay block as target.relay, which stays supported. Set RELAY_SERVER_BASE_URL for the environment you were given.
Routing a run through the bridge is a property of the target, not a separate endpoint — run_redteam and run_playground are called exactly as above. RTModelConfig.via_relay() is the intended constructor: it fills in the parts of the relay shape that never vary, so the three values you actually own are the three you pass.
Python
via_relay() emits the relay block at target.metadata.relay and sets connect_via_relay: True for you. connect_via_relay, metadata and relay are all declared fields on RTModelConfig, so building the target by hand needs no _extra_fields:
Python
Either target is submitted the same way:
Python
target.metadata.relay is the canonical spelling, and the same one a saved model stores as model_config.metadata.relay. The bare target.relay is the older form and is still accepted, so existing code keeps working; sending both is fine only when they carry the same block, and if they disagree the request is a 422 naming the conflict. The request models are extra: forbid, so connect_via_relay without a relay block is a 422 whose msg reads Value error, target.metadata.relay is required when connect_via_relay is true, and an unrecognised key inside relay is a 422 too. In particular there is no relay endpoint, relay token, timeout or offline-grace setting to configure: the relay address is fixed infrastructure and the timeouts are server-side. Every literal string, and the 400s the gateway raises for a misconfigured saved model, are tabulated under Exact 422 strings for an inline target.
target.metadata is not a free-form metadata bag. relay is the only key it accepts; any other — metadata.tenant_id, metadata.aws_region, provider-specific metadata in general — is a 422. The Red Team target cannot express provider metadata, and accepting it silently would mean the run attacks a differently-configured target and reports success on it. Use the Archived Red Team API for a target that needs provider metadata.

Connect a Relay Bridge

pip install enkryptai-sdk also installs an enkryptai-relay console script — the bridge itself. Run it on any machine inside your network that can reach the LLM. It is configured entirely by environment variables:
  • RELAY_BRIDGE_ID (required): the id this bridge registers under, and the value your runs name in target.metadata.relay.bridge_id. Free text you choose; it is scoped to your account, so it only has to be unique within it.
  • ENKRYPT_API_KEY (required): your Enkrypt API key. This is also how the cloud knows whose bridge this is.
  • TARGET_BASE_URL: base URL of your local LLM, used to resolve a path-only target.
  • BRIDGE_HOOKS_MODULE: dotted path to a translation-hooks module. The default is an identity passthrough, which is all you need when the local LLM already speaks OpenAI (vLLM, Ollama, LM Studio, Azure OpenAI, LiteLLM, …). For anything else, export before_request and after_response coroutines from your own module and point this at it — translation lives at the bridge, so customer-specific request shapes never reach the cloud.
  • RELAY_SERVER_BASE_URL: the WSS URL to dial. See the availability note above.
There is no user id to configure. You supply only an API key; Enkrypt resolves the owning account from it and stamps that identity on both the bridge socket and the runs you submit, which is how a run finds your bridge. Two customers can therefore both name a bridge customer-bridge-1 without colliding. (ENKRYPT_USER_ID exists only for local testing against a relay with no gateway in front of it, where there is no API key to resolve.) To embed the bridge in a supervisor or a Kubernetes sidecar instead of running the script:
Python

Check Relay Bridge Status

Whether a bridge is currently connected. This is the reachability check for a relay target, in place of the model-health endpoints. RedTeamClient has no method for it yet, so call it directly:
Python
The answer is scoped to your own account. A bridge someone else registered under the same name reports as not connected rather than leaking that it exists, so connected: False covers “not running”, “never existed” and “not yours” alike.

Findings and risk mitigation

These read a finished run’s summary rather than creating a run — pass the dict from get_run_results() straight through.

Get Findings

Python

Mitigate Risks with a System Prompt

Python

Mitigate Risks with a Guardrails Policy

Python

Service health

Health Check

Python

Status Check

Python
© 2025 Enkrypt AI. All rights reserved. Enkrypt AI software is provided under a proprietary license. Unauthorized use, reproduction, or distribution of this software or any portion of it is strictly prohibited. Terms of Use: https://www.enkryptai.com/terms-and-conditions Enkrypt AI and the Enkrypt AI logo are trademarks of Enkrypt AI, Inc.