Skip to main content

Python SDK for AI compliance monitoring and policy enforcement under the EU AI Act

Project description

Kyvvu SDK

The Agent Security Kernel (ASK) for Python agents. Enforce security and safety policies on every agent action before it runs — stopping data leakage and destructive actions — with EU AI Act, OWASP, and GDPR compliance as a bonus.

Get started in 2 minutes

pip install kyvvu
kyvvu register          # create account + API key
kyvvu init my-agent     # scaffold a demo agent
cd my-agent && python agent.py

The demo agent runs three steps: an LLM call, a data fetch, and a code execution. The third step is blocked by the OWASP security policy — showing runtime enforcement in action.

Free tier: 1,000 active agent-hours/month at no cost. See https://kyvvu.com/pricing for details.

Docs: https://docs.kyvvu.com · Issues: https://github.com/Kyvvu/issues · License: Apache 2.0 (SDK), BSL 1.1 (engine)


What the SDK does

  1. Registers your agent with the Kyvvu API (POST /api/v1/agents) on startup. This is a real HTTP call that acquires an agent_id and evaluates agent-registration policies.
  2. Evaluates every step your agent takes against loaded policies before execution. Policies are fetched from the API and cached (this is done by kyvvu-engine, which is included as a dependency).
  3. Records completed steps into an in-memory per-task history so that path-dependent policies (predecessors, sequences, rate limits) work.
  4. Flushes the audit trail to the Kyvvu API on task completion.

The SDK makes HTTP calls at two points:

  • Agent registrationPOST /api/v1/agents (once at startup).
  • Policy fetchGET /api/v1/policies (on first evaluation, then every KV_POLICY_TTL_SECONDS; handled by kyvvu-engine).
  • Log flushPOST to the configured log endpoint (on end_task(); handled by kyvvu-engine, off by default).
  • Incident webhookPOST to the configured incident endpoint (on policy violation; handled by kyvvu-engine, off by default).

Quickstart

from kyvvu import Kyvvu, StepType, Verb

kv = Kyvvu(api_key="KvKey-...", agent_key="my-bot")
kv.register_agent(name="My Bot", purpose="Customer support")

task_id = kv.start_task()

@kv.step(StepType.step_model, Verb.POST)
def chat(prompt: str) -> str:
    return llm.complete(prompt)

result = chat("Hello")
kv.end_task()

Bring-your-own identity

# If agent_id is provisioned externally (Terraform, config file, admin console):
kv = Kyvvu(api_key="KvKey-...", agent_key="my-bot", agent_id="ag_abc123")
# No register_agent() call needed — start using @kv.step immediately.

Task lifecycle (programmatic API)

task_id = kv.start_task()
try:
    result = my_agent_function()
except Exception as e:
    kv.error_task(error=e)
    raise
else:
    kv.end_task()

All three methods accept optional context=, properties=, and meta= kwargs for template matching and caller overrides.


Integration modes

The SDK supports three integration patterns. All produce the same stream of Behavior objects; they differ in how agent actions are captured:

  1. Decorator (@kv.step) — for custom Python agents.
  2. LangChain / LangGraph callback handlerKyvvuLangChainHandler (shared, works for both) and KyvvuLangGraphHandler (adds node metadata).
  3. CrewAI listenerKyvvuCrewAIListener, wired to the CrewAI event bus.

1. Decorator integration (@kv.step)

For custom Python agents. Wrap each function with @kv.step(step_type, verb). The decorator handles evaluate → execute → record automatically.

from kyvvu import Kyvvu, StepType, Verb, RiskClassification

kv = Kyvvu(
    api_key="KvKey-...",
    agent_key="gmail-assistant",
    risk_classification=RiskClassification.HIGH,
)
kv.register_agent(name="Gmail Assistant")

class GmailAgent:
    @kv.step(StepType.task_start)
    def fetch_email(self):
        return self._read_inbox()

    @kv.step(StepType.step_model, Verb.POST,
             properties={"model": {"name": "gpt-4o"}})
    def generate_reply(self, email):
        return llm.complete(email["body"])

    @kv.step(StepType.task_end)
    def finish(self):
        pass  # flushes audit log

See examples/custom-agent/gmail-agent/agent.py for a full working example.

2. LangChain / LangGraph callback handler

For LangChain-based agents. Construct a Kyvvu instance, register the agent, then pass a KyvvuLangChainHandler as a callback. LLM calls, tool invocations, and agent decisions are captured automatically.

from kyvvu import Kyvvu
from kyvvu.schemas import Environment, RiskClassification
from kyvvu.integrations.langchain import KyvvuLangChainHandler

kv = Kyvvu(
    api_key="KvKey-...",
    agent_key="finance-agent",
    environment=Environment.DEVELOPMENT,
    risk_classification=RiskClassification.LIMITED,
)
kv.register_agent(
    name="Finance Agent",
    purpose="Stock ticker lookup",
    metadata={"framework": "langchain", "tools": ["search"]},
)

