AxonFlow Python SDK
Enterprise AI Governance in 3 Lines of Code.

Upgrade strongly recommended. AxonFlow ships substantial monthly security and quality hardening; staying on the latest major is the security-supported release line. Latest release · Security advisories
Taking a sponsored workflow to production?
Choose the path that fits:
- Self-serve: free 90-day Evaluation License
- Paid production program: Design Partner or Confidential Pilot - one scoped workflow over 60 or 75 days, founder-led rollout support, upfront conversion pricing, and a fixed decision date; public track from $2,000 or confidential track from $4,000
The paid program requires a dated forcing event, written controls, an executive sponsor, and a technical owner. Prices are subject to eligibility and a signed agreement.
Questions or feedback?
Comment in GitHub Discussions or email hello@getaxonflow.com for private feedback.
How This SDK Fits with AxonFlow
This SDK is a client library for interacting with a running AxonFlow control plane. It is used from application or agent code to send execution context, policies, and requests at runtime.
A deployed AxonFlow platform (self-hosted or cloud) is required for end-to-end AI governance. SDKs alone are not sufficient—the platform and SDKs are designed to be used together.
See AxonFlow in Action
Videos covering different angles of the platform:
Installation
pip install axonflow
With LLM provider support:
pip install axonflow[openai] # OpenAI integration
pip install axonflow[anthropic] # Anthropic integration
pip install axonflow[all] # All integrations
Evaluation Tier (Free License)
Need more capacity than Community without moving to Enterprise? Evaluation uses the same core features with higher limits:
| Limit |
Community |
Evaluation (Free) |
Enterprise |
| Tenant policies |
20 |
50 |
Unlimited |
| Org-wide policies |
0 |
5 |
Unlimited |
| Audit retention |
3 days |
14 days |
3650 days |
| Concurrent executions |
5 |
25 |
Unlimited |
| Pending execution approvals |
5 |
25 |
Unlimited |
| Evidence export (CSV / JSON) |
— |
5,000 records · 14d window · 3/day |
Unlimited |
| Policy simulation |
— |
300 / day |
Unlimited |
Concurrent executions applies to MAP and WCP executions per tenant. Pending execution approvals applies to MAP confirm/step mode and WCP approval queues.
Note: Evidence export and policy simulation are licensed AxonFlow platform capabilities available alongside the SDK on your deployed platform — not language-specific SDK helpers. Access them via the platform API or customer portal. The SDK row is included to show what your licensed deployment unlocks at each tier.
Get a free Evaluation license · Run a paid production program · Full feature matrix
Hosted without installing the platform
Start at the AxonFlow website and follow Hosted signup to the verified Portal. Verify your email, complete account and plan setup, then link an API client in the Portal. Store its client ID and secret securely. A newly registered unpaid Basic account cannot obtain a linked credential through the Portal.
export AXONFLOW_TRY=1
export AXONFLOW_CLIENT_ID='<linked-client-id>'
export AXONFLOW_CLIENT_SECRET='<linked-client-secret>'
import os
from axonflow import AxonFlow
client = AxonFlow(
client_id=os.environ["AXONFLOW_CLIENT_ID"],
client_secret=os.environ["AXONFLOW_CLIENT_SECRET"],
)
AXONFLOW_TRY=1 selects the Hosted endpoint; pass the linked credentials to the constructor as shown. Alternatively, set endpoint="https://try.getaxonflow.com" explicitly with the variable unset. The legacy axonflow.community.register_try() default now directs new Hosted buyers to the Portal before making a request; its custom endpoint form remains available for a self-hosted Community server. For a self-hosted client, unset AXONFLOW_TRY so the explicit endpoint is used. Learn more.
Quick Start
Async Usage (Recommended)
import asyncio
from axonflow import AxonFlow
async def main():
async with AxonFlow(
endpoint="https://your-agent.axonflow.com",
client_id="your-client-id",
client_secret="your-client-secret",
) as client:
# Execute a governed query
response = await client.proxy_llm_call(
user_token="user-jwt-token", query="What is AI governance?", request_type="chat"
)
print(response.data)
asyncio.run(main())
Sync Usage
from axonflow import AxonFlow
with AxonFlow.sync(
endpoint="https://your-agent.axonflow.com",
client_id="your-client-id",
client_secret="your-client-secret",
) as client:
response = client.proxy_llm_call(
user_token="user-jwt-token", query="What is AI governance?", request_type="chat"
)
print(response.data)
Features
Gateway Mode
For lowest-latency LLM calls with full governance and audit compliance:
from axonflow import AxonFlow, TokenUsage
async with AxonFlow(...) as client:
# 1. Pre-check: Get policy approval
ctx = await client.get_policy_approved_context(
user_token="user-jwt", query="Find patient records", data_sources=["postgres"]
)
if not ctx.approved:
raise Exception(f"Blocked: {ctx.block_reason}")
# 2. Make LLM call directly (your code)
llm_response = await openai.chat.completions.create(
model="gpt-4", messages=[{"role": "user", "content": str(ctx.approved_data)}]
)
# 3. Audit the call
await client.audit_llm_call(
context_id=ctx.context_id,
response_summary=llm_response.choices[0].message.content[:100],
provider="openai",
model="gpt-4",
token_usage=TokenUsage(
prompt_tokens=llm_response.usage.prompt_tokens,
completion_tokens=llm_response.usage.completion_tokens,
total_tokens=llm_response.usage.total_tokens,
),
latency_ms=250,
)
OpenAI Integration
Transparent governance for existing OpenAI code:
from openai import OpenAI
from axonflow import AxonFlow
from axonflow.interceptors.openai import wrap_openai_client
openai = OpenAI()
axonflow = AxonFlow(...)
# Wrap client - governance is now automatic
wrapped = wrap_openai_client(openai, axonflow, user_token="user-123")
# Use as normal
response = wrapped.chat.completions.create(
model="gpt-4", messages=[{"role": "user", "content": "Hello!"}]
)
MCP Connectors
Query data through MCP connectors:
# List available connectors
connectors = await client.list_connectors()
# Query a connector
result = await client.query_connector(
user_token="user-jwt",
connector_name="postgres",
operation="query",
params={"sql": "SELECT * FROM users LIMIT 10"},
)
MCP Policy Features (v3.2.0)
Exfiltration Detection - Prevent large-scale data extraction:
# Query with exfiltration limits (default: 10K rows, 10MB)
result = await client.query_connector(
user_token="user-jwt",
connector_name="postgres",
operation="query",
params={"sql": "SELECT * FROM customers"},
)
# Check exfiltration info
if result.policy_info.exfiltration_check.exceeded:
print(f"Limit exceeded: {result.policy_info.exfiltration_check.limit_type}")
# Configure: MCP_MAX_ROWS_PER_QUERY=1000, MCP_MAX_BYTES_PER_QUERY=5242880
Dynamic Policy Evaluation - Orchestrator-based rate limiting, budget controls:
# Response includes dynamic policy info when enabled
if result.policy_info.dynamic_policy_info.orchestrator_reachable:
print(f"Policies evaluated: {result.policy_info.dynamic_policy_info.policies_evaluated}")
for policy in result.policy_info.dynamic_policy_info.matched_policies:
print(f" {policy.policy_name}: {policy.action}")
# Enable: MCP_DYNAMIC_POLICIES_ENABLED=true
Multi-Agent Planning
Generate and execute multi-agent plans:
# Generate a plan
plan = await client.generate_plan(
query="Book a flight and hotel for my trip to Paris", domain="travel"
)
print(f"Plan has {len(plan.steps)} steps")
# Execute the plan
result = await client.execute_plan(plan.plan_id)
print(f"Result: {result.result}")
AuthZEN-native authorization
client.evaluate asks the gateway an AuthZEN question - may this subject perform this action on this resource? - over POST /api/v1/access/evaluation. It is the surface to write new integrations against: at v11 the engine behind it becomes AxonFlow's new Policy Decision Point with no wire change, so an integration written here migrates once rather than twice. Nothing is deprecated by it today; client.decide and the gateway/proxy methods are wire-stable through all of v11.
from axonflow import (
AuthZENAction,
AuthZENRequest,
AuthZENResource,
AuthZENSubject,
AuthZENRefusal,
)
decision = await client.evaluate(
AuthZENRequest(
subject=AuthZENSubject(type="gateway", id="llm-gateway-01"),
action=AuthZENAction(name="llm.completion"),
resource=AuthZENResource(type="llm", id="llm"),
context={"args": {"query": user_prompt}},
)
)
if not decision.allowed:
raise RuntimeError(f"blocked: {decision.state} ({decision.reason})")
for obligation in decision.mandatory_obligations:
... # an allow you cannot discharge is not an allow
Several preconditions of one operation go in a bulk envelope, which returns one decision - a denied entry denies the operation, so a caller cannot act on the entry it liked:
from axonflow import AuthZENBulk
decision = await client.evaluate_all(
AuthZENBulk(
subject=AuthZENSubject(type="gateway", id="llm-gateway-01"),
action=AuthZENAction(name="tool.call"),
context={"args": {"query": user_prompt}},
evaluations=[
AuthZENRequest(resource=AuthZENResource(type="tool", id="jira/move_issue")),
AuthZENRequest(resource=AuthZENResource(type="tool", id="jira/update_project")),
],
)
)
Known gotchas
A refusal is not a denial. This surface refuses anything it cannot evaluate rather than evaluating around it - send a subject property or an unrecognised context member and you get an AuthZENRefusal naming the exact member, not a decision computed without it. Treating every error as a deny fails closed, which is safe, but blocks traffic that would be allowed once the request is corrected.
try:
decision = await client.evaluate(request)
except AuthZENRefusal as refusal:
refusal.code # e.g. "unevaluable_attribute" - a closed, generated set
refusal.pointer # "/evaluation/subject/properties" - the member to fix
refusal.refused_by # "client" (this SDK) or "gateway"
refusal.retryable # only a gateway dependency failure is
AuthZENProtocolError is separate and means something else: the gateway answered 200 with a body this build cannot safely act on - no profile context, a profile it cannot read, or a decision boolean that disagrees with its operational state. It is always fail-closed, and the fix is an upgrade or an operator, not a corrected request. Read .kind to tell those apart without matching on the message: unsupported_profile and unknown_operational_state mean upgrade the SDK, while missing_profile_context, decision_state_disagreement, obligations_on_refusal and undecodable_body mean go and look at the deployment. A 401 surfaces as the SDK's ordinary AuthenticationError, because the gateway answers authentication before this route runs.
decision.allowed, never decision.decision. The bare boolean is AuthZEN 1.0's collapsed rendering; allowed additionally requires the operational state to be ALLOW, so a CHALLENGE or an ERROR can never be read as permission.
Three states, not two. None cannot express the difference between "the source established there is no value" and "the source could not be reached", and collapsing them is how an attribute nobody resolved gets recorded as one that was weighed. Attributes inside the context and properties bags may be explicit:
from axonflow import AuthZENAttribute, AUTHZEN_UNKNOWN_RESOLUTION_FAILED
context = {
"args": {"query": user_prompt},
"correlation": {
"session_id": AuthZENAttribute.absent(), # a fact: omitted, request sent
"trace_id": AuthZENAttribute.unknown( # not a fact: refused locally,
AUTHZEN_UNKNOWN_RESOLUTION_FAILED # nothing is sent
),
},
}
The tri-state applies to attribute data, not to the structural members (subject.id, action.name, …): those are the identity of the question being asked, and an identity you cannot resolve is not an attribute whose absence a policy could evaluate - there is no request to make.
Today's mapping is deliberately narrow. subject.type must be "gateway" (an end-user subject needs the identity plane, which activates at v11); an llm or agent resource id must be the stage name itself, not a provider/model pair, because nothing on the serving path reads a provider or a model; a tool resource id is "server/tool", because both halves ARE read. Everything else is refused by name.
The wire types are generated from the platform's canonical contract artifact (scripts/gen_authzen_types.py); CI fails if the committed module is not what the artifact produces. Runnable example: examples/authzen_evaluation.py. Migration notes: docs/AUTHZEN_MIGRATION_DRAFT.md.
v11.0.0 platform
Against a v11.0.0 platform this SDK reaches the new decision plane. Against an older platform the calls that existed before work as before, and each v11 field is None. What each part needs from the platform: