AIGC makes AI invocation governance deterministic, enforceable, and auditable by design.
AIGC enforces deterministic, fail-closed policy evaluation over every model invocation. No silent fallbacks. No prompt-based governance. Core governance gates are unconditionally fail-closed; configured exceptions (risk scoring warn_only, sink failure log mode) are explicitly scoped and audited.
Every model call is validated against a declared policy, checked for role authorization, schema compliance, and tool constraints, and produces a tamper-evident audit artifact.
Governance is not documentation. It is runtime enforcement.
SDK Implementation: Reference implementation of constitutional governance for AI-assisted systems.
Status: v0.3.0 — 585 tests, 95% coverage. M2: risk scoring, signing (HMAC-SHA256), audit chain (opt-in), composition semantics, pluggable PolicyLoader, policy dates, OTel, policy testing, compliance export CLI, custom gates. Audit schema v1.2.
No AI-influenced behavior is valid unless it is:
- Explicitly specified
- Deterministically enforceable
- Externally observable
- Replayable and auditable
- Governed independently of any specific model or provider
This invariant is not aspirational. Every enforcement path in this SDK is designed to satisfy all five conditions or fail closed.
| Layer | Concern | Implementation |
|---|---|---|
| Behavioral Specification | No implicit behavior | YAML policies validated against JSON Schema (Draft-07) |
| Deterministic Enforcement | Machine-verifiable constraints | enforce_invocation() pipeline — fail-closed on any violation |
| Observability | Structured, persistent artifacts | SHA-256 checksummed audit records per invocation |
| Replay & Audit | Replayable execution paths | Golden replays + deterministic artifact generation |
| Model-Independent Governance | Provider-agnostic control | Roles, schemas, and policies — not prompts |
pip install aigc-sdkThe import name is aigc:
from aigc import enforce_invocationFrom source (editable install with dev dependencies):
python3 -m venv aigc-env
source aigc-env/bin/activate
python -m pip install --upgrade pip setuptools wheel
pip install --no-build-isolation -e '.[dev]'Note: The --no-build-isolation flag is required in network-restricted
environments. It uses the already-installed setuptools and wheel instead of
trying to download them fresh into an isolated build environment.
If using an internal PyPI mirror or wheelhouse, ensure pip, setuptools, and
wheel are available before running the editable install.
Preferred imports:
from aigc import enforce_invocation, AIGC
from aigc.errors import (
InvocationValidationError,
PreconditionError,
SchemaValidationError,
GovernanceViolationError,
)Instance-scoped enforcement (recommended for new code):
from aigc import AIGC
from aigc.sinks import JsonFileAuditSink
engine = AIGC(sink=JsonFileAuditSink("audit.jsonl"))
audit = engine.enforce(invocation)- Invocation shape validation (typed errors, no raw
KeyError) - Policy loading with safe YAML + Draft-07 schema validation
- Role allowlist enforcement
- Preconditions + output schema validation
- Postcondition enforcement (
output_schema_valid) - Deterministic audit artifact generation with canonical SHA-256 checksums
- FAIL audit artifacts emitted before exception propagation
- Conditional guards —
when/thenrules expand effective policy from runtime context; evaluated before role validation; effects are additive - Named conditions — boolean flags resolved from invocation context with defaults and required enforcement
- Tool constraints — per-tool
max_callscap and tool allowlist enforcement; violations emit FAIL audits - Retry policy — opt-in
with_retry()wrapper for transientSchemaValidationErrorfailures with linear backoff - Policy composition —
extendsinheritance with recursive merge (arrays append, dicts recurse, scalars replace) and cycle detection
-
Async enforcement —
enforce_invocation_async()runs policy I/O off the event loop viaasyncio.to_thread; identical governance behavior to sync -
Pluggable audit sinks — every enforcement emits to the configured sink automatically; configurable failure mode (
logorraise). Prefer instance-scoped configuration:from aigc import AIGC from aigc.sinks import JsonFileAuditSink engine = AIGC(sink=JsonFileAuditSink("audit.jsonl"))
The global
set_audit_sink()function is retained for backward compatibility but is not recommended for new code. -
Instance-scoped enforcement —
AIGCclass for thread-safe, isolated configuration (sink, failure mode, strict mode, redaction patterns) -
Structured logging —
aigc.*logger namespace withNullHandlerdefault; host applications configure log levels and handlers -
@governeddecorator — wraps sync and async LLM call sites:from aigc.decorators import governed @governed( policy_file="policies/governance.yaml", role="planner", model_provider="anthropic", model_identifier="claude-sonnet-4-5-20250929", ) async def plan_investigation(input_data: dict, context: dict) -> dict: return await llm.generate(input_data)
- Risk scoring engine — factor-based risk computation with
strict,risk_scored, andwarn_onlymodes;RiskThresholdErrorraised in strict mode when threshold exceeded - Artifact signing — HMAC-SHA256 signing via pluggable
ArtifactSignerinterface; constant-time signature verification - Tamper-evident audit chain — opt-in
AuditChainutility for hash-chaining artifacts withchain_id,chain_index,previous_audit_checksumfields; manual integration by the host - Composition restriction semantics —
intersect,union, andreplacestrategies for policy inheritance viacomposition_strategy - Pluggable PolicyLoader —
PolicyLoaderBaseABC for custom policy sources (database, API, vault);FilePolicyLoaderdefault - Policy version dates —
effective_date/expiration_dateenforcement with injectable clock for testing - OpenTelemetry integration — optional spans and gate events; no-op when OTel is not installed; governance unaffected by telemetry
- Policy testing framework —
PolicyTestCase,PolicyTestSuite,expect_pass(),expect_fail()for policy validation - Compliance export CLI —
aigc compliance exportgenerates JSON compliance reports from JSONL audit trails - Custom EnforcementGate plugins —
EnforcementGateABC with four insertion points (pre_authorization,post_authorization,pre_output,post_output) for host-specific gates
Audit artifacts follow schemas/audit_artifact.schema.json and include:
- policy identity:
policy_file,policy_version,policy_schema_version - model identity:
model_provider,model_identifier,role - result:
enforcement_result, structuredfailures - integrity + auditability:
input_checksum,output_checksum,timestamp - deterministic metadata container:
metadata
.github/workflows/sdk_ci.yml enforces:
- build-tool bootstrap (
pip,setuptools,wheel) and editable install with--no-build-isolationfor restricted-environment parity python -m pytestwith coverage gate (--cov-fail-under=90)flake8foraigc- markdown lint
- policy YAML validation against the Draft-07 policy schema
Before tagging a release, confirm all gates pass locally:
python -m pytest --cov=aigc --cov-report=term-missing --cov-fail-under=90
flake8 aigc
npx markdownlint-cli2 "**/*.md"
python - <<'PY'
import json; from pathlib import Path; import yaml; from jsonschema import Draft7Validator, validate
schema = json.loads(Path("schemas/policy_dsl.schema.json").read_text())
[validate(yaml.safe_load(p.read_text()), schema) or print(f"ok: {p}") for p in Path("policies").glob("*.yaml")]
PYThen tag and push to trigger CI + PyPI publish:
git tag v<version>
git push origin v<version>| Document | Purpose |
|---|---|
| Integration Contract | Runnable hello-world, end-to-end example, extension points, troubleshooting |
| PROJECT.md | Authoritative structure and architecture |
| Architecture Design | Enforcement pipeline and design principles |
| Integration Guide | Host system integration patterns and compliance checklist |
| Policy DSL Spec | Full policy YAML specification |
| Usage Guide | Code examples and best practices |
