### Set Up Development Environment with Hatch Source: https://enforcecore.dev/docs/guides/development.html An alternative setup using Hatch. Install Hatch, create a new environment, and install dependencies. ```bash pip install hatch hatch env create ``` -------------------------------- ### Example Dockerfile for EnforceCore Agent Source: https://enforcecore.dev/docs/defense-in-depth.html This Dockerfile sets up a Python environment, installs EnforceCore, and prepares the agent for runtime execution with specific user and file configurations. ```dockerfile FROM python:3.12-slim # Drop all capabilities, add only what's needed # (handled at runtime via docker run --cap-drop=ALL) # Read-only root filesystem # (handled at runtime via docker run --read-only) # Install EnforceCore RUN pip install enforcecore # Non-root user RUN useradd -m agent USER agent COPY policy.yaml /app/policy.yaml COPY agent.py /app/agent.py CMD ["python", "/app/agent.py"] ``` -------------------------------- ### Install EnforceCore Source: https://enforcecore.dev/docs Install the EnforceCore library using pip. ```bash pip install enforcecore ``` -------------------------------- ### Install enforcecore Source: https://enforcecore.dev/docs/quickstart.html Install the enforcecore library using pip. Use `[all]` to include optional extras. ```bash pip install enforcecore ``` ```bash pip install enforcecore[all] ``` -------------------------------- ### Set Up EnforceCore with Hatch Source: https://enforcecore.dev/docs/dev-guide.html Install Hatch, create a new environment, install dependencies, and run commands within the Hatch environment for EnforceCore development. ```bash # Install hatch if you don't have it pip install hatch # Create environment and install dependencies hatch env create # Run inside the hatch environment hatch run python -c "import enforcecore; print(enforcecore.__version__)" ``` -------------------------------- ### Install EnforceCore with All Features Source: https://enforcecore.dev/docs/getting-started/quickstart.html Install EnforceCore with all optional features, including OpenTelemetry support and framework adapters, using pip. ```bash pip install "enforcecore[all]" ``` -------------------------------- ### Install LangChain Integration Source: https://enforcecore.dev/docs/quickstart.html Install the `langchain-core` package to integrate enforcecore with LangChain. ```bash pip install langchain-core ``` -------------------------------- ### Quick Start Redactor Initialization and Usage Source: https://enforcecore.dev/docs/reference/api/redactor.html Initialize the Redactor with specific PII categories and redact text. This example also shows how to access the redacted text, detected entities, count, and whether redaction occurred. ```python from enforcecore import Redactor redactor = Redactor(categories=["email", "phone", "ssn"]) result = redactor.redact("Contact john@example.com or call 555-123-4567") print(result.text) # "Contact [EMAIL] or call [PHONE]" print(result.entities) # [DetectedEntity(category="email", text="john@example.com", ...), # DetectedEntity(category="phone", text="555-123-4567", ...)] print(result.count) # 2 print(result.was_redacted) # True ``` -------------------------------- ### Quick Start: Record and Verify Audit Trail Source: https://enforcecore.dev/docs/reference/api/auditor.html Demonstrates the basic usage of the Auditor class to record an event and then verify the integrity of the generated audit trail. This is useful for initial setup and understanding the core functionality. ```python from enforcecore import Auditor, verify_trail # Create an auditor auditor = Auditor(output_path="./audit_logs/trail.jsonl") # Record an event entry = auditor.record( tool_name="web_search", policy_name="production", decision="allowed", ) print(entry.entry_hash) # "sha256:a3f2c..." # Verify trail integrity result = verify_trail("./audit_logs/trail.jsonl") print(result.is_valid) # True print(result.total_entries) # 1 ``` -------------------------------- ### Building Custom Adapters Source: https://enforcecore.dev/docs/api-design.html Example of how to build a custom adapter using `wrap_with_policy`. ```APIDOC ### Building Custom Adapters Use `wrap_with_policy` to build adapters for any framework: ``` from enforcecore.integrations import wrap_with_policy def my_framework_tool(func, policy): """Example custom adapter.""" enforced = wrap_with_policy(func, policy=policy) return MyFramework.register_tool(enforced) ``` ``` -------------------------------- ### Clone Repository and Set Up Virtual Environment Source: https://enforcecore.dev/docs/guides/development.html Clone the EnforceCore repository and set up a Python virtual environment. Activate the environment before installing dependencies. ```bash git clone git@github-akiosai:akios-ai/EnforceCore.git cd EnforceCore python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Install EnforceCore in Development Mode Source: https://enforcecore.dev/docs/guides/development.html Install EnforceCore and its development dependencies using pip. This command installs the package in editable mode. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Verify EnforceCore Installation Source: https://enforcecore.dev/docs/guides/development.html Verify that EnforceCore is installed correctly by checking its version. This command runs a small Python script. ```bash python -c "import enforcecore; print(enforcecore.__version__)" ``` -------------------------------- ### Install EnforceCore with OpenTelemetry and Prometheus Source: https://enforcecore.dev/docs/roadmap.html Install EnforceCore with optional packages for OpenTelemetry tracing and logging, or Prometheus metrics. These are useful for integrating EnforceCore's observability features into your existing monitoring infrastructure. ```bash pip install enforcecore pip install enforcecore[otel] # OpenTelemetry traces + logs pip install enforcecore[prometheus] # Prometheus metrics ``` -------------------------------- ### Benchmark JSON Output Example Source: https://enforcecore.dev/docs/benchmarks.html An example of the JSON output format for EnforceCore benchmarks. This format includes metadata about the execution environment and detailed performance results for each benchmarked policy. ```json { "metadata": { "timestamp": "2026-02-21T15:56:09Z", "python_version": "3.14.2", "platform": "Darwin arm64", "cpu": "arm", "machine": "arm64", "enforcecore_version": "1.0.0", "total_duration_ms": 1372.34 }, "results": [ { "name": "policy_pre_call", "iterations": 1000, "warmup_iterations": 100, "mean_ms": 0.0927, "p50_ms": 0.0118, "p95_ms": 0.0196, "p99_ms": 0.2275, "p999_ms": 69.3257, "std_dev_ms": 2.1955 } ] } ``` -------------------------------- ### Error Handling Examples Source: https://enforcecore.dev/docs/reference/api/guard.html Provides examples of how to catch specific errors raised by the Resource Guard. ```APIDOC ## Error Handling Examples ### Description Catch specific exceptions raised by the Resource Guard components when limits are violated. ### Examples **Catching Cost Limit Errors:** ```python from enforcecore.core.types import CostLimitError try: # Assume enforcer is initialized and record_cost exceeds budget enforcer.record_cost(50.00) except CostLimitError as e: print(f"Budget exceeded: {e}") ``` **Catching Rate Limit Errors:** ```python from enforcecore.guard.ratelimit import RateLimitError try: # Assume limiter is initialized and check exceeds rate limit limiter.check("web_search") except RateLimitError as e: print(f"Rate limited: {e}") ``` **Catching Domain Denied Errors:** ```python from enforcecore.guard.network import DomainDeniedError try: # Assume checker is initialized and check is for a denied domain checker.check("evil.malicious.xyz") except DomainDeniedError as e: print(f"Domain denied: {e}") ``` ``` -------------------------------- ### Clone EnforceCore Repository and Set Up Virtual Environment Source: https://enforcecore.dev/docs/dev-guide.html Clone the EnforceCore repository, create a Python virtual environment, activate it, and install the project in development mode with all dev dependencies. ```bash # Clone the repository git clone git@github-akiosai:akios-ai/EnforceCore.git cd EnforceCore # Create a virtual environment python3 -m venv .venv source .venv/bin/activate # Install in development mode with all dev dependencies pip install -e ".[dev]" # Verify setup python -c "import enforcecore; print(enforcecore.__version__)" ``` -------------------------------- ### Example Docker Run Command for EnforceCore Agent Source: https://enforcecore.dev/docs/defense-in-depth.html This command demonstrates how to run a Docker container with EnforceCore, applying security best practices such as dropping all capabilities, using a read-only filesystem, and configuring seccomp. ```bash docker run \ --cap-drop=ALL \ --read-only \ --tmpfs /tmp:noexec,nosuid,size=64m \ --security-opt=no-new-privileges \ --security-opt seccomp=enforcecore-seccomp.json \ --network=restricted \ my-agent:latest ``` -------------------------------- ### Quick Start: Collecting and Verifying Witness Hashes Source: https://enforcecore.dev/docs/api/witness.html This snippet demonstrates how to set up an Auditor with a CallbackWitness to collect hashes and then verify the audit trail against these collected hashes. ```python from enforcecore.auditor import Auditor from enforcecore.auditor.witness import CallbackWitness, verify_with_witness # Collect witness hashes hashes = [] witness = CallbackWitness(hashes.append) auditor = Auditor(output_path="audit.jsonl", witness=witness) # Record some entries auditor.record(tool_name="search", policy_name="strict") auditor.record(tool_name="calculator", policy_name="strict") # Verify trail against witness result = verify_with_witness("audit.jsonl", witness_hashes=[r.entry_hash for r in hashes]) assert result.is_valid ``` -------------------------------- ### Load Sensitivity Configuration from YAML Source: https://enforcecore.dev/docs/api-design.html Example of a YAML structure for configuring sensitivity labels, including enabling/disabling features, setting default clearance, and fallback actions. ```yaml sensitivity_labels: enabled: true default_clearance: internal enforce: true fallback: redact ``` -------------------------------- ### Quick Start: Decorator and Programmatic Enforcement Source: https://enforcecore.dev/docs/reference/api/enforcer.html Demonstrates the two primary ways to integrate EnforceCore: using the `@enforce` decorator for automatic policy application or the `Enforcer` class for programmatic control. ```python from enforcecore import enforce, Enforcer, Policy # Decorator approach (recommended) @enforce(policy="policy.yaml") async def run_agent(user_input: str) -> str: ... # Or use bare decorator with default policy @enforce async def run_agent(user_input: str) -> str: ... # Programmatic approach enforcer = Enforcer.from_file("policy.yaml") result = enforcer.enforce_sync(my_function, *args, tool_name="search") ``` -------------------------------- ### EnforceCore CLI for Plugin Management Source: https://enforcecore.dev/docs/api-design.html Use the `enforcecore` CLI to manage plugins. `enforcecore plugin list` discovers all installed plugins, and `enforcecore plugin info ` loads and inspects a specific plugin. ```bash enforcecore plugin list # Discover all installed plugins enforcecore plugin info # Load and inspect a specific plugin ``` -------------------------------- ### CLI Command for Exporting Compliance Reports Source: https://enforcecore.dev/docs/api-design.html Examples of using the enforcecore CLI to export compliance reports in different formats and periods. ```bash enforcecore audit export --format eu-ai-act --period 2026-Q4 --output report.json enforcecore audit export --format soc2 --period 2026-H1 --output soc2.html ``` -------------------------------- ### Enforce Decorator: Sync Function Example Source: https://enforcecore.dev/docs/reference/api/enforcer.html Demonstrates applying the `@enforce` decorator to a synchronous function for policy enforcement. ```python @enforce(policy="policy.yaml") def classify_document(text: str) -> str: return classifier.predict(text) ``` -------------------------------- ### Quick Start: Protect and Verify Append-Only File Source: https://enforcecore.dev/docs/api/immutable.html Demonstrates the basic usage of `protect_append_only()` to set the OS-level append-only attribute on a file and `is_append_only()` to verify its status. ```python from enforcecore.auditor.immutable import protect_append_only, is_append_only # Protect an existing file protect_append_only("audit.jsonl") assert is_append_only("audit.jsonl") ``` -------------------------------- ### Instrument EnforceCore with OpenTelemetry Source: https://enforcecore.dev/docs/api-design.html Use EnforceCoreInstrumentor to automatically create OpenTelemetry spans for every @enforce() call. Requires `pip install enforcecore[otel]`. Optionally provide tracer and meter providers. ```python from enforcecore import EnforceCoreInstrumentor # Requires: pip install enforcecore[otel] instrumentor = EnforceCoreInstrumentor() instrumentor.instrument( tracer_provider=my_provider, # optional; falls back to global OTel provider meter_provider=my_meter, # optional ) ``` ```python def instrument( self, *, tracer_provider: Any = None, meter_provider: Any = None, ) -> None def uninstrument(self) -> None @property def metrics(self) -> EnforceCoreMetrics @property def is_instrumented(self) -> bool ``` -------------------------------- ### Initialize AuditStore Source: https://enforcecore.dev/docs/api-design.html Initialize AuditStore with an AuditBackend instance. Verification can be enabled or disabled. ```python def __init__(self, backend: AuditBackend, verify_on_read: bool = True) -> None ``` -------------------------------- ### Initialize and Run Benchmark Source: https://enforcecore.dev/docs/api-design.html Instantiate a BenchmarkRunner and run all benchmarks with a specified number of iterations. ```python bench = BenchmarkRunner() suite: BenchmarkSuite = bench.run_all(iterations=1000) ``` -------------------------------- ### Initialize PolicyServerClient Source: https://enforcecore.dev/docs/api-design.html Create a PolicyServerClient to fetch policies from a remote server. Caching and signature verification can be configured. ```python from enforcecore import PolicyServerClient client = PolicyServerClient( url="https://policy.acme.com/agents/chatbot-v2", token=os.environ["POLICY_SERVER_TOKEN"], cache_ttl=300, # seconds; 0 disables caching verify_signature=True, # HMAC-SHA256 verification ) enforcer = Enforcer.from_server(client) ``` -------------------------------- ### Export EnforceCore Metrics with Prometheus Source: https://enforcecore.dev/docs/api-design.html Utilize EnforceCorePrometheusExporter to expose EnforceCore metrics via HTTP. Requires `pip install enforcecore[prometheus]`. The exporter operates in no-op mode if prometheus_client is not installed. ```python from enforcecore import EnforceCorePrometheusExporter # Requires: pip install enforcecore[prometheus] exporter = EnforceCorePrometheusExporter() exporter.instrument() exporter.start_http_server(port=9090) ``` ```python def __init__(self, *, registry: Any = None) -> None # registry: prometheus_client.CollectorRegistry or None (uses global registry). # Operates in no-op mode if prometheus_client not installed — never raises on init. def instrument(self) -> None def uninstrument(self) -> None def start_http_server(self, port: int = 9090, addr: str = "0.0.0.0") -> None @property def is_instrumented(self) -> bool @property def is_available(self) -> bool ``` -------------------------------- ### PluginManager Source: https://enforcecore.dev/docs/api-design.html Manages the discovery, loading, and access of installed EnforceCore plugins. ```APIDOC ## PluginManager Manages the lifecycle of EnforceCore plugins. ### Methods - `discover() -> list[PluginInfo]`: Discovers installed plugins and returns their metadata without loading them. - `load_all(ignore_errors: bool = False) -> int`: Loads all installed plugins. Returns the count of loaded plugins. Raises `PluginLoadError` if any plugin fails to load and `ignore_errors` is `False`. - `load(name: str) -> None`: Loads a single plugin by its name. Raises `PluginLoadError` if the plugin is not found or fails to instantiate. ### Properties - `guards` (list[GuardPlugin]): A list of all loaded guard plugins. - `redactors` (list[RedactorPlugin]): A list of all loaded redactor plugins. - `audit_backends` (list[AuditBackendPlugin]): A list of all loaded audit backend plugins. ``` -------------------------------- ### Initialize PostgreSQLBackend Source: https://enforcecore.dev/docs/api-design.html Initialize the PostgreSQLBackend for production environments. Supports connection pooling, JSONB context, and concurrent writes. ```python from enforcecore.auditstore.backends import PostgreSQLBackend # Requires: pip install enforcecore[postgres] backend = PostgreSQLBackend( host="localhost", database="enforcecore", user="postgres", password="secret", port=5432, verify_merkle=True, pool_size=5, ssl_mode="prefer", # "disable" | "allow" | "prefer" | "require" ) ``` ```python def __init__(self, db_path: str = "audit.db", verify_merkle: bool = True) ``` -------------------------------- ### Auditor with Immutable Source: https://enforcecore.dev/docs/api/immutable.html Example of initializing an Auditor with immutable protection enabled. ```APIDOC ## Auditor(output_path, immutable=True) ### Description Initialize the Auditor with append-only protection enabled for audit files. ### Parameters #### Path Parameters - **output_path** (string) - Required - The path for audit log files. - **immutable** (boolean) - Optional - If set to `True`, enables OS-level append-only protection for audit files. Defaults to `False`. ``` -------------------------------- ### Get All Registered Scenarios Source: https://enforcecore.dev/docs/api-design.html Retrieve a list of all registered adversarial scenarios. ```python scenarios: list[Scenario] = get_all_scenarios() ``` -------------------------------- ### Enforcer Initialization and Guard Access Source: https://enforcecore.dev/docs/reference/api/guard.html Demonstrates how to initialize the Enforcer from a policy file and access the resource guard directly. ```APIDOC ## Enforcer Initialization and Guard Access ### Description Initialize the Enforcer with a policy file and access the `guard` object for manual control or inspection. ### Method ```python from enforcecore import Enforcer # Load policy and initialize Enforcer enforcer = Enforcer.from_file("policy.yaml") # Access the resource guard guard = enforcer.guard ``` ``` -------------------------------- ### Load Enforcer from a Remote Policy Server Source: https://enforcecore.dev/docs/roadmap.html Demonstrates how to initialize an Enforcer by fetching policies from a remote server. This is useful for centralized policy management, allowing agents to pull policies dynamically. Ensure the POLICY_SERVER_TOKEN environment variable is set. ```python Enforcer.from_server( "https://policy.acme.com/agents/chatbot-v2", token=os.environ["POLICY_SERVER_TOKEN"], cache_ttl=300, ) ``` -------------------------------- ### Get Specific Audit Entry Source: https://enforcecore.dev/docs/api-design.html Retrieve a single audit entry by its ID. ```python def get_entry(self, entry_id: str) -> AuditEntry | None ``` -------------------------------- ### Loading Policies Source: https://enforcecore.dev/docs/api-design.html Demonstrates how to load policies from YAML files or create them programmatically using the Policy class. ```APIDOC ## Loading Policies This section shows how to load policies using the `load_policy` function or by instantiating the `Policy` class directly. ### Loading from YAML ```python from enforcecore import load_policy policy = load_policy("policies/strict.yaml") ``` ### Programmatic Loading (from dict) ```python from enforcecore import Policy policy = Policy( name="my-policy", rules={ "allowed_tools": ["search", "calculator"], "pii_redaction": {"enabled": True, "categories": ["email", "phone"]}, "resource_limits": {"max_call_duration_seconds": 30}, }, on_violation="block", ) ``` ### Policy Validation ```python from enforcecore import Policy errors = Policy.validate_file("policies/strict.yaml") if errors: print(f"Policy has errors: {errors}") ``` ``` -------------------------------- ### ComplianceFormat Enum Values Source: https://enforcecore.dev/docs/api-design.html Examples of different compliance formats available in the ComplianceFormat enum. ```python ComplianceFormat.EU_AI_ACT # EU AI Act Articles 9, 13, 14, 52 ComplianceFormat.SOC2 # SOC2 CC6, CC7, CC8, CC9 ComplianceFormat.GDPR # GDPR Article 30 (records of processing) ``` -------------------------------- ### AuditBackend Get Entry Method Source: https://enforcecore.dev/docs/api-design.html Abstract method to retrieve an audit entry by its ID. ```python @abstractmethod def get_entry(self, entry_id: str) -> AuditEntry | None ``` -------------------------------- ### Get Scenarios by Category Source: https://enforcecore.dev/docs/api-design.html Retrieve a list of scenarios belonging to a specific threat category. ```python scenarios: list[Scenario] = get_scenarios_by_category(ThreatCategory.tool_abuse) ``` -------------------------------- ### Load Policies from YAML or Dict Source: https://enforcecore.dev/docs/api-design.html Demonstrates loading policies from a YAML file or defining them programmatically using a dictionary. Includes validation of policy files. ```python from enforcecore import Policy, load_policy # From YAML file policy = load_policy("policies/strict.yaml") # From dict (programmatic) policy = Policy( name="my-policy", rules={ "allowed_tools": ["search", "calculator"], "pii_redaction": {"enabled": True, "categories": ["email", "phone"]}, "resource_limits": {"max_call_duration_seconds": 30}, }, on_violation="block", ) # Validate without loading errors = Policy.validate_file("policies/strict.yaml") if errors: print(f"Policy has errors: {errors}") ``` -------------------------------- ### Redactor Configuration in policy.yaml Source: https://enforcecore.dev/docs/api-design.html Example policy configuration to enable PII redaction for specific categories and strategy. ```yaml # policy.yaml rules: pii_redaction: enabled: true categories: [email, phone, ssn] strategy: placeholder ``` -------------------------------- ### Initialize AuditStoreBackendAdapter Source: https://enforcecore.dev/docs/api-design.html Instantiates AuditStoreBackendAdapter to bridge a backend to the Auditor write API. It automatically translates the Auditor's dict format to AuditEntry. ```python from enforcecore import AuditStoreBackendAdapter adapter = AuditStoreBackendAdapter(backend) auditor = Auditor(backend=adapter) ``` -------------------------------- ### AuditBackend Get Chain Tail Method Source: https://enforcecore.dev/docs/api-design.html Abstract method to retrieve the last entry in the audit chain. ```python @abstractmethod def get_chain_tail(self) -> AuditEntry | None ``` -------------------------------- ### Create CompliancePeriod Instances Source: https://enforcecore.dev/docs/api-design.html Demonstrates creating CompliancePeriod objects for quarterly, half-yearly, and annual periods. ```python period = CompliancePeriod.from_label("2026-Q4") # quarterly period = CompliancePeriod.from_label("2026-H1") # half-year period = CompliancePeriod.from_label("2026") # annual ``` -------------------------------- ### AutoGen Tool Integration Source: https://enforcecore.dev/docs/guides/integrations.html Wrap functions for AutoGen using `enforced_tool` from `enforcecore.integrations.autogen`. This requires `autogen-core` v0.4+ to be installed. ```python from enforcecore.integrations.autogen import enforced_tool @enforced_tool(policy="policy.yaml", description="Get weather") def get_weather(city: str) -> str: return f"Weather in {city}: 22°C, sunny" ``` ```python from enforcecore.integrations.autogen import enforced_tool @enforced_tool(policy="policy.yaml", description="Get current weather") def get_weather(city: str) -> str: return f"Weather in {city}: 22°C, sunny" # Register with an AutoGen agent agent.register_tool(get_weather) ``` -------------------------------- ### CrewAI Tool Integration Source: https://enforcecore.dev/docs/guides/integrations.html Integrate tools with CrewAI using the `enforced_tool` decorator from `enforcecore.integrations.crewai`. Requires `crewai` to be installed. ```python from enforcecore.integrations.crewai import enforced_tool @enforced_tool(policy="policy.yaml") def calculator(expression: str) -> str: """Evaluate a math expression.""" return str(eval(expression)) ``` ```python from enforcecore.integrations.crewai import enforced_tool @enforced_tool(policy="policy.yaml") def calculator(expression: str) -> str: """Evaluate a math expression.""" return str(eval(expression)) # Assign to a CrewAI agent agent = Agent(tools=[calculator], ...) ``` -------------------------------- ### Initialize MultiTenantEnforcer Source: https://enforcecore.dev/docs/api-design.html Instantiate MultiTenantEnforcer with a default policy and register policies for specific tenants. ```python from enforcecore import MultiTenantEnforcer mt = MultiTenantEnforcer(default_policy="base_policy.yaml") mt.register("team_a", "team_a_policy.yaml") mt.register("team_b", "team_b_policy.yaml") ``` -------------------------------- ### Initialize Enforcer from File or Policy Object Source: https://enforcecore.dev/docs/reference/api/enforcer.html Demonstrates two ways to initialize an Enforcer instance: directly from a YAML policy file or by first creating a Policy object from a file and then passing it to the Enforcer constructor. ```python from enforcecore import Enforcer, Policy # From YAML file enforcer = Enforcer.from_file("policy.yaml") # From Policy object policy = Policy.from_file("policy.yaml") enforcer = Enforcer(policy) ``` -------------------------------- ### Conventional Commit Messages Source: https://enforcecore.dev/docs/dev-guide.html Examples of commit messages following the Conventional Commits specification for various types of changes. ```text feat(policy): add YAML policy loading with Pydantic validation fix(enforcer): handle async generator functions correctly docs(readme): add quickstart guide test(auditor): add Merkle chain integrity tests chore(ci): add macOS to test matrix ``` -------------------------------- ### CrewAI Agent Tool Assignment Source: https://enforcecore.dev/docs/api/integrations.html Demonstrates assigning an EnforceCore-enforced tool to a CrewAI agent. Ensure the `crewai` package is installed. ```python from enforcecore.integrations.crewai import enforced_tool @enforced_tool(policy="policy.yaml") def calculator(expression: str) -> str: """Evaluate a math expression.""" return str(eval(expression)) # Assign to a CrewAI agent agent = Agent(tools=[calculator], ...) ``` -------------------------------- ### Run Benchmarks via CLI Source: https://enforcecore.dev/docs/benchmarks.html Execute benchmarks using the command-line interface. Options include setting the number of iterations, output format (Markdown, JSON, or all), and specifying an output directory. ```bash # Default: 1000 iterations, Markdown output python -m benchmarks.run ``` ```bash # 5000 iterations, JSON output python -m benchmarks.run --iterations 5000 --format json ``` ```bash # Both formats, written to disk python -m benchmarks.run --format all --output results/ ``` -------------------------------- ### NERBackend Source: https://enforcecore.dev/docs/api-design.html The NERBackend class is used for Named Entity Recognition to detect PII in text. It requires additional installations for spaCy and presidio-analyzer. ```APIDOC ## NERBackend ### Description Provides functionality for Named Entity Recognition (NER) to detect PII within text. ### Initialization ```python from enforcecore import NERBackend # Requires: pip install enforcecore[ner] # Requires: python -m spacy download en_core_web_lg ner = NERBackend(threshold=0.8, language="en") ``` ### Method: analyze Analyzes the input text to identify and categorize named entities. - **text** (str): The text to analyze. - **categories** (set[str] | None, optional): A set of specific entity categories to detect. If None, all supported entity types are detected. - **threshold** (float | None, optional): A confidence threshold for entity detection. If None, the default threshold set during initialization is used. ### Returns - list[tuple[int, int, str, float]]: A list of tuples, where each tuple represents a detected entity with its start position, end position, category, and confidence score. The list is sorted by the start position. ### Example ```python spans = ner.analyze("Call John at john@acme.com") # -> [(9, 13, "person_name", 0.95), (17, 29, "email", 0.99)] ``` ### Properties - **threshold** (float): The current confidence threshold. - **language** (str): The language model currently in use. ### Supported entity categories: `email`, `phone`, `ssn`, `credit_card`, `ip_address`, `person_name`, `passport`, `location`, `date_time`, `national_id`, `medical_id`, `driver_license`, `iban`, `crypto_address`, `bank_account`, `itin`, `us_tin`. ``` -------------------------------- ### Initialize and Export Compliance Report Source: https://enforcecore.dev/docs/api-design.html Instantiate ComplianceReporter and export a report in EU AI Act format for a specific quarter. ```python from enforcecore import ComplianceReporter, ComplianceFormat, CompliancePeriod reporter = ComplianceReporter() report = reporter.export( ComplianceFormat.EU_AI_ACT, CompliancePeriod.from_label("2026-Q4"), ) ``` -------------------------------- ### Initialize JSONLBackend Source: https://enforcecore.dev/docs/api-design.html Initialize the JSONLBackend for storing audit logs in a JSONL file. Parent directories are created automatically. ```python from enforcecore.auditstore.backends import JSONLBackend backend = JSONLBackend("audit_logs/trail.jsonl") ``` ```python def __init__(self, path: str = "audit_logs/trail.jsonl") ``` -------------------------------- ### Require Package Utility Source: https://enforcecore.dev/docs/guides/integrations.html The `require_package` utility from `enforcecore.integrations._base` checks for package importability and raises an `ImportError` with installation instructions if the package is missing. ```python from enforcecore.integrations._base import require_package require_package("langchain_core", pip_name="langchain-core") ``` -------------------------------- ### LangGraph/LangChain Tool Integration Source: https://enforcecore.dev/docs/guides/integrations.html Use the `enforced_tool` decorator from `enforcecore.integrations.langgraph` to wrap a function for use with LangGraph or LangChain. Ensure `langchain-core` is installed. ```python from enforcecore.integrations.langgraph import enforced_tool @enforced_tool(policy="policy.yaml") def search_web(query: str) -> str: """Search the web.""" return api.search(query) ``` ```python from enforcecore.integrations.langgraph import enforced_tool @enforced_tool(policy="policy.yaml") def search_web(query: str) -> str: """Search the web for information.""" return api.search(query) # Use in a LangGraph node — tool calls are automatically enforced result = search_web.invoke({"query": "AI safety"}) ``` -------------------------------- ### Standalone Redactor Usage Source: https://enforcecore.dev/docs/api-design.html Demonstrates initializing the Redactor with default or custom settings for categories and strategies. Shows how to perform detection-only or full redaction operations and access results. ```python from enforcecore.redactor import Redactor, RedactionResult, DetectedEntity from enforcecore.core.types import RedactionStrategy # Default: all categories, placeholder strategy redactor = Redactor() # Selective categories redactor = Redactor(categories=["email", "phone"]) # Custom strategy redactor = Redactor(strategy=RedactionStrategy.HASH) # Detection only (no modification) entities: list[DetectedEntity] = redactor.detect("Email john@example.com") for e in entities: print(f" {e.category}: {e.text!r} at [{e.start}:{e.end}]") # Full redaction result: RedactionResult = redactor.redact("Call 555-123-4567 or john@example.com") print(result.text) # "Call or " print(result.count) # 2 print(result.was_redacted) # True print(result.original_text) # "Call 555-123-4567 or john@example.com" print(result.entities) # [DetectedEntity(category="phone", ...), ...] print(result.events) # [RedactionEvent(entity_type="phone", ...), ...] ``` -------------------------------- ### LangGraph/LangChain Tool Usage Source: https://enforcecore.dev/docs/api/integrations.html Example of invoking an enforced tool within a LangGraph node. Tool calls are automatically enforced by EnforceCore. ```python from enforcecore.integrations.langgraph import enforced_tool @enforced_tool(policy="policy.yaml") def search_web(query: str) -> str: """Search the web for information.""" return api.search(query) # Use in a LangGraph node — tool calls are automatically enforced result = search_web.invoke({"query": "AI safety"}) ``` -------------------------------- ### Get Enforcement Call Chain Source: https://enforcecore.dev/docs/api-design.html Returns a copy of the current enforcement call chain, listing tool names from outermost to innermost. ```python get_enforcement_chain() -> list[str] ``` -------------------------------- ### platform_info() Source: https://enforcecore.dev/docs/api-design.html Retrieves information about the current platform and sandbox environment. ```APIDOC ## platform_info() ### Description Retrieves information about the current platform and sandbox environment. ### Method `platform_info() -> dict` ### Parameters None ### Request Example ```python from enforcecore.sandbox.runner import platform_info info = platform_info() print(info) # Example Output: # { # "platform": "linux", # "subprocess_isolation": True, # "resource_limits": True, # "memory_limits": True, # "cpu_time_limits": True, # "env_restriction": True, # "wasm_sandbox": False, # "python_version": "3.9.1" # } ``` ### Response #### Success Response (200) - **info** (dict) - A dictionary containing platform and sandbox environment details. ``` -------------------------------- ### Configuration (Environment Variables) Source: https://enforcecore.dev/docs/api-design.html Environment variables for configuring EnforceCore settings, prefixed with ENFORCECORE_. ```APIDOC ## Configuration (Environment Variables) All settings can be overridden via environment variables prefixed with `ENFORCECORE_`: ``` ENFORCECORE_DEFAULT_POLICY=policies/default.yaml ENFORCECORE_AUDIT_PATH=./audit_logs/ ENFORCECORE_AUDIT_ENABLED=true ENFORCECORE_REDACTION_ENABLED=true ENFORCECORE_LOG_LEVEL=INFO ENFORCECORE_COST_BUDGET_USD=100.0 ENFORCECORE_FAIL_OPEN=false # NEVER set to true in production ENFORCECORE_DEV_MODE=false # Set to true/1/yes to suppress fail_open warnings ``` ``` -------------------------------- ### Enable Verbose Enforcement Logging Source: https://enforcecore.dev/docs/dev-guide.html Configure structlog to capture DEBUG level logs for detailed enforcement tracing. Ensure structlog is installed. ```python import structlog structlog.configure( wrapper_class=structlog.make_filtering_bound_logger(0), # DEBUG level ) ``` -------------------------------- ### Configure and Check Rate Limits Source: https://enforcecore.dev/docs/reference/api/guard.html Initialize a `RateLimiter`, add specific rate limits for tools or global usage, and check compliance before making a call. Raises `RateLimitError` if the limit is exceeded. ```python from enforcecore.guard.ratelimit import RateLimiter, RateLimit limiter = RateLimiter() limiter.add_limit("web_search", RateLimit(max_calls=10, window_seconds=60)) # Check before calling limiter.check("web_search") # Raises RateLimitError if exceeded ``` -------------------------------- ### Get Current Enforcement Depth Source: https://enforcecore.dev/docs/api-design.html Retrieves the current nesting depth of enforcement scopes. Returns 0 if not currently within any enforcement scope. ```python get_enforcement_depth() -> int ``` -------------------------------- ### Load Plugins with EnforceCore PluginManager Source: https://enforcecore.dev/docs/roadmap.html Initialize and load all available plugins using the PluginManager. This allows for the use of custom guards, redactors, and audit backends. ```python # pip install enforcecore-guard-pii-enterprise from enforcecore import PluginManager manager = PluginManager() manager.load_all() print(manager.guards) # [] ``` -------------------------------- ### Human-Readable Policy Example Source: https://enforcecore.dev/docs/compliance/eu-ai-act.html A declarative YAML policy defining allowed and denied tools, and the action to take on violation. This policy is designed to be readable by non-developers. ```yaml name: "reviewed-policy" version: "1.0" rules: allowed_tools: ["search_web", "calculator"] denied_tools: ["execute_shell"] on_violation: "block" # Human decision: block, not log ``` -------------------------------- ### Detect Current Platform Information Source: https://enforcecore.dev/docs/dev-guide.html Use the detect_platform function to get information about the operating system, architecture, and supported features like cgroups and seccomp. ```python from enforcecore.guard.platform import detect_platform info = detect_platform() print(info) # PlatformInfo(os='darwin', arch='arm64', cgroups=False, seccomp=False, setrlimit=True) ``` -------------------------------- ### Configuration Source: https://enforcecore.dev/docs/api-design.html Utilities for managing global settings and configurations. ```APIDOC ## Configuration ### `Settings` #### Description Represents the global configuration object for EnforceCore. ### `settings` #### Description A module-level singleton instance of `Settings` for accessing and modifying global configurations. ``` -------------------------------- ### Run EnforceCore Tests with Coverage Source: https://enforcecore.dev/docs/dev-guide.html Run all tests and generate a coverage report, showing missing lines for the enforcecore module. ```bash # Run with coverage pytest --cov=enforcecore --cov-report=term-missing ``` -------------------------------- ### EnforceCore API Decorator Example Source: https://enforcecore.dev/docs/concepts/architecture.html This snippet shows how to use the EnforceCore decorator to apply policies to an asynchronous function. It demonstrates policy specification and function definition. ```python DEC["@enforce(policy='my_policy.yaml')
async def call_tool(args): ..."] ``` -------------------------------- ### Import AuditStore Source: https://enforcecore.dev/docs/api-design.html Import the AuditStore class for querying audit records. ```python from enforcecore.auditstore import AuditStore ``` -------------------------------- ### Enforce Python Code with @enforce Decorator Source: https://enforcecore.dev/docs/getting-started/quickstart.html Apply the `@enforce` decorator to Python functions to enforce defined policies. This example demonstrates allowed and blocked actions. ```python import asyncio from enforcecore import enforce, EnforcementViolation # 1. Apply the policy @enforce(policy="strict.yaml") async def search_web(query: str) -> str: # Simulating a tool call return f"Results for: {query}" @enforce(policy="strict.yaml") async def execute_shell(cmd: str) -> str: # This should be blocked return f"Executed: {cmd}" async def main(): try: # Allowed Action print("🤖 Agent: Searching web...") result = await search_web("Python security best practices") print(f"✅ Success: {result}") # Blocked Action print("\n🤖 Agent: Attempting shell execution...") await execute_shell("rm -rf /") except EnforcementViolation as e: print(f"⛔ BLOCKED: {e}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Configure and Check Network Domains Source: https://enforcecore.dev/docs/reference/api/guard.html Initialize a `DomainChecker` with allowed and denied domains, including wildcard support. Use the `check` method to validate network requests, which raises `DomainDeniedError` for disallowed domains. ```python from enforcecore.guard.network import DomainChecker checker = DomainChecker( allowed_domains=["api.openai.com", "*.wikipedia.org"], denied_domains=["*.malicious.xyz"], deny_all_other=True, ) checker.check("api.openai.com") # OK checker.check("evil.malicious.xyz") # Raises DomainDeniedError checker.check("random-site.com") # Raises DomainDeniedError (deny_all_other) ``` -------------------------------- ### Enforce Policy on Function Source: https://enforcecore.dev/docs Apply a YAML-defined policy to an asynchronous Python function using the enforce decorator. This example uses a 'strict.yaml' policy for web searches. ```python from enforcecore import enforce @enforce(policy="policies/strict.yaml") async def search_web(query: str) -> str: return await api.search(query) ``` -------------------------------- ### Get Sensitivity Level from String Source: https://enforcecore.dev/docs/api-design.html Convert string representations (including aliases like 'confidential') to SensitivityLabel enum values. Raises ValueError for unrecognized strings. ```python from enforcecore import sensitivity_level, SensitivityLabel level = sensitivity_level("confidential") # -> SensitivityLabel.CONFIDENTIAL ```