# Behavioural Contracts API Reference

## Core Classes

### BehaviouralContract
The main contract enforcement class.

```python
from behavioural_contracts import BehaviouralContract

contract = BehaviouralContract({
    "version": "1.0",
    "description": "My Agent",
    "policy": {"pii": False},
    "behavioural_flags": {"conservatism": "high"},
    "response_contract": {
        "output_format": {
            "required_fields": ["decision", "confidence"]
        }
    }
})
```

### PromptInjectionDetector
Detects prompt injection attempts in input text.

```python
from behavioural_contracts.security import PromptInjectionDetector

detector = PromptInjectionDetector()
is_injection, patterns, confidence = detector.detect_injection(text)
```

### ContextValidator
Validates context consistency to prevent hallucinations.

```python
from behavioural_contracts.security import ContextValidator

validator = ContextValidator()
is_consistent, message, score = validator.validate_context_consistency(
    current_response, previous_context
)
```

### ComplianceTemplates
Pre-configured templates for regulatory compliance.

```python
from behavioural_contracts.compliance_templates import ComplianceTemplates

# Get GDPR template
gdpr_contract = ComplianceTemplates.gdpr_template()

# Get HIPAA template
hipaa_contract = ComplianceTemplates.hipaa_template()

# Create multi-compliance template
multi_contract = ComplianceTemplates.create_multi_compliance_template(
    ["GDPR", "HIPAA", "SOC2"]
)
```

## Decorators

### @behavioural_contract
Main decorator for enforcing behavioural contracts.

```python
from behavioural_contracts import behavioural_contract

@behavioural_contract({
    "version": "1.0",
    "description": "Security Agent",
    "response_contract": {
        "output_format": {
            "required_fields": ["decision", "confidence", "temperature_used"]
        }
    }
})
def security_agent(threat: str) -> dict:
    return {
        "decision": "block",
        "confidence": "high",
        "temperature_used": 0.3
    }
```

### @create_compliant_agent
Creates agents with pre-configured compliance templates.

```python
from behavioural_contracts.compliance_templates import create_compliant_agent

@create_compliant_agent("gdpr")
def gdpr_agent(data: str) -> dict:
    return {
        "compliance_status": "compliant",
        "data_processing_basis": "legitimate_interest",
        "privacy_impact": "low",
        "recommendations": ["Data processed according to GDPR"]
    }
```

## Utility Functions

### generate_contract
Generates properly formatted contracts from specification data.

```python
from behavioural_contracts import generate_contract

contract = generate_contract({
    "version": "1.0",
    "description": "My Agent",
    "response_contract": {
        "output_format": {
            "required_fields": ["decision", "confidence"]
        }
    }
})
```

### format_contract
Formats existing contracts to ensure proper value types.

```python
from behavioural_contracts import format_contract

formatted = format_contract({
    "version": 1.0,  # Will be converted to string
    "description": "My Agent",
    "response_contract": {
        "output_format": {
            "required_fields": ["decision"]
        }
    }
})
```

## Configuration

### Contract Structure
```python
{
    "version": "1.0",                    # Contract version
    "description": "Agent description",  # Human-readable description
    
    "policy": {                          # Policy settings
        "pii": False,                    # PII handling flag
        "compliance_tags": ["GDPR"],     # Required compliance tags
        "allowed_tools": ["search"]      # Allowed tools
    },
    
    "behavioural_flags": {               # Behavioural configuration
        "conservatism": "high",          # Conservatism level
        "verbosity": "compact",          # Output verbosity
        "temperature_control": {         # Temperature settings
            "mode": "adaptive",          # Control mode
            "range": [0.2, 0.6]         # Allowed range
        }
    },
    
    "response_contract": {               # Response validation
        "output_format": {               # Output structure
            "required_fields": ["decision", "confidence"],
            "on_failure": {              # Fallback configuration
                "action": "fallback",
                "max_retries": 1
            }
        },
        "max_response_time_ms": 4000,    # Time limit
        "behaviour_signature": {         # Behaviour tracking
            "key": "decision",
            "expected_type": "string"
        }
    }
}
```

## Error Handling

### BehaviouralContractViolationError
Raised when contract validation fails.

```python
from behavioural_contracts.exceptions import BehaviouralContractViolationError

try:
    result = agent_function(input_data)
except BehaviouralContractViolationError as e:
    print(f"Contract violation: {e}")
    # Handle violation (e.g., use fallback response)
```

## Best Practices

1. **Always include required fields** in your response
2. **Set appropriate temperature ranges** for your use case
3. **Use compliance templates** for regulated domains
4. **Test with the interactive demo** before production
5. **Monitor contract violations** in production logs
6. **Regularly update compliance templates** as regulations change 