🔍 /

GovernLayer Documentation

GovernLayer is the governance layer for agentic AI. It provides compliance auditing, behavioral drift detection, deterministic risk scoring, agent and model registries, shadow AI discovery, policy enforcement, and an immutable hash-chained audit ledger for every AI decision your organization makes.

Built for the Agentic Era
GovernLayer governs not just models, but autonomous AI agents. Register every agent, detect unauthorized (shadow) AI usage, enforce policies, and maintain a tamper-proof audit trail across 18 regulatory frameworks.

Key Capabilities

  • Governance Decisions — Automated APPROVE / BLOCK / ESCALATE decisions with full audit trail
  • Behavioral Drift Detection — Sentence-transformer embeddings measure how far AI reasoning drifts from safety manifolds
  • 6-Dimension Risk Scoring — Deterministic, instant risk assessment across Privacy, Autonomy, Infrastructure, Oversight, Transparency, and Fairness
  • Agent Registry — Register, govern, and monitor every AI agent in your organization
  • Shadow AI Discovery — Detect unauthorized AI usage across 15+ provider patterns
  • Model Registry — Track model lifecycle from development through production with model cards
  • 18 Regulatory Frameworks — Generate compliance reports for EU AI Act, NIST AI RMF, ISO 42001, GDPR, HIPAA, SOC 2, and more
  • Immutable Audit Ledger — SHA-256 hash-chained records that cannot be altered after creation
  • Policy Engine — Define, evaluate, and enforce governance policies programmatically
  • Incident Management — Full lifecycle tracking from detection through resolution
  • Multi-LLM Consensus — Voting, Chain-of-Verification, and Adversarial Debate to prevent hallucinations in critical decisions
  • Enterprise Multi-Tenancy — Organizations, API keys, RBAC, webhooks, and usage metering

Architecture Overview

                    +---------------------------+
                    |      GovernLayer API       |
                    |       (FastAPI v3.0)       |
                    +---------------------------+
                    |   /v1/govern   /v1/risk    |
                    |   /v1/drift    /v1/scan    |
                    |   /v1/agents   /v1/models  |
                    |   /v1/reports  /v1/policies|
                    +-------------+-------------+
                                  |
          +-----------------------+-----------------------+
          |                       |                       |
  +-------v--------+   +---------v--------+   +----------v---------+
  |  Drift Engine   |   |  Risk Scorer     |   | Compliance Auditor |
  | (Embeddings +   |   | (6-Dimension     |   | (LLM-Powered +     |
  |  Safety         |   |  Deterministic)  |   |  18 Frameworks)    |
  |  Manifolds)     |   |                  |   |                    |
  +-------+--------+   +------------------+   +--------------------+
          |
  +-------v--------+   +------------------+   +--------------------+
  | Audit Ledger    |   |  Policy Engine   |   |  Agent Registry    |
  | (SHA-256 Hash   |   | (Rule-Based      |   | (Shadow AI +       |
  |  Chain)         |   |  Evaluation)     |   |  Governance)       |
  +----------------+   +------------------+   +--------------------+
          |
  +-------v----------------------------------------------------+
  |               Achonye Multi-LLM Orchestrator                |
  |  Leader (Opus) -> Board (Sonnet, Gemini, GPT-4o)            |
  |  -> Validator (Consensus Engine) -> Operators (14 models)   |
  +-------------------------------------------------------------+
  |  Ollama (Local)  |  Groq (Fast)  |  OpenRouter (Universal)  |
  +------------------+---------------+--------------------------+

Two Interfaces

GovernLayer offers two ways to integrate:

  • REST API — Full-featured FastAPI server with OpenAPI docs at /docs. Supports JWT and API key authentication.
  • MCP Server — FastMCP server with 12 tools for integration with Claude Desktop, IDEs, and other MCP-compatible clients. Runs via stdio.

Quickstart

Get your first governance decision in under 5 minutes.

Step 1: Register an Account

bash
curl -X POST https://api.governlayer.ai/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@yourcompany.com",
    "password": "SecurePass123",
    "company": "YourCompany"
  }'

Response:

json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "bearer",
  "email": "admin@yourcompany.com"
}

Step 2: Create an Organization

bash
curl -X POST https://api.governlayer.ai/v1/enterprise/orgs \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "YourCompany",
    "slug": "yourcompany",
    "plan": "starter"
  }'

Step 3: Generate an API Key

bash
curl -X POST https://api.governlayer.ai/v1/enterprise/orgs/yourcompany/api-keys \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "production",
    "scopes": "govern,audit,risk,scan"
  }'

Response:

json
{
  "api_key": "gl_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",
  "prefix": "gl_a1b2c3",
  "name": "production",
  "scopes": ["govern", "audit", "risk", "scan"],
  "expires_at": null,
  "warning": "Save this key now. It cannot be retrieved again."
}
Save Your API Key
The full API key is only returned once at creation time. GovernLayer stores a SHA-256 hash of the key, not the key itself. If you lose it, revoke it and generate a new one.

Step 4: Make Your First Governance Decision

bash
curl -X POST https://api.governlayer.ai/v1/govern \
  -H "Authorization: Bearer gl_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6" \
  -H "Content-Type: application/json" \
  -d '{
    "system_name": "loan-scorer",
    "reasoning_trace": "I will evaluate this loan application based on creditworthiness and financial history to determine approval.",
    "use_case": "loan_approval",
    "handles_personal_data": true,
    "makes_autonomous_decisions": false,
    "has_human_oversight": true,
    "is_explainable": true,
    "has_bias_testing": true
  }'

Response:

json
{
  "decision_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "system": "loan-scorer",
  "action": "APPROVE",
  "reason": "Within safe boundaries (risk=66, drift=0.0812)",
  "risk": {
    "score": 66,
    "level": "MEDIUM",
    "dimensions": {
      "privacy": 40,
      "autonomy": 100,
      "infrastructure": 100,
      "oversight": 100,
      "transparency": 100,
      "fairness": 100
    }
  },
  "drift": {
    "coefficient": 0.0812,
    "vetoed": false,
    "flags": 0
  },
  "ledger": {
    "hash": "a3f2b8c91d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0",
    "policy_version": "3.0.0"
  },
  "timestamp": "2026-03-18T14:23:01.456789"
}
You are now governing AI
Every governance decision is recorded in an immutable SHA-256 hash-chained ledger. The decision above has been cryptographically linked to every previous decision, creating a tamper-proof audit trail.

Authentication

GovernLayer supports two authentication methods. Both can be used interchangeably on all /v1/ endpoints.

API Keys (Recommended)

API keys use the gl_ prefix and are scoped to an organization. Pass them in the Authorization header:

http
Authorization: Bearer gl_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6

Scopes

Each API key is assigned scopes that control which endpoints it can access:

ScopeEndpointsDescription
govern/v1/govern, /v1/agents, /v1/models, /v1/incidents, /v1/policiesFull governance pipeline, registry management, incident and policy management
audit/v1/audit/{system}, /auditCompliance auditing and audit history retrieval
risk/v1/riskRisk scoring operations
scan/v1/scan, /v1/drift, /v1/agents/discovery/scanQuick scans, drift detection, shadow AI discovery

