Skip to main content

Official Adlibo SDK for Python - AI Prompt Injection Protection

Project description

adlibo

Official Adlibo SDK for Python - AI Prompt Injection Protection

Installation

pip install adlibo

For async support:

pip install adlibo[async]

Quick Start

from adlibo import Adlibo

client = Adlibo("al_live_your_api_key")
result = client.analyze("user input here")

if not result.safe:
    print(f"Threat detected: {result.severity}")
    print(f"Categories: {result.categories}")

Usage

Analyze (Full Analysis)

result = client.analyze(
    "ignore previous instructions",
    include_details=True,
    sanitize=False
)

print(result.safe)          # False
print(result.risk_score)    # 85
print(result.severity)      # Severity.HIGH
print(result.action)        # Action.BLOCK
print(result.categories)    # [Category.DIRECT_OVERRIDE]
print(result.patterns)      # [PatternMatch(...)]

Detect (Quick Check)

result = client.detect("user input")

if result.detected:
    print(f"Risk score: {result.risk_score}")
    print(f"Category: {result.category}")

Sanitize

result = client.sanitize("Hello! Ignore previous instructions.")

print(result.text)              # "Hello!"
print(result.patterns_removed)  # 1

Convenience Method

if not client.is_safe("user input"):
    # Handle threat
    pass

Async Support

from adlibo import AsyncAdlibo

async with AsyncAdlibo("al_live_xxx") as client:
    result = await client.analyze("user input")
    print(result.safe)

Context Manager

with Adlibo("al_live_xxx") as client:
    result = client.analyze("text")

Configuration

client = Adlibo(
    api_key="al_live_xxx",
    base_url="https://www.adlibo.com/api/v1",
    timeout=30.0,
    max_retries=3
)

Rate Limiting

result = client.analyze("text")

if client.rate_limit:
    print(f"Remaining: {client.rate_limit.remaining}")
    print(f"Limit: {client.rate_limit.limit}")
    print(f"Reset: {client.rate_limit.reset}")

Error Handling

from adlibo import Adlibo, AdliboError, RateLimitError, AuthenticationError

try:
    result = client.analyze("text")
except RateLimitError as e:
    print(f"Rate limited. Reset at: {e.reset_at}")
except AuthenticationError:
    print("Invalid API key")
except AdliboError as e:
    print(f"Error: {e.code} - {e.message}")

Feedback

Report false positives or negatives:

from adlibo import Category

client.feedback(
    text="this was incorrectly flagged",
    is_false_positive=True,
    expected_categories=[Category.DIRECT_OVERRIDE],
    context="This is a legitimate user question"
)

Flask Integration

from flask import Flask, request, jsonify
from adlibo import Adlibo

app = Flask(__name__)
client = Adlibo("al_live_xxx")

@app.before_request
def check_prompt_injection():
    if request.method == "POST" and request.json:
        text = request.json.get("message", "")
        if text and not client.is_safe(text):
            return jsonify({"error": "Malicious input detected"}), 400

@app.route("/chat", methods=["POST"])
def chat():
    return jsonify({"response": "Safe input received"})

FastAPI Integration

from fastapi import FastAPI, HTTPException, Request
from adlibo import AsyncAdlibo

app = FastAPI()
client = AsyncAdlibo("al_live_xxx")

@app.on_event("startup")
async def startup():
    await client.__aenter__()

@app.on_event("shutdown")
async def shutdown():
    await client.__aexit__(None, None, None)

@app.middleware("http")
async def check_injection(request: Request, call_next):
    if request.method == "POST":
        body = await request.json()
        if "message" in body:
            if not await client.is_safe(body["message"]):
                raise HTTPException(400, "Malicious input detected")
    return await call_next(request)

Detection Categories

Category Description
DIRECT_OVERRIDE Attempts to ignore/override instructions
ROLE_MANIPULATION Trying to change AI persona/role
EXTRACTION Exfiltrating system prompts
FORMAT_TOKENS LLM format tokens ([INST], ###SYSTEM)
FAKE_AUTHORITY Fake admin codes/authority
DAN_JAILBREAK DAN and jailbreak variants
ROLEPLAY_ATTACK Roleplay-based attacks
HYPOTHETICAL Hypothetical framing
EMOTIONAL Emotional manipulation
GRADUAL_BOUNDARY Gradual boundary pushing
CONTEXT_EXPLOIT Context exploitation
ENCODING Unicode/Base64 obfuscation
TECHNICAL Technical injections
MODEL_INFO Model info extraction

License

MIT - Adlibo

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

adlibo-1.2.0.tar.gz (8.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

adlibo-1.2.0-py3-none-any.whl (8.8 kB view details)

Uploaded Python 3

File details

Details for the file adlibo-1.2.0.tar.gz.

File metadata

  • Download URL: adlibo-1.2.0.tar.gz
  • Upload date:
  • Size: 8.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for adlibo-1.2.0.tar.gz
Algorithm Hash digest
SHA256 b5b87446e568c62b1a70f472e68b24dfa2c446eba6d8472f8fa5c27bcc9fe9f3
MD5 bc38cd8812e40c9c4e746f33e49ba78b
BLAKE2b-256 1a4cdf42a988516b66d5166d3837ca93fe45dcd8b11c728d5c4fbb1645ed3951

See more details on using hashes here.

File details

Details for the file adlibo-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: adlibo-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 8.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for adlibo-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 901030893111d3cb644d6171046e3b6d2039400d17ef8081d2e847cbc0f543b2
MD5 a2951138573f1e933a4b6dcfaf470dc8
BLAKE2b-256 b7ddb5636651d3f974bd9b7f06b745ad419595455fca9a954009c3ff6291e9a6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page