handler = KyvvuLangChainHandler(kv)
result = agent.invoke(query, config={"callbacks": [handler]})

The handler is a pure adapter — it does not manage identity or registration. Same Kyvvu() + register_agent() pattern as the decorator integration.

See examples/langchain-agent/finance-agent/agent.py for a full working example.

For LangGraph, the shared KyvvuLangChainHandler works (LangGraph runs on langchain_core callbacks); pass it via config={"callbacks": [handler]}. Use KyvvuLangGraphHandler (kyvvu.integrations.langgraph) to additionally capture node metadata (langgraph.node_name) and map GraphInterrupt to step.gate.

3. CrewAI listener

For CrewAI crews. KyvvuCrewAIListener (kyvvu.integrations.crewai) attaches to the CrewAI event bus to capture agent steps, tool calls (with parallel-call pairing), and crew output. Because the event bus swallows exceptions, blocks are surfaced via listener.is_blocked / listener.blocked_reason (circuit breaker) rather than a raised exception at the call site.

Behaviour templates

Both integrations use YAML templates to map framework events to the v0.05 atomic behaviour vocabulary (step.model, step.resource, task.start, etc.). The template engine lives in kyvvu_engine.templates; the SDK ships templates for its adapters and loads them by name:

from kyvvu.templates import load                  # SDK-bundled templates
from kyvvu_engine.templates import BehaviorTemplate  # engine: the template engine

dec = load("decorator")
lc  = load("langchain")

# Custom template from file
custom = BehaviorTemplate.from_path("/path/to/template.yaml")
kv = Kyvvu(api_key="...", agent_key="bot", template=custom)

Or set KV_TEMPLATE_LOCATION to a YAML file path.

Async support

The @kv.step decorator automatically detects async def functions and wraps them correctly:

@kv.step(StepType.step_model, Verb.POST)
async def chat(prompt: str) -> str:
    return await openai_client.chat.completions.create(
        model="gpt-4o", messages=[{"role": "user", "content": prompt}]
    )

Policy evaluation and recording are synchronous (sub-millisecond, in-process) — only the decorated function call is awaited. Error handling, blocked-step propagation, and task lifecycle all work identically to sync functions.


Project structure

kyvvu-sdk/
├── kyvvu/
│   ├── __init__.py              # Public API surface (__all__)
│   ├── __version__.py           # Version string (0.14.1)
│   ├── core.py                  # Kyvvu class — registration, task API, runner
│   ├── schemas.py               # Enums, Behavior, EvalContext (re-exports from engine)
│   ├── exceptions.py            # Exception hierarchy + KyvvuBlockedError
│   ├── logging.py               # setup_logging re-export from engine
│   ├── _task_context.py         # ContextVar for active task_id
│   ├── _limits.py               # Truncation constants for input/output capture
│   ├── templates/               # SDK-bundled template YAMLs (the engine hosts the loader)
│   │   ├── __init__.py          # load(name) — load a bundled template by name
│   │   ├── decorator.template.yaml
│   │   ├── langchain.template.yaml
│   │   ├── langgraph.template.yaml
│   │   ├── crewai.template.yaml
│   │   └── patterns/            # reusable rule-fragment templates (reference)
│   ├── integrations/
│   │   ├── __init__.py          # FrameworkAdapter export
│   │   ├── _base.py             # FrameworkAdapter base class
│   │   ├── decorator.py         # @kv.step implementation
│   │   ├── langchain.py         # KyvvuLangChainHandler (LangChain + LangGraph)
│   │   ├── langgraph.py         # KyvvuLangGraphHandler (node metadata)
│   │   └── crewai.py            # KyvvuCrewAIListener
│   └── cli/
│       ├── main.py              # Typer app (kyvvu command)
│       ├── auth.py              # register, login, logout, whoami
│       ├── agents.py            # list-agents
│       ├── policies.py          # list-policies
│       ├── manifests.py         # list-manifests, assign-manifest, list-assignments, unassign-manifest
│       ├── config.py            # config management
│       ├── init_cmd.py          # kyvvu init (scaffold project)
│       ├── serve.py             # kyvvu serve (local engine server)
│       └── client.py            # HTTP client for CLI commands
├── tests/                       # 606 tests
│   ├── conftest.py
│   ├── test_decorator*.py       # Decorator integration tests
│   ├── test_programmatic_task_api.py
│   ├── test_identity_acquisition.py
│   ├── test_register_agent_side_effects.py
│   ├── templates/               # Template matching/loading tests
│   ├── integrations/
│   │   ├── langchain/           # 10 LangChain handler test files
│   │   └── test_framework_adapter_base.py
│   └── cli/                     # CLI command tests
├── pyproject.toml
├── pytest.ini
└── .env.example

Configuration

The Kyvvu constructor accepts explicit kwargs or reads from environment variables. Precedence: kwargs > env vars > .env in cwd > defaults.