JWT Tokens

JWT tokens are issued on registration or login. They are primarily used for account management operations (creating orgs, generating API keys, MFA setup).

bash
curl -X POST https://api.governlayer.ai/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@yourcompany.com",
    "password": "SecurePass123"
  }'

If MFA is enabled, include the TOTP code:

json
{
  "email": "admin@yourcompany.com",
  "password": "SecurePass123",
  "mfa_code": "482937"
}

Password Requirements

  • Minimum 8 characters, maximum 72 characters
  • At least one uppercase letter
  • At least one lowercase letter
  • At least one digit

Rate Limits & Plans

GovernLayer enforces rate limits per API key, backed by Redis. Limits are applied per minute and per month based on your plan tier.

PlanPriceRequests/minRequests/monthFrameworksSupport
Free$0205005Community
Starter$49/mo10010,00018Email
Pro$199/mo500100,00018Priority
EnterpriseCustom2,000+Unlimited18 + CustomDedicated

When you exceed your rate limit, the API returns HTTP 429 Too Many Requests with a Retry-After header indicating when you can make the next request.

json
{
  "detail": "Rate limit exceeded. 20 requests per minute on free plan.",
  "retry_after": 42
}

Governance Decisions

The governance decision pipeline is the core of GovernLayer. When you call POST /v1/govern, the platform runs a multi-stage pipeline and returns one of three actions:

ActionMeaningTrigger Conditions
APPROVEAI action is safe to proceedRisk level LOW or MEDIUM with no semantic flags, drift coefficient within threshold
ESCALATE_HUMANRequires human review before proceedingRisk level HIGH, or MEDIUM risk with semantic risk flags detected
BLOCKAI action is blocked immediatelyBehavioral drift coefficient exceeds safety threshold (default 0.3)

Pipeline Stages

  1. Drift Detection — The AI's reasoning trace is embedded using sentence-transformers and compared against pre-built safety manifolds for the use case. Outputs a drift coefficient (Dc).
  2. Risk Scoring — Six boolean inputs are mapped to deterministic dimension scores. No LLM involved — instant and reproducible.
  3. Decision Logic — If drift is vetoed, BLOCK. If risk is HIGH, ESCALATE. If MEDIUM with semantic flags, ESCALATE. Otherwise, APPROVE.
  4. Ledger Recording — The decision is cryptographically recorded in the hash-chained audit ledger with the previous record's hash.
  5. Webhook Dispatch — If webhooks are configured, a governance.decision event is fired asynchronously.

Drift Detection

Behavioral drift detection measures how far an AI system's reasoning has deviated from its intended safety boundaries. GovernLayer uses sentence-transformer embeddings to compute a drift coefficient.

How It Works

  1. Safety Manifolds — For each use case (loan approval, hiring, medical diagnosis, content moderation, general), a set of reference sentences defines "safe" reasoning behavior. These are pre-embedded at startup.
  2. Trace Embedding — The AI's reasoning trace is embedded into the same vector space using sentence-transformers.
  3. Drift Coefficient (Dc) — Calculated as 1 - cos(v_t, m_s) where v_t is the trace vector and m_s is the manifold centroid. Range: 0.0 (identical) to 2.0 (opposite).
  4. Threshold Check — Default threshold is 0.3. If Dc > threshold, the action is vetoed (BLOCK).

Alignment Levels

Dc RangeAlignmentAction
0.00 – 0.15STRONGLY_ALIGNEDPROCEED
0.15 – 0.30ALIGNEDPROCEED
0.30 – 0.50DRIFTINGVETO
0.50 – 0.80HIGH_DRIFTVETO
0.80 – 2.00CRITICAL_DRIFTVETO

Semantic Risk Patterns

In addition to embedding-based drift, GovernLayer scans for dangerous keyword patterns in reasoning traces:

  • Destructive actions: delete, destroy, remove, eliminate, wipe
  • Bypass attempts: bypass, ignore, skip, override, circumvent
  • Discrimination signals: discriminat*, bias, race, gender, religion, ethnicity
  • Manipulation: manipulat*, deceiv*, trick, mislead, exploit
  • Authorization violations: unauthorized, illegal, prohibited, forbidden

Graceful Degradation

When sentence-transformers is unavailable (e.g., in lightweight Docker builds without PyTorch), the drift engine falls back to keyword-only analysis. If dangerous patterns are detected in keyword-only mode, the drift coefficient is set to 0.5 and the action is vetoed.

Risk Scoring

Risk scoring is fully deterministic — no LLM calls, no network requests, instant response. Six boolean inputs map to fixed scores across six dimensions.

Dimensions

DimensionTrue ScoreFalse ScoreInput Field
Privacy40100handles_personal_data
Autonomy30100makes_autonomous_decisions
Infrastructure25100used_in_critical_infrastructure
Oversight10020has_human_oversight
Transparency10030is_explainable
Fairness10025has_bias_testing

The overall score is the mean of all six dimensions. Risk levels are assigned as:

  • LOW — Score ≥ 80
  • MEDIUM — Score ≥ 50 and < 80
  • HIGH — Score < 50
Worst-Case Score
An AI system that handles personal data, makes autonomous decisions, operates in critical infrastructure, has no human oversight, is not explainable, and has no bias testing receives a score of 28.3 (HIGH risk). Such a system would be automatically escalated for human review.

Audit Ledger

Every governance decision is recorded in a SHA-256 hash-chained audit ledger, providing an immutable, tamper-evident record of all AI governance activity.

Hash Chain Construction

  1. The genesis record uses SHA256("GOVERNLAYER_GENESIS") as its previous hash.
  2. Each subsequent record includes: decision_id, system_name, governance_action, drift_coefficient, risk_score, policy_version, created_at, and the previous record's hash.
  3. The current_hash is computed as SHA256(JSON(record_data + previous_hash)).
  4. Any modification to a historical record would break the hash chain, making tampering detectable.

Ledger Fields

FieldDescription
decision_idUUID v4 unique identifier for this decision
system_nameName of the AI system being governed
governance_actionAPPROVE, ESCALATE_HUMAN, BLOCK, or AUDIT_COMPLETE
risk_scoreCalculated risk score (0-100)
risk_levelLOW, MEDIUM, or HIGH
previous_hashSHA-256 hash of the preceding record
current_hashSHA-256 hash of this record (includes previous_hash)
policy_versionGovernLayer policy version at time of decision
created_atISO 8601 timestamp

Consensus Engine

For critical governance decisions, GovernLayer can route through its multi-LLM consensus engine to prevent hallucinations and ensure reliability. Three strategies are available:

1. Voting

Three or more LLMs independently evaluate the same prompt. The majority answer is selected. Confidence is calculated as the percentage of models that agree. This is the fastest consensus strategy.

2. Chain-of-Verification

