Superagent LogoSuperagent
SDKs

Python SDK

Async Python client for implementing Superagent into your apps

Python client for calling the Superagent Guard and Redact endpoints.

Installation

Terminal
uv add superagent-ai

Tip: uv add pins the dependency in your project; run examples with uv run if you aren't using a dedicated virtual environment.

Quick start

main.py
import asyncio
from superagent_ai import create_client

async def main() -> None:
    client = create_client(
        api_base_url="https://app.superagent.sh/api",  # Optional, this is the default
        api_key="sk-...",
    )

    # Guard: Analyze commands for security threats
    guard_result = await client.guard(
        "Write a hello world script",
        on_block=lambda reason: print("Guard blocked:", reason),
        on_pass=lambda: print("Guard approved!"),
    )

    if guard_result.rejected:
        print("Rejected:", guard_result.reasoning)
    else:
        print("Approved:", guard_result.decision)

    # Redact: Remove sensitive data from text
    redact_result = await client.redact(
        "My email is john@example.com and SSN is 123-45-6789"
    )

    print(redact_result.redacted)
    # Output: "My email is <REDACTED_EMAIL> and SSN is <REDACTED_SSN>"

    # Verify: Check claims against source materials
    verify_result = await client.verify(
        "The company was founded in 2020 and has 500 employees",
        [
            {
                "name": "About Us",
                "content": "Founded in 2020, our company has grown rapidly...",
                "url": "https://example.com/about"
            },
            {
                "name": "Team Page",
                "content": "We currently have over 450 team members...",
                "url": "https://example.com/team"
            }
        ]
    )

    print(verify_result.claims)
    # Output: Array of claim verifications with verdicts, evidence, and reasoning

    await client.aclose()

asyncio.run(main())

Using as a context manager

context_manager.py
import asyncio
from superagent_ai import create_client

async def main() -> None:
    async with create_client(api_key="sk-...") as client:
        result = await client.guard("command")
        redacted = await client.redact("text")

asyncio.run(main())

API Reference

create_client(**kwargs)

Creates a new Superagent client.

