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.0.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.0.0-py3-none-any.whl (8.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: adlibo-1.0.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.0.0.tar.gz
Algorithm Hash digest
SHA256 edf01cea7bfe5d7837199413d6ce7ef0635aa65d996afc31fc0f69e0676ba865
MD5 0fc65308d315d53b641d8d028987afd7
BLAKE2b-256 e14652eae20bd23712ba07bdce109320fea8cf8efeedb62a01336c33dfd911fd

See more details on using hashes here.

File details

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

File metadata

  • Download URL: adlibo-1.0.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.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 eb34efd431550a36a025fe82e07c5b1486ce265e2cc3c993804b2937d912d2c4
MD5 9fe280ceb2ecaaf68246a55fb4fcf40a
BLAKE2b-256 d9980b1f70cdd68bdb58961932b3576fe344992ef67c8b1e9eb9a4883d2f392b

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