A four-stage pipeline designed to catch hallucinations:

  1. Generate — A primary model produces an initial response
  2. Question — A second model generates verification questions about claims in the response
  3. Verify — A third model independently answers those verification questions
  4. Synthesize — A fourth model reconciles discrepancies and produces the final, verified response

3. Adversarial Debate

The most rigorous strategy, used for the highest-stakes decisions:

  1. Claim — A model states a position on the governance question
  2. Critique — A different model challenges the position, identifying weaknesses and counter-arguments
  3. Judge — A third model evaluates both sides and renders a final verdict with reasoning

API: Governance

POST /v1/govern Full governance pipeline

Run the complete governance pipeline: drift detection, risk scoring, decision logic, and ledger recording. Returns APPROVE, ESCALATE_HUMAN, or BLOCK with a full audit trail.

Auth: API Key or JWT — requires govern scope

Request Body

FieldTypeRequiredDescription
system_namestringrequiredName of the AI system being governed
reasoning_tracestringrequiredThe AI's reasoning output to be analyzed for drift (max 10,000 chars)
use_casestringoptionalUse case for drift manifold selection: loan_approval, hiring, medical_diagnosis, content_moderation, general. Default: general
handles_personal_databooleanoptionalDefault: false
makes_autonomous_decisionsbooleanoptionalDefault: false
used_in_critical_infrastructurebooleanoptionalDefault: false
has_human_oversightbooleanoptionalDefault: true
is_explainablebooleanoptionalDefault: true
has_bias_testingbooleanoptionalDefault: false

Response

json
{
  "decision_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "system": "loan-scorer",
  "action": "APPROVE",
  "reason": "Within safe boundaries (risk=66, drift=0.0812)",
  "risk": {
    "score": 66,
    "level": "MEDIUM",
    "dimensions": {
      "privacy": 40, "autonomy": 100, "infrastructure": 100,
      "oversight": 100, "transparency": 100, "fairness": 100
    }
  },
  "drift": {
    "coefficient": 0.0812,
    "vetoed": false,
    "flags": 0
  },
  "ledger": {
    "hash": "a3f2b8c91d4e5f6a7b8c9d0e...",
    "policy_version": "3.0.0"
  },
  "timestamp": "2026-03-18T14:23:01.456789"
}

curl Example

bash
curl -X POST https://api.governlayer.ai/v1/govern \
  -H "Authorization: Bearer gl_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "system_name": "fraud-detector",
    "reasoning_trace": "Analyzing transaction patterns to identify anomalous behavior consistent with fraud.",
    "use_case": "general",
    "handles_personal_data": true,
    "makes_autonomous_decisions": true,
    "has_human_oversight": true,
    "is_explainable": true,
    "has_bias_testing": false
  }'
POST /v1/drift Analyze behavioral drift

Analyze an AI reasoning trace for behavioral drift from safety manifolds. Returns the drift coefficient without creating a governance decision or ledger entry.

Auth: API Key or JWT — requires scan scope

Request Body

FieldTypeRequiredDescription
reasoning_tracestringrequiredAI reasoning text to analyze (max 10,000 chars)
use_casestringoptionalDefault: general
thresholdfloatoptionalDrift threshold (0.0–1.0). Default: 0.3

Response

json
{
  "coefficient": 0.1245,
  "vetoed": false,
  "flags": 0,
  "explanation": "Drift coefficient d_c=0.1245 within safety threshold t=0.3. Reasoning trace is aligned.",
  "timestamp": "2026-03-18T14:25:00.123456"
}
POST /v1/risk Deterministic risk scoring

Calculate a deterministic 6-dimension risk score. No LLM calls — instant response. Uses the same scoring algorithm as the governance pipeline.

Auth: API Key or JWT — requires risk scope

Request Body

FieldTypeRequiredDescription
system_namestringrequiredName of the AI system
handles_personal_databooleanoptionalDefault: false
makes_autonomous_decisionsbooleanoptionalDefault: false
used_in_critical_infrastructurebooleanoptionalDefault: false
has_human_oversightbooleanoptionalDefault: true
is_explainablebooleanoptionalDefault: true
has_bias_testingbooleanoptionalDefault: false

Response

json
{
  "system": "chatbot-support",
  "score": 100,
  "level": "LOW",
  "dimensions": {
    "privacy": 100, "autonomy": 100, "infrastructure": 100,
    "oversight": 100, "transparency": 100, "fairness": 100
  },
  "timestamp": "2026-03-18T14:26:00.789012"
}
POST /v1/scan Quick deterministic scan

Quick scan combining drift detection and risk scoring without LLM calls. Returns an instant APPROVE/ESCALATE/BLOCK decision without recording to the ledger.

Auth: API Key or JWT — requires scan scope

Response

json
{
  "system": "content-moderator",
  "action": "APPROVE",
  "risk_score": 83,
  "drift_coefficient": 0.0923,
  "vetoed": false,
  "timestamp": "2026-03-18T14:27:00.345678"
}

API: Audit & Reports

POST /audit LLM-powered compliance audit

Run a full compliance audit against specified frameworks using LLM analysis. Creates a ledger entry with AUDIT_COMPLETE action.

Auth: JWT

Request Body

FieldTypeRequiredDescription
system_namestringrequiredName of the system to audit
system_descriptionstringrequiredDetailed description (max 5,000 chars)
industrystringrequiredIndustry vertical (e.g., "healthcare", "finance")
frameworksstringrequiredComma-separated frameworks: NIST_AI_RMF,EU_AI_ACT,HIPAA
GET /v1/audit/{system_name} Retrieve audit history

Retrieve governance audit history for a specific system, ordered by most recent first.

Auth: API Key or JWT — requires audit scope

Query Parameters

ParameterTypeDefaultDescription
limitinteger50Max records to return (capped at 100)

Response

json
{
  "system": "loan-scorer",
  "total": 3,
  "records": [
    {
      "decision_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
      "action": "APPROVE",
      "risk_score": 66.0,
      "risk_level": "MEDIUM",
      "hash": "a3f2b8c91d4e5f6a...",
      "created_at": "2026-03-18T14:23:01"
    }
  ]
}
POST /v1/reports Generate compliance report

Generate a regulatory compliance report for any of the 18 supported frameworks.

Request Body

FieldTypeRequiredDescription
system_namestringrequiredName of the system
frameworkstringoptionalFramework ID (see table below). Default: eu_ai_act
risk_tierstringoptionalRisk classification: high, limited, minimal. Default: high
contextobjectoptionalAdditional context data for the report generator

curl Example

bash
curl -X POST https://api.governlayer.ai/v1/reports \
  -H "Content-Type: application/json" \
  -d '{
    "system_name": "loan-approval-v3",
    "framework": "eu_ai_act",
    "risk_tier": "high"
  }'
GET /v1/reports/compliance-summary Cross-framework compliance scores

Quick compliance score summary across 6 key frameworks. Powers dashboard charts.

Query: ?system_name=loan-approval-v3

