Skip to main content

Behavioural Contracts

A Python package for enforcing behavioural contracts in AI agents. This package provides a framework for defining, validating, and enforcing behavioural contracts that ensure AI agents operate within specified constraints and patterns.

Installation

pip install behavioural-contracts

Quick Start

from behavioural_contracts import behavioural_contract, generate_contract

# Define your contract
contract_data = {
    "version": "1.1",
    "description": "Financial Analyst Agent",
    "role": "analyst",
    "policy": {
        "pii": False,
        "compliance_tags": ["EU-AI-ACT"],
        "allowed_tools": ["search", "summary"]
    },
    "behavioural_flags": {
        "conservatism": "moderate",
        "verbosity": "compact",
        "temperature_control": {
            "mode": "adaptive",
            "range": [0.2, 0.6]
        }
    },
    "response_contract": {
        "output_format": {
            "type": "object",
            "required_fields": [
                "decision", "confidence", "summary", "reasoning",
                "compliance_tags", "temperature_used"
            ],
            "on_failure": {
                "action": "fallback",
                "max_retries": 1,
                "fallback": {
                    "decision": "unknown",
                    "confidence": "low",
                    "summary": "Recommendation rejected due to validation failure.",
                    "reasoning": "The model's response failed validation checks."
                }
            }
        },
        "max_response_time_ms": 4000,
        "behaviour_signature": {
            "key": "decision",
            "expected_type": "string"
        }
    }
}

# Generate a formatted contract
contract = generate_contract(contract_data)

# Use the contract with your agent
@behavioural_contract(contract)
def analyst_agent(signal: dict, **kwargs):
    return {
        "decision": "BUY",
        "confidence": "high",
        "summary": "Strong buy signal based on technical indicators",
        "reasoning": "Multiple indicators show bullish momentum",
        "compliance_tags": ["EU-AI-ACT"],
        "temperature_used": 0.3  # Required field for temperature validation
    }

Key Features

1. Contract Generation

Generate properly formatted contracts from specification data:

from behavioural_contracts import generate_contract

# Basic contract
basic_contract = generate_contract({
    "version": "1.1",
    "description": "Simple Agent",
    "role": "agent",
    "response_contract": {
        "output_format": {
            "required_fields": ["decision", "confidence", "temperature_used"]
        }
    }
})

# Contract with policy and response validation
policy_contract = generate_contract({
    "version": "1.1",
    "description": "Compliant Agent",
    "role": "agent",
    "policy": {
        "pii": False,
        "compliance_tags": ["GDPR", "HIPAA"],
        "allowed_tools": ["search", "analyze"]
    },
    "response_contract": {
        "output_format": {
            "required_fields": [
                "decision", "confidence", "compliance_tags", "temperature_used"
            ]
        },
        "max_response_time_ms": 2000
    }
})

2. Contract Formatting

Format existing contracts to ensure proper value types:

from behavioural_contracts import format_contract

# Format a contract with mixed types
formatted = format_contract({
    "version": 1.1,  # Will be converted to string
    "description": "My Agent",
    "response_contract": {
        "output_format": {
            "required_fields": ["decision", "temperature_used"]
        },
        "max_response_time_ms": 1000
    }
})

3. Behavioural Contract Decorator

Use the decorator to enforce contracts on your agent functions:

from behavioural_contracts import behavioural_contract

# Using a dictionary
@behavioural_contract({
    "version": "1.1",
    "description": "Trading Agent",
    "role": "trader",
    "policy": {
        "pii": False,
        "compliance_tags": ["FINRA"]
    },
    "response_contract": {
        "output_format": {
            "required_fields": [
                "decision", "confidence", "compliance_tags", "temperature_used"
            ]
        }
    }
})
def trading_agent(signal: dict, **kwargs):
    return {
        "decision": "BUY",
        "confidence": "high",
        "compliance_tags": ["FINRA"],
        "temperature_used": 0.3
    }

4. Response Validation

The contract system enforces response validation including:

  • Required fields
  • Temperature range validation
  • Response time limits
  • Compliance tag verification
  • PII detection
  • Tool usage validation
@behavioural_contract({
    "version": "1.1",
    "description": "Validated Agent",
    "role": "agent",
    "behavioural_flags": {
        "temperature_control": {
            "range": [0.2, 0.6]
        }
    },
    "response_contract": {
        "output_format": {
            "required_fields": [
                "decision", "confidence", "temperature_used"
            ]
        },
        "max_response_time_ms": 1000
    }
})
def validated_agent(signal: dict, **kwargs):
    # Response will be validated for:
    # - All required fields present
    # - Temperature within range
    # - Response time under 1000ms
    return {
        "decision": "APPROVE",
        "confidence": "high",
        "temperature_used": 0.3
    }

Contract Structure

A behavioural contract consists of several key sections:

  1. Basic Information

    • version: Contract version
    • description: Agent description
    • role: Agent role
  2. Policy Settings

    • pii: PII handling flag
    • compliance_tags: Required compliance tags
    • allowed_tools: List of allowed tools
  3. Behavioural Flags

    • conservatism: Agent conservatism level
    • verbosity: Output verbosity
    • temperature_control: Temperature settings
      • mode: Control mode (fixed/adaptive)
      • range: Allowed temperature range [min, max]
  4. Response Contract

    • output_format: Response structure requirements
      • type: Output type (usually "object")
      • required_fields: List of required fields
      • on_failure: Fallback configuration
    • max_response_time_ms: Maximum allowed response time
    • behaviour_signature: Key field to track for suspicious behavior

Python Installation

PyPI version Python versions License

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Overview

https://www.openagentstack.ai

Metadata

Release files for behavioural-contracts 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for behavioural-contracts 0.1.1
File Size Uploaded Provenance Actions
behavioural_contracts-0.1.1.tar.gz 17.7 kB Without provenance Details for behavioural_contracts-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for behavioural-contracts 0.1.1
File Interpreter ABI Platform Actions
behavioural_contracts-0.1.1-py3-none-any.whl Python 3 none any Details for behavioural_contracts-0.1.1-py3-none-any.whl

Total release size: 34.9 kB

Release files / behavioural_contracts-0.1.1.tar.gz

Download URL behavioural_contracts-0.1.1.tar.gz
Size 17.7 kB
Tags Source
SHA-256 checksum
How to use checksums
fa0880f685641d069d18523265bd0b603610427566413b9e6fb1f685704bd64d
BLAKE2b-256 checksum
How to use checksums
460efb45f904244015369f66971fe30d00d076e718a6f1dc200aabadbe504f11
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.12.5

Release files / behavioural_contracts-0.1.1-py3-none-any.whl

Download URL behavioural_contracts-0.1.1-py3-none-any.whl
Size 17.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1e38165e77d6701ec8a3edd8d7fa4001237617a2ad115c267a4931bf60d1f5f8
BLAKE2b-256 checksum
How to use checksums
789c23d5a7e37d3c2d753b042b0a62a92475846306c35c94994aa5e82381d99b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.12.5

Security for behavioural-contracts 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page