Skip to main content

Official Python SDK for SafeNest - AI-powered child safety API

Project description

SafeNest

SafeNest Python SDK

Official Python SDK for the SafeNest API
AI-powered child safety analysis

PyPI version Python versions build status license

API DocsDashboardDiscord


Installation

pip install safenest

Requirements

  • Python 3.9+

Quick Start

import asyncio
from safenest import SafeNest

async def main():
    client = SafeNest(api_key="your-api-key")

    # Quick safety analysis
    result = await client.analyze("Message to check")

    if result.risk_level != RiskLevel.SAFE:
        print(f"Risk: {result.risk_level}")
        print(f"Summary: {result.summary}")

    await client.close()

asyncio.run(main())

Or use as a context manager:

async with SafeNest(api_key="your-api-key") as client:
    result = await client.analyze("Message to check")

API Reference

Initialization

from safenest import SafeNest

# Simple
client = SafeNest(api_key="your-api-key")

# With options
client = SafeNest(
    api_key="your-api-key",
    timeout=30.0,      # Request timeout in seconds
    max_retries=3,     # Retry attempts
    retry_delay=1.0,   # Initial retry delay in seconds
)

Bullying Detection

result = await client.detect_bullying("Nobody likes you, just leave")

if result.is_bullying:
    print(f"Severity: {result.severity}")       # Severity.MEDIUM
    print(f"Types: {result.bullying_type}")     # ["exclusion", "verbal_abuse"]
    print(f"Confidence: {result.confidence}")   # 0.92
    print(f"Rationale: {result.rationale}")

Grooming Detection

from safenest import DetectGroomingInput, GroomingMessage, MessageRole

result = await client.detect_grooming(
    DetectGroomingInput(
        messages=[
            GroomingMessage(role=MessageRole.ADULT, content="This is our secret"),
            GroomingMessage(role=MessageRole.CHILD, content="Ok I won't tell"),
        ],
        child_age=12,
    )
)

if result.grooming_risk == GroomingRisk.HIGH:
    print(f"Flags: {result.flags}")  # ["secrecy", "isolation"]

Unsafe Content Detection

result = await client.detect_unsafe("I don't want to be here anymore")

if result.unsafe:
    print(f"Categories: {result.categories}")  # ["self_harm", "crisis"]
    print(f"Severity: {result.severity}")      # Severity.CRITICAL

Quick Analysis

Runs bullying and unsafe detection in parallel:

result = await client.analyze("Message to check")

print(f"Risk Level: {result.risk_level}")   # RiskLevel.SAFE/LOW/MEDIUM/HIGH/CRITICAL
print(f"Risk Score: {result.risk_score}")   # 0.0 - 1.0
print(f"Summary: {result.summary}")
print(f"Action: {result.recommended_action}")

Emotion Analysis

result = await client.analyze_emotions("I'm so stressed about everything")

print(f"Emotions: {result.dominant_emotions}")  # ["anxiety", "sadness"]
print(f"Trend: {result.trend}")                 # EmotionTrend.WORSENING
print(f"Followup: {result.recommended_followup}")

Action Plan

from safenest import GetActionPlanInput, Audience, Severity

plan = await client.get_action_plan(
    GetActionPlanInput(
        situation="Someone is spreading rumors about me",
        child_age=12,
        audience=Audience.CHILD,
        severity=Severity.MEDIUM,
    )
)

print(f"Steps: {plan.steps}")
print(f"Tone: {plan.tone}")

Incident Report

from safenest import GenerateReportInput, ReportMessage

report = await client.generate_report(
    GenerateReportInput(
        messages=[
            ReportMessage(sender="user1", content="Threatening message"),
            ReportMessage(sender="child", content="Please stop"),
        ],
        child_age=14,
    )
)

print(f"Summary: {report.summary}")
print(f"Risk: {report.risk_level}")
print(f"Next Steps: {report.recommended_next_steps}")

Tracking Fields

All methods support external_id and metadata for correlating requests:

result = await client.detect_bullying(
    "Test message",
    external_id="msg_12345",
    metadata={"user_id": "usr_abc", "session": "sess_xyz"},
)

# Echoed back in response
print(result.external_id)  # "msg_12345"
print(result.metadata)     # {"user_id": "usr_abc", ...}

Usage Tracking

result = await client.detect_bullying("test")

# Access usage stats after any request
if client.usage:
    print(f"Limit: {client.usage.limit}")
    print(f"Used: {client.usage.used}")
    print(f"Remaining: {client.usage.remaining}")

# Request metadata
print(f"Request ID: {client.last_request_id}")

Error Handling

from safenest import (
    SafeNest,
    SafeNestError,
    AuthenticationError,
    RateLimitError,
    ValidationError,
    NotFoundError,
    ServerError,
    TimeoutError,
    NetworkError,
)

try:
    result = await client.detect_bullying("test")
except AuthenticationError as e:
    print(f"Auth error: {e.message}")
except RateLimitError as e:
    print(f"Rate limited: {e.message}")
except ValidationError as e:
    print(f"Invalid input: {e.message}, details: {e.details}")
except ServerError as e:
    print(f"Server error {e.status_code}: {e.message}")
except TimeoutError as e:
    print(f"Timeout: {e.message}")
except NetworkError as e:
    print(f"Network error: {e.message}")
except SafeNestError as e:
    print(f"Error: {e.message}")

Type Hints

The SDK is fully typed. All models are dataclasses with type hints:

from safenest import (
    # Enums
    Severity,
    GroomingRisk,
    RiskLevel,
    EmotionTrend,
    Audience,
    MessageRole,
    # Input types
    AnalysisContext,
    DetectBullyingInput,
    DetectGroomingInput,
    DetectUnsafeInput,
    AnalyzeInput,
    AnalyzeEmotionsInput,
    GetActionPlanInput,
    GenerateReportInput,
    # Message types
    GroomingMessage,
    EmotionMessage,
    ReportMessage,
    # Result types
    BullyingResult,
    GroomingResult,
    UnsafeResult,
    AnalyzeResult,
    EmotionsResult,
    ActionPlanResult,
    ReportResult,
    Usage,
)

FastAPI Example

from fastapi import FastAPI, HTTPException
from safenest import SafeNest, RateLimitError

app = FastAPI()
client = SafeNest(api_key="your-api-key")

@app.post("/check-message")
async def check_message(message: str):
    try:
        result = await client.analyze(message)

        if result.risk_level.value in ["high", "critical"]:
            raise HTTPException(
                status_code=400,
                detail={"error": "Message blocked", "reason": result.summary}
            )

        return {"safe": True, "risk_level": result.risk_level.value}

    except RateLimitError:
        raise HTTPException(status_code=429, detail="Too many requests")

Support


License

MIT License - see LICENSE for details.


Built with care for child safety by the SafeNest team

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

safenest-1.0.1.tar.gz (785.8 kB view details)

Uploaded Source

Built Distribution

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

safenest-1.0.1-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

Details for the file safenest-1.0.1.tar.gz.

File metadata

  • Download URL: safenest-1.0.1.tar.gz
  • Upload date:
  • Size: 785.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for safenest-1.0.1.tar.gz
Algorithm Hash digest
SHA256 82c9a96c0b7cbaf1007b13c9639574e811a387bd402dfcf9877f0fcbb4c3d7ef
MD5 f32ea85c7c3fa357c1244a54d4498e2a
BLAKE2b-256 18e4cb7e41b5a5bae1d5ba9cb41b0ba9807d3f86ed8f5099e24a3813b122a6fb

See more details on using hashes here.

File details

Details for the file safenest-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: safenest-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 11.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for safenest-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5556c7a00340be12a19557d0cfc508c8fcbbfbe272113e31c922eb7dae581d75
MD5 f6c10e7aa4cc99d0f63d50b7d7572bb5
BLAKE2b-256 2a7b202c6a55729cc843d1488c8b398391a05b17d4ff9007205e590a255878e9

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