json
{
  "frameworks": [
    {"id": "eu_ai_act", "name": "EU AI Act", "pct": 72},
    {"id": "nist_ai_rmf", "name": "NIST AI RMF", "pct": 85},
    {"id": "iso_42001", "name": "ISO 42001", "pct": 68},
    {"id": "soc2", "name": "SOC 2", "pct": 91},
    {"id": "hipaa", "name": "HIPAA", "pct": 55},
    {"id": "gdpr", "name": "GDPR", "pct": 78}
  ],
  "average": 74.8
}
GET /v1/reports/frameworks List all 18 supported frameworks

Returns metadata for all 18 regulatory frameworks supported by the report generator, including jurisdiction, description, and applicable industries.

API: Agent Registry

The Agent Registry enables you to register, discover, and govern every AI agent in your organization. It also provides shadow AI detection to find unauthorized AI usage.

POST /v1/agents Register an AI agent

Register an AI agent in the governance registry. Newly registered agents start with pending_review status.

Auth: API Key or JWT — requires govern scope

Request Body

FieldTypeRequiredDescription
namestringrequiredUnique agent name
agent_typestringoptionalautonomous, chatbot, tool_agent, workflow, copilot. Default: autonomous
descriptionstringoptionalWhat this agent does
ownerstringoptionalOwner email or team
teamstringoptionalOrganizational team
purposestringoptionalBusiness purpose
toolsstring[]optionalTools the agent has access to
model_providerstringoptionalLLM provider (OpenAI, Anthropic, etc.)
model_namestringoptionalModel identifier (gpt-4o, claude-sonnet-4-20250514, etc.)
autonomy_levelintegeroptional1 (supervised) to 5 (fully autonomous). Default: 1
risk_tierstringoptionallow, medium, high, critical

curl Example

bash
curl -X POST https://api.governlayer.ai/v1/agents \
  -H "Authorization: Bearer gl_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "support-chatbot-v2",
    "agent_type": "chatbot",
    "description": "Customer support conversational AI",
    "owner": "cx-team@company.com",
    "team": "Customer Experience",
    "purpose": "Handle tier-1 support tickets via chat",
    "model_provider": "OpenAI",
    "model_name": "gpt-4o",
    "tools": ["ticket_lookup", "knowledge_base", "escalation"],
    "autonomy_level": 2,
    "risk_tier": "medium"
  }'
GET /v1/agents List registered agents

List all registered agents with filtering and pagination.

Query Parameters

ParameterTypeDescription
statusstringFilter: approved, pending_review, under_review, rejected, suspended
agent_typestringFilter: autonomous, chatbot, tool_agent, workflow, copilot
is_shadowbooleanFilter for shadow (unregistered) AI agents
teamstringFilter by organizational team
pageintegerPage number (default 1)
limitintegerResults per page (default 50)
POST /v1/agents/{agent_id}/governance Approve, reject, or suspend

Update an agent's governance status. Available actions: approve, reject, suspend, activate, review.

Auth: API Key or JWT — requires govern scope

json
{
  "action": "approve",
  "approved_by": "ciso@company.com",
  "reason": "Passed security review and bias testing"
}
POST /v1/agents/discovery/scan Shadow AI discovery scan

Scan for unauthorized or unregistered AI usage across your organization. Detects 15+ AI provider patterns including OpenAI, Anthropic, Google AI, Azure OpenAI, AWS Bedrock, HuggingFace, Cohere, Replicate, Groq, Mistral, Together AI, LangChain, CrewAI, AutoGen, and local Ollama instances.

Auth: API Key or JWT — requires scan scope

Request Body

json
{
  "scan_type": "api_patterns",
  "targets": [
    "api.openai.com/v1/chat/completions",
    "api.anthropic.com/v1/messages",
    "api-inference.huggingface.co/models/gpt2",
    "localhost:11434/api/generate"
  ]
}

Response

json
{
  "scan_type": "api_patterns",
  "targets_scanned": 4,
  "total_detections": 4,
  "unregistered_ai": 3,
  "risk_level": "critical",
  "detections": [
    {"provider": "OpenAI", "severity": "high", "source": "api.openai.com/v1/chat/completions", "registered": false},
    {"provider": "Anthropic", "severity": "high", "source": "api.anthropic.com/v1/messages", "registered": false},
    {"provider": "HuggingFace", "severity": "medium", "source": "api-inference.huggingface.co/models/gpt2", "registered": false},
    {"provider": "Ollama (Local)", "severity": "low", "registered": true, "agent_id": 5}
  ],
  "recommendation": "Found 3 unregistered AI service(s). Register via POST /v1/agents.",
  "known_patterns": 15
}

API: Model Registry

POST /v1/models Register an AI model

Register a new AI model in the governance registry. Models track lifecycle stages from development through retirement.

Auth: API Key or JWT — requires govern scope

bash
curl -X POST https://api.governlayer.ai/v1/models \
  -H "Authorization: Bearer gl_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "fraud-detector",
    "version": "2.1.0",
    "provider": "pytorch",
    "description": "Real-time transaction fraud detection",
    "owner": "fraud-team@company.com",
    "risk_tier": "high"
  }'
GET /v1/models List registered models

List all registered models with optional filtering by lifecycle stage and governance status. Supports pagination.

Query Parameters: ?lifecycle=production&governance_status=compliant&page=1&limit=50

PUT /v1/models/{model_id}/lifecycle Update model lifecycle

Promote or demote a model through lifecycle stages: development, staging, production, deprecated, retired.

json
{ "lifecycle": "production" }
POST /v1/models/{model_id}/card Create model card

Create a transparency model card documenting intended use, limitations, training data, evaluation metrics, ethical considerations, and fairness analysis.

json
{
  "intended_use": "Credit risk scoring for consumer loans under $50,000",
  "limitations": "Not validated for commercial loans or international markets",
  "training_data_summary": "5M anonymized loan applications, 2018-2025",
  "evaluation_metrics": {"accuracy": 0.94, "auc_roc": 0.97, "f1": 0.91},
  "ethical_considerations": "Tested for disparate impact across race, gender, and age",
  "fairness_analysis": {"disparate_impact_ratio": 0.85, "equalized_odds": true}
}

API: Incidents & Policies

POST /v1/incidents Report a governance incident

Report a new AI governance incident. Automatically triggers webhooks for high/critical severity and sends email notifications.

Auth: API Key or JWT — requires govern scope

bash
curl -X POST https://api.governlayer.ai/v1/incidents \
  -H "Authorization: Bearer gl_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Resume screener bias flag - gender disparity",
    "description": "Disparate impact ratio dropped below 0.8 for gender dimension",
    "severity": "critical",
    "category": "fairness",
    "reporter": "fairness-audit"
  }'

Response

json
{
  "id": 42,
  "title": "Resume screener bias flag - gender disparity",
  "severity": "critical",
  "status": "open",
  "created_at": "2026-03-18T15:30:00.123456"
}
GET /v1/incidents List all incidents

List all incidents with optional filters by status (open, investigating, mitigating, resolved, closed) and severity (low, medium, high, critical). Supports pagination.

PATCH /v1/incidents/{incident_id} Update incident status

