Skip to main content

Python SDK for the Kakunin AI agent compliance API

Project description

kakunin

Python SDK for the Kakunin AI agent compliance API. Issues X.509 certificates to AI agents, monitors behavioral baselines, and enforces scope limits at the tool layer.

pip install kakunin

Requires Python 3.9+.


Quick Start

import asyncio
from kakunin import Kakunin

async def main():
    async with Kakunin(api_key="kak_live_...") as client:
        # Register an agent
        agent = await client.agents.create(
            name="TradeBot-1",
            model="gpt-4o",
            version="2024-11",
        )

        # Record a behavioral event — returns risk_band
        event = await client.events.create(
            agent_id=agent.id,
            action_type="transaction_initiated",
            details={"amount_usd": 50000, "venue": "NYSE"},
        )
        print(event.risk_band)  # "low" | "medium" | "high"

asyncio.run(main())

verify_agent_scope Decorator

Wrap any function (sync or async) to verify that the agent is active and holds required scopes before execution. Raises ScopeViolationError on failure — never swallows it.

from kakunin import Kakunin, verify_agent_scope

client = Kakunin(api_key="kak_live_...")

@verify_agent_scope(client, agent_id="agt-123", required_scopes=["trade.execute"])
async def execute_trade(order: dict) -> dict:
    # Only runs if agent agt-123 is active and has trade.execute scope
    return await broker.submit(order)

# Also works on sync functions
@verify_agent_scope(client, agent_id="agt-123", required_scopes=["data.read"])
def fetch_prices(symbol: str) -> list[float]:
    return market_data.get(symbol)

LangChain Integration

Option A — KakuninToolGuard (per-tool scope enforcement)

Wraps any LangChain tool. Scope is verified before every _run / _arun call.

from langchain_core.tools import tool
from kakunin import Kakunin
from kakunin.integrations.langchain import KakuninToolGuard

client = Kakunin(api_key="kak_live_...")

@tool
def execute_trade(order: str) -> str:
    """Execute a trade order on the exchange."""
    return broker.submit(order)

# Wrap the tool — drop into any LangChain agent as-is
guarded_trade = KakuninToolGuard(
    kakunin=client,
    agent_id="agt-123",
    tool=execute_trade,
    required_scopes=["trade.execute"],
)

from langchain.agents import create_react_agent
agent = create_react_agent(llm, tools=[guarded_trade], prompt=prompt)

Option B — verify_agent_scope on tool functions

from langchain_core.tools import tool
from kakunin import Kakunin, verify_agent_scope

client = Kakunin(api_key="kak_live_...")

@tool
@verify_agent_scope(client, agent_id="agt-123", required_scopes=["trade.execute"])
async def execute_trade(order: str) -> str:
    """Execute a trade order."""
    return await broker.submit(order)

Option C — Chain-level guard via callback

Guards an entire LangChain chain, not individual tools.

from kakunin.integrations.langchain import langchain_scope_callback

guard = langchain_scope_callback(
    client, agent_id="agt-123", required_scopes=["trade.execute"]
)
chain = my_chain.with_config(callbacks=[guard])

AutoGen Integration

KakuninConversableAgent subclasses AutoGen's ConversableAgent. It emits behavioral events for every message and verifies scope before each reply.

from autogen import UserProxyAgent
from kakunin import Kakunin
from kakunin.integrations.autogen import KakuninConversableAgent

client = Kakunin(api_key="kak_live_...")

risk_agent = KakuninConversableAgent(
    kakunin=client,
    agent_id="agt-456",
    required_scopes=["risk.assess"],   # verified before every generate_reply()
    # Standard AutoGen kwargs:
    name="RiskEngine",
    system_message="You are a risk analyst. Assess the given trade for regulatory risk.",
    llm_config={"model": "gpt-4o"},
)

user_proxy = UserProxyAgent(name="User", human_input_mode="NEVER")
user_proxy.initiate_chat(risk_agent, message="Assess trade T-984231")

To attach the agent's certificate serial to outbound HTTP calls:

from kakunin.integrations.autogen import KakuninConversableAgent, KakuninHttpxMixin

class MyAgent(KakuninHttpxMixin, KakuninConversableAgent):
    pass

agent = MyAgent(
    kakunin=client,
    agent_id="agt-456",
    cert_serial="3A:F2:...",
    name="RiskEngine",
    llm_config={"model": "gpt-4o"},
)

# Outbound requests carry X-Kakunin-Cert-Serial automatically
resp = await agent.http_client.get("https://internal-service/prices")

Other Framework Integrations

Framework Import What it does
LangGraph kakunin.integrations.langgraph.kakunin_node Decorator: emits behavioral event on every node execution
LlamaIndex kakunin.integrations.llamaindex.KakuninFunctionToolGuard Wraps FunctionTool with scope check
CrewAI kakunin.integrations.crewai.KakuninCrewAgent Agent subclass with event emission + scope guard
CAMEL-AI kakunin.integrations.camel.KakuninToolkit 4 FunctionTools (verify status, check scope, risk score, emit event)

Error Handling

from kakunin import ScopeViolationError, RateLimitError, AuthenticationError

try:
    result = await guarded_function()
except ScopeViolationError as e:
    # Agent is suspended, retired, or missing a required scope
    print(f"Scope check failed: {e.missing_scopes}")
    # Do NOT proceed — the agent is not authorised
except RateLimitError:
    await asyncio.sleep(1)
    # Retry
except AuthenticationError:
    # Invalid API key — check KAKUNIN_API_KEY env var
    raise

Full docs at kakunin.ai/docs.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

kakunin-0.2.0.tar.gz (30.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kakunin-0.2.0-py3-none-any.whl (33.6 kB view details)

Uploaded Python 3

File details

Details for the file kakunin-0.2.0.tar.gz.

File metadata

  • Download URL: kakunin-0.2.0.tar.gz
  • Upload date:
  • Size: 30.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for kakunin-0.2.0.tar.gz
Algorithm Hash digest
SHA256 3ed5856727ccb8f741260cb06ef7d8ee280ea3b6caf85872764ee837f0f06800
MD5 4303392dc67a65f205c781b7916eb24f
BLAKE2b-256 fcc9bebec5e12ab316e87904c2d1575602fcb52174363ca103e70d28d8b94e5f

See more details on using hashes here.

Provenance

The following attestation bundles were made for kakunin-0.2.0.tar.gz:

Publisher: publish.yml on nqzai/kakunin-sdk-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file kakunin-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: kakunin-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 33.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for kakunin-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c0bcd1f4e42450f1d35ed80c084c2fa470ea06328b7b35010e596bbaee04c9ce
MD5 2a9371af7b2cc98678c2d9a920511db4
BLAKE2b-256 32416f1a0fc26923d557748da79c034493e0f939686e3e1707f2f4acdcf44c6c

See more details on using hashes here.

Provenance

The following attestation bundles were made for kakunin-0.2.0-py3-none-any.whl:

Publisher: publish.yml on nqzai/kakunin-sdk-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page