Parameters:

  • api_key (required) – API key provisioned in Superagent
  • api_base_url (optional) – Base URL for the API (defaults to https://app.superagent.sh/api)
  • client (optional) – Custom httpx.AsyncClient instance
  • timeout (optional) – Request timeout in seconds (defaults to 10.0)

Returns: Client

client.guard(input, *, on_block=None, on_pass=None)

Analyzes text or a PDF file for security threats.

Parameters:

Prop

Type

Returns: GuardResult

Prop

Type

GuardDecision:

Prop

Type

client.redact(input, *, url_whitelist=None, entities=None, format=None)

Redacts sensitive data from text or PDF files.

Parameters:

Prop

Type

Returns: RedactResult

Prop

Type

client.verify(text, sources)

Verifies claims in text against provided source materials.

Parameters:

Prop

Type

Source (dict):

Prop

Type

Returns: VerifyResult

Prop

Type

ClaimVerification (dict):

Prop

Type

Claim Verification

You can verify claims in text against provided source materials:

verify_example.py
import asyncio
from superagent_ai import create_client

async def main() -> None:
    async with create_client(api_key="sk-...") as client:
        result = await client.verify(
            "The company was founded in 2020 and has 500 employees.",
            [
                {
                    "name": "About Us",
                    "content": "Founded in 2020, our company has grown rapidly...",
                    "url": "https://example.com/about"
                },
                {
                    "name": "Team Page",
                    "content": "We currently have over 450 team members...",
                    "url": "https://example.com/team"
                }
            ]
        )

        # Iterate through claims to check verdicts
        for claim in result.claims:
            print(f"Claim: {claim['claim']}")
            print(f"Verdict: {'✓ True' if claim['verdict'] else '✗ False'}")
            print(f"Evidence: {claim['evidence']}")
            print(f"Reasoning: {claim['reasoning']}")
            print(f"Sources: {', '.join(s['name'] for s in claim['sources'])}")
            print('---')

asyncio.run(main())

How it works:

  • The text parameter contains the claims you want to verify
  • The sources list provides the reference materials against which claims are verified
  • The AI analyzes each claim and determines if it's supported, contradicted, or unverifiable
  • Returns detailed results with verdicts, evidence quotes, reasoning, and source references
  • Only uses information explicitly stated in the provided sources

Use cases:

  • Fact-checking articles or content against authoritative sources
  • Verifying marketing claims against product documentation
  • Validating information in reports against source data
  • Checking consistency between different documents
  • Automated compliance verification

Detected PII/PHI Types

The redaction feature detects and replaces:

  • Email addresses<REDACTED_EMAIL>
  • Social Security Numbers<REDACTED_SSN>
  • Credit cards (Visa, Mastercard, Amex) → <REDACTED_CC>
  • Phone numbers (US format) → <REDACTED_PHONE>
  • IP addresses (IPv4/IPv6) → <REDACTED_IP>
  • API keys & tokens<REDACTED_API_KEY>
  • AWS access keys<REDACTED_AWS_KEY>
  • Bearer tokensBearer <REDACTED_TOKEN>
  • MAC addresses<REDACTED_MAC>
  • Medical record numbers<REDACTED_MRN>
  • Passport numbers<REDACTED_PASSPORT>
  • IBAN<REDACTED_IBAN>
  • ZIP codes<REDACTED_ZIP>

Custom Entity Redaction

You can specify custom entities to redact using natural language descriptions by passing an entities parameter to the redact() method:

custom_entities_example.py
client = create_client(api_key="sk-...")

result = await client.redact(
    "My credit card is 4532-1234-5678-9010 and my email is john@example.com",
    entities=["credit card numbers", "email addresses"]
)
# The model will redact the specified entity types based on your natural language descriptions

How it works:

  • The entities list is sent to the redaction API in the request body
  • You can describe entities in natural language (e.g., "credit card numbers", "social security numbers", "phone numbers")
  • The AI model interprets your descriptions and redacts matching content
  • This allows for flexible, context-aware redaction beyond predefined patterns

Examples of entity descriptions:

  • ["credit card numbers", "social security numbers"]
  • ["email addresses", "phone numbers", "IP addresses"]
  • ["API keys", "passwords", "authentication tokens"]
  • ["medical record numbers", "patient names"]
  • ["company names", "project codenames"]

URL Whitelisting

You can specify URLs that should not be redacted by passing a url_whitelist parameter to the redact() method:

url_whitelist_example.py
client = create_client(api_key="sk-...")

result = await client.redact(
    "Check out https://github.com/user/repo and https://secret.com/data",
    url_whitelist=["https://github.com", "https://example.com"]
)
# Output: "Check out https://github.com/user/repo and <URL_REDACTED>"

The whitelist is applied locally after redaction, meaning:

  1. The text is sent to the redact API (URLs are not yet redacted by the API)
  2. The response is processed locally
  3. URLs not matching the whitelist prefixes are replaced with <URL_REDACTED>
  4. URLs matching the whitelist prefixes are preserved as-is
  5. The final result is returned

How it works:

  • Whitelisted URLs (those starting with any prefix in url_whitelist) remain unchanged
  • Non-whitelisted URLs are replaced with <URL_REDACTED>
  • The matching is done using prefix comparison (e.g., "https://github.com" matches "https://github.com/user/repo")

PDF File Redaction

You can redact sensitive information from PDF files. The API supports two output formats:

Option 1: Get Redacted PDF File (format="pdf")

Returns PDF bytes with redactions applied:

pdf_file_output.py
import asyncio
from superagent_ai import create_client

async def main() -> None:
    async with create_client(api_key="sk-...") as client:
        # Get redacted PDF file
        with open("sensitive-document.pdf", "rb") as pdf_file:
            result = await client.redact(
                pdf_file,  # Pass file as first parameter
                format="pdf",  # Returns PDF bytes
                entities=["SSN", "credit card numbers", "email addresses"]
            )

        # Save the redacted PDF
        if result.pdf:
            with open("redacted-output.pdf", "wb") as output_file:
                output_file.write(result.pdf)
            print("Redacted PDF saved to redacted-output.pdf")

asyncio.run(main())

Option 2: Get Redacted Text (format="json", default)

Returns JSON with the redacted text extracted from the PDF:

pdf_text_output.py
import asyncio
from superagent_ai import create_client

async def main() -> None:
    async with create_client(api_key="sk-...") as client:
        # Get redacted text from PDF
        with open("sensitive-document.pdf", "rb") as pdf_file:
            result = await client.redact(
                pdf_file,  # Pass file as first parameter
                format="json",  # Returns JSON with redacted text (default)
                entities=["SSN", "credit card numbers", "email addresses"]
            )

            print(result.redacted)  # Redacted text extracted from the PDF
            print(result.reasoning) # Explanation of what was redacted

asyncio.run(main())

How it works:

  • Pass the file object directly as the first parameter
  • The SDK automatically uses multipart/form-data encoding for file inputs
  • format="pdf" returns a redacted PDF file as bytes
  • format="json" (default) extracts text from the PDF, redacts it, and returns as JSON
  • You can combine file redaction with entities to specify custom entity types

Use cases:

  • Redact sensitive data from contracts, invoices, or legal documents
  • Process medical records while maintaining HIPAA compliance
  • Sanitize financial documents before sharing
  • Prepare documents for public release by removing confidential information

Note: The file should be opened in binary mode ("rb"). The SDK handles the proper encoding and content-type headers automatically.

PDF File Guard Analysis

You can analyze PDF files for security threats using the Guard method. The API analyzes the PDF content and returns a JSON response with the security assessment:

Analyze PDF Files

Analyzes a PDF file and returns JSON with security assessment:

pdf_guard.py
import asyncio
from superagent_ai import create_client

async def main() -> None:
    async with create_client(api_key="sk-...") as client:
        # Analyze PDF file for security threats
        with open("document.pdf", "rb") as pdf_file:
            result = await client.guard(
                pdf_file,  # Pass file as first parameter
                on_block=lambda reason: print("Guard blocked:", reason),
                on_pass=lambda: print("Guard approved!"),
            )

        # Check the analysis result
        if result.rejected:
            print(f"Document contains security threats: {result.reasoning}")
            if result.decision:
                print(f"Violation types: {result.decision.get('violation_types', [])}")
                print(f"CWE codes: {result.decision.get('cwe_codes', [])}")
        else:
            print(f"Document is safe: {result.reasoning}")

asyncio.run(main())

How it works:

  • Pass the file object directly as the first parameter
  • The SDK automatically uses multipart/form-data encoding for file inputs
  • The guard extracts text from the PDF and analyzes it for security threats
  • Returns JSON with rejected, reasoning, decision, and usage fields
  • You can use the on_block and on_pass callbacks to handle the analysis results

Use cases:

  • Analyze uploaded documents for malicious content before processing
  • Validate PDF attachments for security threats
  • Screen documents for prompt injection attempts
  • Ensure document safety before feeding to AI models

Note: The file should be opened in binary mode ("rb"). The SDK handles the proper encoding and content-type headers automatically.

Error Handling

error_handling.py
from superagent_ai import GuardError

try:
    result = await client.guard("command")
except GuardError as error:
    print(f"Guard error: {error}")