Update incident status, severity, assignment, root cause, resolution, or impact. All changes are tracked in a timeline array within the incident record.

json
{
  "status": "investigating",
  "assignee": "ml-ops@company.com",
  "root_cause": "Training data distribution shift after Q4 data refresh",
  "impact": "Affected 2,400 candidate evaluations over 3 days"
}
POST /v1/policies Create governance policy

Create a new governance policy with rules that can be evaluated against AI system contexts.

bash
curl -X POST https://api.governlayer.ai/v1/policies \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production AI Safety Policy",
    "version": "1.0",
    "description": "Standard governance rules for production AI systems",
    "rules": [
      {"name": "risk_threshold", "condition": "risk_score <= 70", "action": "allow", "message": "Risk score within acceptable range"},
      {"name": "drift_threshold", "condition": "drift_coefficient <= 0.30", "action": "allow", "message": "Drift within acceptable range"},
      {"name": "human_oversight", "condition": "has_human_oversight == True", "action": "warn", "message": "Human oversight recommended"},
      {"name": "fairness_check", "condition": "fairness_score >= 70", "action": "allow", "message": "Fairness acceptable"},
      {"name": "high_risk_block", "condition": "risk_score <= 90", "action": "allow", "message": "Extreme risk blocked"}
    ]
  }'
POST /v1/policies/evaluate Evaluate context against policy

Evaluate a context object against a specific policy or the default policy. Returns per-rule results indicating pass/fail/warn status.

json
{
  "policy_id": 1,
  "context": {
    "risk_score": 45,
    "drift_coefficient": 0.22,
    "has_human_oversight": true,
    "fairness_score": 82
  }
}

API: Analytics

GET /v1/analytics/usage/summary Usage summary

High-level usage summary including total requests, success/error rates, average latency, and active API keys.

Query: ?days=30

json
{
  "period_days": 30,
  "total_requests": 14523,
  "success_count": 14201,
  "error_count": 322,
  "error_rate": 2.22,
  "average_latency_ms": 127.45,
  "active_api_keys": 8,
  "requests_per_day": 484.1
}
GET /v1/analytics/usage/top-endpoints Most-used endpoints

Ranked list of most-used API endpoints with request counts, average latency, and error counts.

GET /v1/analytics/usage/governance Governance decision analytics

Breakdown of governance decisions by action type (APPROVE/BLOCK/ESCALATE) with average risk scores per action.

json
{
  "period_days": 30,
  "total_decisions": 847,
  "by_action": [
    {"action": "APPROVE", "count": 712, "percentage": 84.1, "avg_risk_score": 78.3},
    {"action": "ESCALATE_HUMAN", "count": 98, "percentage": 11.6, "avg_risk_score": 42.1},
    {"action": "BLOCK", "count": 37, "percentage": 4.4, "avg_risk_score": 31.5}
  ]
}

API: Threats

POST /threats AI threat analysis

Analyze AI-specific threats using MITRE ATLAS and OWASP AI Security frameworks. Uses LLM analysis combined with live search.

Auth: JWT

json
{
  "system_type": "recommendation_engine",
  "deployment_context": "production"
}
POST /incident-response Generate response plan

Generate a detailed AI incident response plan including containment, investigation, regulatory notification, stakeholder communication, and remediation steps.

json
{
  "incident_type": "data_poisoning",
  "system_name": "fraud-detector",
  "affected_users": 50000,
  "industry": "finance"
}
POST /jurisdiction Map jurisdiction requirements

Map which AI regulations apply based on operating countries, industry, and AI system type. Returns applicable laws, deadlines, penalties, and data residency requirements.

json
{
  "countries": "Germany, United States, Singapore",
  "industry": "healthcare",
  "ai_system_type": "diagnostic_assistant"
}
POST /deadlines Track compliance deadlines

Track upcoming AI regulatory compliance deadlines globally. Uses live search to find the latest deadline information, sorted by urgency.

Regulatory Frameworks

GovernLayer supports 18 regulatory frameworks for compliance report generation. Each framework has a dedicated report generator that maps GovernLayer's governance data to framework-specific controls.

FrameworkIDJurisdictionFocus Area
EU AI Acteu_ai_actEuropean UnionAI risk classification, transparency, human oversight
NIST AI RMFnist_ai_rmfUnited StatesAI Risk Management: Govern, Map, Measure, Manage
ISO 42001iso_42001InternationalAI Management System certification
ISO/IEC 27001iso_27001InternationalInformation Security Management for AI
GDPRgdprEuropean UnionData protection, automated decision-making rights
HIPAAhipaaUnited StatesHealth data protection for AI processing PHI
SOC 2 Type IIsoc2United StatesTrust Service Criteria: security, availability
NIS2 Directivenis2European UnionCybersecurity for essential/important entities
DORAdoraEuropean UnionDigital operational resilience (financial sector)
CCPA/CPRAccpaCalifornia, USAConsumer privacy, automated decision-making
MITRE ATLASmitre_atlasInternationalAdversarial threat landscape for AI
OWASP AI Top 10owasp_aiInternationalTop 10 security risks for AI/ML
NIST CSF 2.0nist_csfUnited StatesCybersecurity Framework functions
OECD AI Principlesoecd_aiInternational (46 countries)Fairness, transparency, accountability
IEEE Ethically Alignedieee_ethicsInternationalEthical autonomous/intelligent systems
HITRUST AIhitrustUnited StatesHealthcare AI assurance
NYC Local Law 144nyc_ll144New York CityAutomated employment decision bias audit
Colorado SB 21-169colorado_sb169ColoradoInsurance algorithmic discrimination prevention

EU AI Act

The EU AI Act classifies AI systems into risk tiers and imposes requirements proportional to the risk level. GovernLayer maps its governance data to EU AI Act requirements automatically.

  • Unacceptable Risk — Banned outright (social scoring, real-time biometric surveillance)
  • High Risk — Requires conformity assessment, risk management, human oversight, transparency, data governance, and registration in the EU database
  • Limited Risk — Transparency obligations (disclose AI interaction)
  • Minimal Risk — Voluntary codes of practice

GovernLayer automatically assesses: risk management system documentation, data governance practices, transparency and explainability, human oversight provisions, accuracy and robustness metrics, and bias testing compliance.

NIST AI RMF

The NIST AI Risk Management Framework provides four core functions:

  • GOVERN — Organizational policies, roles, and accountability for AI risk
  • MAP — Identify and categorize AI risks in context
  • MEASURE — Assess and quantify identified risks using metrics
  • MANAGE — Prioritize and act on risks, monitor residual risk

GovernLayer maps each function to specific platform capabilities: governance decisions map to GOVERN, drift detection and risk scoring map to MEASURE, audit ledger maps to MAP, and policy enforcement maps to MANAGE.

ISO 42001

ISO 42001 is the international standard for AI Management Systems (AIMS). It follows the Annex SL structure familiar from ISO 27001 and ISO 9001, making it integrable with existing management systems. GovernLayer reports map to clauses covering: context of the organization, leadership and commitment, planning for risks and opportunities, support and resources, operational planning and control, performance evaluation, and continual improvement.