Parameter Env var Default Purpose
api_url KV_API_URL https://platform.kyvvu.com Kyvvu API base URL
api_key KV_API_KEY Bearer API key (KvKey-...)
agent_key KV_AGENT_KEY Stable agent identifier for policy fetch
agent_id Pre-provisioned agent ID (skips registration)
environment KV_ENVIRONMENT development Deployment environment
risk_classification minimal EU AI Act risk tier
template KV_TEMPLATE_LOCATION built-in Path to YAML template
timeout 10 HTTP timeout (seconds)
log_location KV_LOG_LOCATION stdout WHERE logs go: URL, file path, stdout, none.
log_format KV_LOG_FORMAT kv HOW logs are formatted: kv, json, or otlp.

For the complete environment-variable reference (engine-level settings such as KV_POLICY_TTL_SECONDS, resilience options, etc.), see the Configuration Reference.


CLI

The SDK includes a CLI (kyvvu command) for development and debugging:

kyvvu --version
kyvvu register              # create account + API key
kyvvu login                 # log in, get JWT
kyvvu logout                # clear session
kyvvu whoami                # show current user

kyvvu list-agents           # list registered agents
kyvvu list-policies         # list policies (--agent-id for per-agent)
kyvvu list-manifests        # list manifests from connected repos
kyvvu assign-manifest       # assign manifest to agent
kyvvu unassign-manifest     # remove assignment
kyvvu list-assignments      # list current assignments

kyvvu init my-agent         # scaffold a new agent project
kyvvu serve                 # start local policy evaluation server

Install CLI dependencies (included by default): typer, rich, httpx.


Development

# Install in editable mode (from monorepo root)
pip install -e ./kyvvu-engine && pip install -e "./kyvvu-sdk[dev,langchain]"

# Run all tests (606 tests)
cd kyvvu-sdk
python -m pytest tests/ -v

# Type checking
mypy --strict kyvvu/

# Linting
ruff check kyvvu/ tests/

Public API surface

The following symbols are the public API (kyvvu.__all__):

Core: Kyvvu, enrich, setup_logging

Exceptions: KyvvuError, KyvvuAPIError, KyvvuBlockedError, KyvvuConfigError, KyvvuKeyRevokedError, KyvvuRateLimitError, KyvvuTimeoutError, KyvvuValidationError

Vocabulary: StepType, Verb, Scope, Behavior, EvalContext, EvalResult, PolicyResult, Action

Agent registration: Environment, RiskClassification

Submodule exports (importable from submodules):

  • kyvvu.templates.load — load an SDK-bundled template by name (the template engine BehaviorTemplate / deep_merge / load_template live in kyvvu_engine.templates)
  • kyvvu.integrations.FrameworkAdapter
  • kyvvu.integrations.langchain.KyvvuLangChainHandler

Releasing

  1. Edit VERSIONS at the repo root.
  2. Run ./scripts/bump-version.sh.
  3. Merge to main.
  4. Tag: git tag sdk-v0.x.y && git push origin sdk-v0.x.y.

Licence

The Kyvvu SDK is licensed under the Apache License 2.0. See LICENSE in this directory.

Important: The SDK depends on kyvvu-engine at runtime, which is separately licensed under the Business Source License 1.1 (BSL 1.1). The SDK's permissive license does not extend to the engine. Bundling, vendoring, or depending on the SDK does not grant rights to the engine beyond what BSL 1.1 permits. See kyvvu-engine/LICENSE for the engine's terms.

Production use of the engine requires a Kyvvu commercial subscription or license agreement: licensing@kyvvu.com

By using Kyvvu you agree to the Terms of Service, Privacy Policy, and Acceptable Use Policy.

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

kyvvu-0.16.0.tar.gz (92.6 kB view details)

Uploaded Source

Built Distribution

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

kyvvu-0.16.0-py3-none-any.whl (76.6 kB view details)

Uploaded Python 3

File details

Details for the file kyvvu-0.16.0.tar.gz.

File metadata

  • Download URL: kyvvu-0.16.0.tar.gz
  • Upload date:
  • Size: 92.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for kyvvu-0.16.0.tar.gz
Algorithm Hash digest
SHA256 12ea80316a02d4590f4d16ee391c9fcf0a43605f2ad5bfcf81e7667a512df13c
MD5 8d42e7ce27c20ba44bbd229ed3d8529d
BLAKE2b-256 d8340c8d46dca042d4ec93078b40f44627ac534875ee90725362262531676cdb

See more details on using hashes here.

File details

Details for the file kyvvu-0.16.0-py3-none-any.whl.

File metadata

  • Download URL: kyvvu-0.16.0-py3-none-any.whl
  • Upload date:
  • Size: 76.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for kyvvu-0.16.0-py3-none-any.whl
Algorithm Hash digest
SHA256 356db285bb9e92e0f165f0afbb224db095faa11e26615c441aecfe5d714a4ee5
MD5 ba58425d66ad03f39a3dd19f662f3035
BLAKE2b-256 1fb8d3d6a460a627f798ddf23825aba6ef7f494b74c5adb6ed5871bea82f4af0

See more details on using hashes here.

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