marsguard 0.3.2
Modular Python SDK for generating guardrails via the MARSGuard backend API.
Requires Python: >=3.9
Keywords: guardrail, sdk, llm, safety, policy, prompt

# MARSGuard Python SDK

A modular Python SDK for generating guardrails via the MARSGuard backend API. This SDK enforces request/response schemas using Pydantic and provides robust error handling with custom exceptions.

## Features

- Enforced request/response schema (Pydantic models)
- Modular, easy-to-use client interface
- Structured error handling with custom exceptions
- Minimal dependencies

## Installation

```bash
pip install marsguard
```

## SDK Structure

- **marsguard.sdk.MarsGuardClient**: Main client for interacting with the backend API.
- **marsguard.schemas.AppModel**: Model for application details.
- **marsguard.schemas.ModelSpec**: Model for LLM provider and model name.
- **marsguard.schemas.AudienceSpec**: Model for audience specification.
- **marsguard.schemas.ContentRulesSpec**: Model for content rules.
- **marsguard.schemas.CustomSpec**: Model for custom organizational policy or rules.
- **marsguard.schemas.ProjectSpec**: Model for project specification.
- **marsguard.schemas.GenerateGuardrailsRequest**: Request schema for generating guardrails.
- **marsguard.schemas.DualGuardrailsResponse**: Response schema for generated guardrails, containing both summarized and expanded versions.
- **marsguard.exceptions**: Structured exception hierarchy for robust error handling.

## Usage Example

Below is the recommended way to use the SDK, including a comprehensive `ProjectSpec` template with dummy values and comments. Replace all dummy values with your actual project details.

**Note:**  
The response object (`DualGuardrailsResponse`) contains two fields:
- `guardrails`: The main, summarized/sanitized guardrails.
- `expanded_guardrails`: A longer, more descriptive version of the guardrails (more comprehensive, but consumes more tokens). Use `expanded_guardrails` if you want a more detailed output, but be aware of higher token usage.

```python
import logging
from marsguard import (
    MarsGuardClient,
    AppModel,
    ModelSpec,
    AudienceSpec,
    ContentRulesSpec,
    CustomSpec,
    ProjectSpec,
    GenerateGuardrailsRequest,
)


# Construct a client object to generate the guardrail
client = MarsGuardClient()

# Recommended way to write ProjectSpec using schema
project_spec = ProjectSpec(
    relaxation_factor=0.5,  # 0.0 = strict, 1.0 = relaxed
    audience=AudienceSpec(
        age_factor=30,  # Target audience age (e.g., 18, 25, 50)
        risk_factor=5.0,  # 0..10; higher means stricter safety
        trust="low"  # Audience trust: "low", "medium", or "high"
    ),
    content_rules=ContentRulesSpec(
        max_output_tokens=400,  # Maximum tokens per response
        tone="neutral"  # Response tone, e.g., "neutral", "formal", "friendly"
    ),
    custom=CustomSpec(
        text="Any custom organizational policy or rules here."  # Custom rules
    )
)

# Construct the request object using this particular schema 
req = GenerateGuardrailsRequest(
    app=AppModel(
        name="Your App Name",  # Name of your application
        context="Short business context or description of your app"  # Business context
    ),
    domain="your_domain",  # Domain, e.g., "insurance", "healthcare", "finance"
    model=ModelSpec(
        provider="your_provider",  # LLM provider, e.g., "openai"
        name="your_model_name"     # Model name, e.g., "gpt-4o"
    ),
    project_spec=project_spec
)

try:
    resp = client.generate_guardrails(req)
    print("Guardrails response (summarized):")
    print(resp.guardrails)
    if resp.expanded_guardrails is not None:
        print("Expanded guardrails (more descriptive, higher token usage):")
        print(resp.expanded_guardrails)
    else:
        print("No expanded guardrails returned.")
except Exception as e:
    print(f"Error occurred during guardrails generation: {e}")
```

See [`marsguard/example_usage.py`](marsguard/example_usage.py) for a complete, well-documented dummy template.

## Error Handling

The SDK raises structured exceptions for robust error handling:

- `MarsGuardValidationError`: Raised for invalid request or response schema.
- `MarsGuardAPIError`: Raised for API errors (non-2xx HTTP responses). Includes status code and response text.
- `MarsGuardNetworkError`: Raised for network/connection errors.

Example:

```python
from marsguard.exceptions import MarsGuardAPIError, MarsGuardValidationError, MarsGuardNetworkError

try:
    resp = client.generate_guardrails(req)
except MarsGuardValidationError as ve:
    print("Validation error:", ve)
except MarsGuardAPIError as ae:
    print(f"API error {ae.status_code}: {ae.response_text}")
except MarsGuardNetworkError as ne:
    print("Network error:", ne)
```

## API Reference

- **MarsGuardClient**: Main entry point for backend interaction.
- **AppModel, ModelSpec, AudienceSpec, ContentRulesSpec, CustomSpec, ProjectSpec, GenerateGuardrailsRequest**: Pydantic models for request construction.
- **DualGuardrailsResponse**: Pydantic model for response, with both summarized and expanded guardrails.
- **Exceptions**: All exceptions are in `marsguard.exceptions`.

See the source code and docstrings for detailed API documentation.

## Dependencies

- pydantic >=2.0,<3.0
- requests >=2.28,<3.0