GDPR

For AI systems processing personal data of EU residents, GovernLayer assesses GDPR compliance including: lawful basis for processing, data minimization, purpose limitation, automated decision-making safeguards (Article 22), data protection impact assessment (DPIA) requirements, right to explanation, data subject rights, and international transfer safeguards.

HIPAA

For AI systems in healthcare processing Protected Health Information (PHI), GovernLayer evaluates: administrative safeguards, physical safeguards, technical safeguards, organizational requirements, minimum necessary standard compliance, business associate agreements, breach notification procedures, and audit trail requirements. The platform's immutable audit ledger directly supports HIPAA's audit trail requirements.

SOC 2 Type II

GovernLayer maps governance data to SOC 2 Trust Service Criteria: Security (CC1-CC9), Availability (A1), Processing Integrity (PI1), Confidentiality (C1), and Privacy (P1-P8). The platform's hash-chained audit ledger, access controls, and continuous monitoring directly support SOC 2 evidence requirements.

Enterprise Features

Multi-Tenancy

GovernLayer supports full multi-tenancy through Organizations. Each organization has its own API keys, usage records, webhooks, and billing.

bash
# Create organization
curl -X POST https://api.governlayer.ai/v1/enterprise/orgs \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "Acme Corp", "slug": "acme-corp", "plan": "pro"}'

# Get organization details
curl https://api.governlayer.ai/v1/enterprise/orgs/acme-corp \
  -H "Authorization: Bearer $JWT_TOKEN"

# Get usage statistics
curl "https://api.governlayer.ai/v1/enterprise/orgs/acme-corp/usage?days=30" \
  -H "Authorization: Bearer $JWT_TOKEN"

API Key Management

API keys use the gl_ prefix and are scoped to specific permissions. Keys are hashed with SHA-256 before storage — the raw key is only returned once at creation time.

  • Create: POST /v1/enterprise/orgs/{slug}/api-keys — generates a new key with specified scopes and optional expiration
  • List: GET /v1/enterprise/orgs/{slug}/api-keys — returns key metadata (prefix, scopes, last used) but never the full key
  • Revoke: DELETE /v1/enterprise/orgs/{slug}/api-keys/{key_id} — deactivates a key immediately
Key Rotation
To rotate a key, generate a new key, update your integration to use the new key, then revoke the old key. GovernLayer does not support in-place key rotation to avoid service interruption.

Webhooks

Webhooks notify your systems when governance events occur. Each webhook delivery includes an HMAC-SHA256 signature for verification.

Event Types

EventTrigger
governance.decisionAny governance decision (APPROVE, BLOCK, ESCALATE)
governance.approveAI action approved
governance.blockAI action blocked
governance.escalate_humanAI action escalated for human review
audit.completeCompliance audit completed
incident.createdNew incident reported
incident.updatedIncident status changed
incident.resolvedIncident resolved or closed
*All events (wildcard)

Webhook Payload

json
{
  "event": "governance.decision",
  "data": {
    "decision_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
    "system": "loan-scorer",
    "action": "APPROVE",
    "risk_score": 66,
    "risk_level": "MEDIUM"
  }
}

Headers

HeaderDescription
X-GovernLayer-EventEvent type (e.g., governance.decision)
X-GovernLayer-SignatureHMAC-SHA256 signature: sha256={hex_digest}
Content-Typeapplication/json

Multi-Factor Authentication (TOTP)

GovernLayer supports TOTP-based MFA compatible with Google Authenticator, Authy, 1Password, and any standard authenticator app.

Setup Flow

  1. POST /auth/mfa/setup — generates a TOTP secret, provisioning URI, QR code (base64 PNG), and 10 backup codes
  2. Scan the QR code with your authenticator app
  3. POST /auth/mfa/verify with a 6-digit code — enables MFA on your account

Login with MFA

When MFA is enabled, include the mfa_code field in your login request. Alternatively, use one of your 10 backup codes (each can be used once).

Disable MFA

POST /auth/mfa/disable with a valid TOTP code or backup code to disable MFA.

Billing

GovernLayer uses Stripe for billing and subscription management. Each organization can have a Stripe subscription linked to their plan tier.

  • Checkout: POST /billing/checkout — creates a Stripe checkout session for plan upgrades
  • Portal: GET /billing/portal/{slug} — redirects to the Stripe customer portal for managing subscriptions, payment methods, and invoices
  • Usage: GET /billing/usage/{slug} — returns usage metrics for the current billing period
  • Webhooks: POST /billing/webhook — Stripe webhook endpoint for subscription lifecycle events

Architecture

Achonye Multi-LLM Orchestrator

Achonye (pronounced "ah-CHON-yeh") is GovernLayer's hierarchical multi-LLM orchestration system. It routes tasks to the optimal model based on complexity, capability requirements, and cost optimization.

Hierarchy

  +------------------------------------------+
  |           LEADER: Claude Opus 4.6         |
  |    Supreme orchestrator, final arbiter    |
  +--------------------+---------------------+
                       |
  +--------------------v---------------------+
  |                  BOARD                    |
  |  Claude Sonnet | Gemini Pro | GPT-4o     |
  |  Strategic verification and governance   |
  +--------------------+---------------------+
                       |
  +--------------------v---------------------+
  |              VALIDATOR                    |
  |  Multi-LLM Consensus Engine              |
  |  Voting | Chain-of-Verification | Debate |
  +--------------------+---------------------+
                       |
  +--------------------v---------------------+
  |              OPERATORS (14 models)        |
  | Local: Llama3, Mistral, DeepSeek-R1,     |
  |        Qwen3, Phi-3                       |
  | Cloud: Groq Llama, DeepSeek V3, Devstral,|
  |        Grok, Kimi                         |
  +------------------------------------------+

Token Economics

Task ComplexityRoutingCost
TrivialLocal Ollama (Phi-3, Llama3)$0.00 (free)
SimpleLocal Ollama or Groq$0.00 – $0.0006/1K tokens
ComplexStandard cloud (Gemini, GPT-4o, DeepSeek V3)$0.001 – $0.003/1K tokens
CriticalMulti-LLM consensus (3+ models)$0.003 – $0.015/1K tokens

Model Providers

GovernLayer integrates with three provider tiers:

Ollama (Local)

Zero cost, full privacy. All data stays on your infrastructure. Models: Llama 3 8B, Mistral 7B, DeepSeek-R1 14B, Qwen 3 8B, Phi-3 Mini.

Groq (Fast Cloud)

Hardware-accelerated inference for Llama 3.3 70B. Extremely fast response times at minimal cost ($0.00059/1K tokens). Used for tasks that need cloud-level capability with speed.

OpenRouter (Universal Gateway)

Single API key, 500+ models. Routes to Gemini 2.5 Pro (1M context), GPT-4o, DeepSeek V3, Devstral 2, Grok 4.1, Kimi K2.5, Claude Sonnet 4.6, and Claude Opus 4.6. All non-Groq, non-Ollama models route through OpenRouter.

Task Router

The intelligent task router analyzes each request and selects the optimal model based on:

  • Task Complexity — Trivial, simple, moderate, complex, or critical
  • Required Capability — Reasoning, code generation, fact retrieval, verification, math, multimodal, privacy-sensitive, governance
  • Cost Preference — When prefer_local is true, routes to local models first (saves tokens)
  • Consensus Requirement — Critical tasks automatically trigger multi-LLM validation

Agent Orchestration

GovernLayer uses LangGraph StateGraph for agent orchestration. The governance pipeline is modeled as a directed graph with conditional edges:

  • Drift Node — Analyzes reasoning trace for behavioral drift
  • Risk Node — Computes 6-dimension risk score
  • Decision Node — Applies decision logic (APPROVE/ESCALATE/BLOCK)
  • Escalation Edge — Conditional edge to human-in-the-loop when ESCALATE_HUMAN is the decision
  • Ledger Node — Records the decision in the hash-chained audit ledger

Integrations

MCP Server

GovernLayer provides a FastMCP server with 12 tools for integration with Claude Desktop, Cursor, and other MCP-compatible clients. The MCP server runs standalone via stdio and does not require authentication or a database connection.

Available Tools

ToolDescription
list_frameworksList all 27 AI governance frameworks
calculate_risk_score6-dimension risk score calculation
search_regulationsSearch latest AI regulations and news
audit_ai_systemFull compliance audit against top frameworks
get_framework_detailsDetailed framework compliance guide
analyze_policy_gapsGap analysis between existing policies and frameworks
map_jurisdiction_requirementsMap applicable regulations by country and industry
generate_incident_response_planAI incident response plan generation
track_compliance_deadlinesUpcoming regulatory compliance deadlines
analyze_ai_threatsMITRE ATLAS and OWASP AI threat analysis
achonye_routeRoute a task through the intelligent multi-LLM system
achonye_ecosystemView the full multi-LLM ecosystem status

Running the MCP Server

bash
# From the project root
make mcp

# Or directly
python -m src.mcp.server

Claude Desktop Configuration

Add to your ~/.claude/claude_desktop_config.json:

json
{
  "mcpServers": {
    "governlayer": {
      "command": "python",
      "args": ["-m", "src.mcp.server"],
      "cwd": "/path/to/governlayer-ai"
    }
  }
}

n8n Workflows

GovernLayer ships with an importable n8n workflow that runs the full governance pipeline hourly. The workflow is located at n8n-workflows/governlayer_full_pipeline.json.

Setup

bash
# Start n8n
make n8n-start

# Open UI and import the workflow
make n8n-ui
# Import: n8n-workflows/governlayer_full_pipeline.json

Autonomous Daemon

The governance daemon (scripts/governlayer_daemon.py) runs the full pipeline autonomously on a schedule. It can run once or loop at a configurable interval.

bash
# Run pipeline once
make daemon-run

# Start hourly daemon
make daemon-start

# Check health
make daemon-health

# Stop daemon
make daemon-stop

Webhook Consumers

To receive and verify GovernLayer webhooks, implement an HTTPS endpoint that validates the HMAC-SHA256 signature.

python
import hmac
import hashlib
from flask import Flask, request, abort

app = Flask(__name__)
WEBHOOK_SECRET = "your_webhook_secret"

@app.route("/webhook", methods=["POST"])
def handle_webhook():
    body = request.get_data()
    signature = request.headers.get("X-GovernLayer-Signature", "")
    expected = "sha256=" + hmac.new(
        WEBHOOK_SECRET.encode(), body, hashlib.sha256
    ).hexdigest()

    if not hmac.compare_digest(signature, expected):
        abort(401, "Invalid signature")

    event = request.headers.get("X-GovernLayer-Event")
    data = request.get_json()

    if event == "governance.block":
        alert_security_team(data["data"])
    elif event == "incident.created":
        create_jira_ticket(data["data"])

    return {"status": "ok"}, 200

SDKs & Examples

Python

python
import requests

BASE_URL = "https://api.governlayer.ai"
API_KEY = "gl_your_api_key"
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

# Governance decision
resp = requests.post(f"{BASE_URL}/v1/govern", headers=headers, json={
    "system_name": "loan-scorer",
    "reasoning_trace": "Evaluating loan based on credit score and income.",
    "use_case": "loan_approval",
    "handles_personal_data": True,
    "has_human_oversight": True,
    "is_explainable": True,
})
decision = resp.json()
print(f"Action: {decision['action']}, Risk: {decision['risk']['score']}")

# Risk scoring
resp = requests.post(f"{BASE_URL}/v1/risk", headers=headers, json={
    "system_name": "chatbot",
    "handles_personal_data": False,
    "has_human_oversight": True,
    "is_explainable": True,
})
risk = resp.json()
print(f"Risk Level: {risk['level']}, Score: {risk['score']}")

# Register an agent
resp = requests.post(f"{BASE_URL}/v1/agents", headers=headers, json={
    "name": "support-chatbot-v3",
    "agent_type": "chatbot",
    "owner": "cx-team@company.com",
    "model_provider": "OpenAI",
    "model_name": "gpt-4o",
    "autonomy_level": 2,
})
print(f"Agent registered: {resp.json()['id']}")

curl Examples

bash
# Quick scan (no LLM, instant)
curl -X POST https://api.governlayer.ai/v1/scan \
  -H "Authorization: Bearer gl_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"system_name": "chatbot", "reasoning_trace": "Helping user with product question."}'

# Generate EU AI Act report
curl -X POST https://api.governlayer.ai/v1/reports \
  -H "Content-Type: application/json" \
  -d '{"system_name": "hiring-ai", "framework": "eu_ai_act", "risk_tier": "high"}'

# List all incidents
curl https://api.governlayer.ai/v1/incidents?status=open&severity=critical \
  -H "Authorization: Bearer gl_your_api_key"

# Governance analytics
curl "https://api.governlayer.ai/v1/analytics/usage/governance?days=30"

Full Pipeline Example

This example runs the complete governance lifecycle: drift analysis, risk scoring, governance decision, compliance audit, and ledger verification.

python
import requests

BASE = "https://api.governlayer.ai"
KEY = "gl_your_api_key"
H = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}

system = "loan-approval-v3"
trace = "I will evaluate this loan based on credit score, income, and employment history."

# Step 1: Drift detection
drift = requests.post(f"{BASE}/v1/drift", headers=H, json={
    "reasoning_trace": trace, "use_case": "loan_approval", "threshold": 0.3
}).json()
print(f"Drift: {drift['coefficient']} ({'VETOED' if drift['vetoed'] else 'OK'})")

# Step 2: Risk scoring
risk = requests.post(f"{BASE}/v1/risk", headers=H, json={
    "system_name": system, "handles_personal_data": True,
    "has_human_oversight": True, "is_explainable": True, "has_bias_testing": True,
}).json()
print(f"Risk: {risk['score']}/100 ({risk['level']})")

# Step 3: Full governance decision (includes ledger entry)
decision = requests.post(f"{BASE}/v1/govern", headers=H, json={
    "system_name": system, "reasoning_trace": trace,
    "use_case": "loan_approval", "handles_personal_data": True,
    "has_human_oversight": True, "is_explainable": True, "has_bias_testing": True,
}).json()
print(f"Decision: {decision['action']} (hash: {decision['ledger']['hash'][:16]}...)")

# Step 4: Generate compliance report
report = requests.post(f"{BASE}/v1/reports", json={
    "system_name": system, "framework": "eu_ai_act", "risk_tier": "high"
}).json()
print(f"EU AI Act compliance: {report.get('compliance_score', 'N/A')}%")

# Step 5: Verify audit trail
history = requests.get(f"{BASE}/v1/audit/{system}?limit=5", headers=H).json()
print(f"Audit records: {history['total']}")
for r in history['records']:
    print(f"  {r['action']} | Risk: {r['risk_score']} | {r['created_at']}")

Shadow AI Discovery Example

python
import requests

BASE = "https://api.governlayer.ai"
H = {"Authorization": "Bearer gl_your_api_key", "Content-Type": "application/json"}

# Scan network traffic patterns for unauthorized AI usage
scan = requests.post(f"{BASE}/v1/agents/discovery/scan", headers=H, json={
    "scan_type": "api_patterns",
    "targets": [
        "api.openai.com/v1/chat/completions",
        "api.anthropic.com/v1/messages",
        "api-inference.huggingface.co/models/bert-base",
        "bedrock-runtime.us-east-1.amazonaws.com",
        "generativelanguage.googleapis.com/v1beta/models"
    ]
}).json()

print(f"Scanned {scan['targets_scanned']} targets")
print(f"Risk level: {scan['risk_level']}")
print(f"Unregistered AI services: {scan['unregistered_ai']}")

for d in scan['detections']:
    status = "REGISTERED" if d.get('registered') else "UNREGISTERED"
    print(f"  [{status}] {d['provider']} (severity: {d['severity']})")

# Register discovered agents
for d in scan['detections']:
    if not d.get('registered'):
        requests.post(f"{BASE}/v1/agents", headers=H, json={
            "name": f"discovered-{d['provider'].lower().replace(' ', '-')}",
            "agent_type": "autonomous",
            "model_provider": d["provider"],
            "description": f"Auto-discovered via shadow AI scan",
            "risk_tier": d["severity"],
        })
        print(f"  Registered: {d['provider']}")

Security

Overview

GovernLayer implements defense-in-depth security practices across all layers.

Transport Security

  • HSTSStrict-Transport-Security: max-age=63072000; includeSubDomains; preload (2-year max-age)
  • CORS — Locked to governlayer.ai origin. Methods restricted to specific HTTP verbs. Headers restricted to Authorization, Content-Type, X-API-Key

Response Headers

HeaderValue
X-Content-Type-Optionsnosniff
X-Frame-OptionsDENY
X-XSS-Protection1; mode=block
Referrer-Policystrict-origin-when-cross-origin
Permissions-Policycamera=(), microphone=(), geolocation=()

Authentication Security

  • Passwords — Hashed with bcrypt. Minimum 8 characters with uppercase, lowercase, and digit requirements
  • API Keys — Stored as SHA-256 hashes. Raw keys never persisted. Prefix (gl_ + first 6 chars) stored for identification
  • JWT — HS256 signed with a 64-byte secret key. Short-lived tokens
  • MFA — TOTP (RFC 6238) with backup codes. Backup codes hashed with SHA-256

Infrastructure

  • Rate Limiting — Redis-backed, per API key, with plan-based tiers
  • Input Validation — Pydantic models with strict field validation, max lengths, and regex patterns
  • SQL Injection — SQLAlchemy ORM with parameterized queries throughout
  • Docker — Multi-stage builds, non-root user, health checks
  • Secrets — All secrets via environment variables, never hardcoded. pydantic-settings for centralized config

Webhook Signature Verification

Every webhook delivery is signed with HMAC-SHA256 using the webhook secret generated at creation time. Always verify signatures before processing webhook payloads.

python
import hmac
import hashlib

def verify_signature(body: bytes, signature: str, secret: str) -> bool:
    """Verify GovernLayer webhook HMAC-SHA256 signature."""
    expected = "sha256=" + hmac.new(
        secret.encode(), body, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature, expected)
javascript
const crypto = require('crypto');

function verifySignature(body, signature, secret) {
  const expected = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(body)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

Data Handling

  • Reasoning traces are processed for drift analysis and then stored only as SHA-256 hashes in the audit ledger. Raw traces are not persisted beyond the request lifecycle
  • Audit records are immutable once written to the hash-chained ledger. They cannot be modified or deleted
  • API keys are hashed before storage. GovernLayer never stores raw API keys
  • Passwords are hashed with bcrypt with appropriate work factor
  • MFA secrets and backup codes are stored encrypted/hashed in the database
  • Webhook secrets are generated with secrets.token_hex(32) (256-bit entropy)

Changelog

v3.0.0 Current

Released: March 2026

Agent Registry & Shadow AI

  • Full CRUD API for AI agent registration and governance
  • Shadow AI discovery with 15+ provider detection patterns
  • Agent cards for transparency documentation
  • Dependency graph tracking between agents
  • Governance lifecycle: approve, reject, suspend, activate

Model Registry

  • Model lifecycle management: development, staging, production, deprecated, retired
  • Model cards with intended use, limitations, evaluation metrics, fairness analysis
  • Governance status tracking per model

Policy Engine

  • Programmable governance policies with rule-based evaluation
  • Default policy with risk, drift, oversight, and fairness rules
  • Policy versioning and soft-delete deactivation

Incident Management

  • Full incident lifecycle: open, investigating, mitigating, resolved, closed
  • Severity levels: low, medium, high, critical
  • Timeline tracking with actor attribution
  • Automatic webhook and email notifications for high/critical incidents

Analytics & Reporting

  • Usage analytics: summary, trends, top endpoints, latency percentiles, error breakdown
  • Governance analytics: decision breakdown by action type
  • 18 regulatory framework report generators
  • Cross-framework compliance summary

Enterprise

  • Multi-tenancy with organizations
  • Self-service API key provisioning with scopes
  • Redis-backed rate limiting with plan tiers
  • Webhooks with HMAC-SHA256 signatures
  • Usage metering per API key
  • Stripe billing integration
  • TOTP multi-factor authentication with backup codes

Architecture

  • Achonye multi-LLM orchestration with 14-model registry
  • Intelligent task router (complexity + capability analysis)
  • Three consensus strategies: Voting, Chain-of-Verification, Adversarial Debate
  • OpenRouter universal gateway for cloud models
  • Ollama for local inference (zero cost, full privacy)

Security

  • CORS locked to governlayer.ai
  • HSTS with 2-year max-age and preload
  • Permissions-Policy header (camera/mic/geo disabled)
  • API key SHA-256 hashing (raw keys never stored)
  • Mutation audit log for all write operations