Skip to main content

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 auth              # log in via device code (no password)
# then: open the dashboard, go to Workspace → API Keys, and create one
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 registration — POST /api/v1/agents (once at startup).
  • Policy fetch — GET /api/v1/policies (on first evaluation, then every KV_POLICY_TTL_SECONDS; handled by kyvvu-engine).
  • Log flush — POST to the configured log endpoint (on end_task(); handled by kyvvu-engine, off by default).
  • Incident webhook — POST 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 handler — KyvvuLangChainHandler (shared, works for both) and KyvvuLangGraphHandler (adds node metadata).
  3. CrewAI listener — KyvvuCrewAIListener, 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

All three 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.17.0)
│   ├── 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              # auth (device-code 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/                       # 625 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 auto WHERE logs go: URL, file path, stdout, none, or auto — the platform when it is the policy source, else stdout (#357).
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 auth                  # log in via device code (no password)
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]"

# Or, from the repo root, with uv -- one command, no engine-first ordering:
uv sync --all-packages --all-extras

# Run all tests (625 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, get_current_task_id, setup_logging

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

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

TASK_BOUNDARY_STEP_TYPES is the frozen set of the four step types that mark task boundaries (task.start, task.end, task.error, task.idle) — use it to tell them apart from the eight steps that describe what an agent does inside a task. Behavior is constructed from step_type and rejects unknown kwargs.

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.

Release files for kyvvu 0.21.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kyvvu 0.21.1
File Size Uploaded
kyvvu-0.21.1.tar.gz 187.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for kyvvu 0.21.1
File Interpreter ABI Platform
kyvvu-0.21.1-py3-none-any.whl Python 3 none any Details

Total release size: 318.3 kB

Release files / kyvvu-0.21.1.tar.gz

Download URL kyvvu-0.21.1.tar.gz
Size 187.3 kB
Tags Source
SHA-256 checksum
How to use checksums
31afe369ad5e65d075fa3bb43de10c93aba4d505266226c253ce66eda4bf4892
BLAKE2b-256 checksum
How to use checksums
7e088304961476d9da8a4f711a962c445dafc874b299c13beab995d2bb4f4ed9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / kyvvu-0.21.1-py3-none-any.whl

Download URL kyvvu-0.21.1-py3-none-any.whl
Size 131.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d0c0c50509c1bca5dab21fddb268f7b7fad97f6c07c6e8458993408875391ea4
BLAKE2b-256 checksum
How to use checksums
6823dbd02da87246468ca3e15e73b4bc3b46c093ecfb74658a8eac4afa6a4ffb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release history Release notifications | RSS feed

This release

0.21.1 This release

2 release files

0.21.0

2 release files

0.20.0

2 release files

0.19.0

2 release files

0.18.2

2 release files

0.18.1

2 release files

0.18.0

2 release files

0.17.0

2 release files

0.16.0

2 release files

0.15.1

2 release files

0.15.0

2 release files

0.14.1

2 release files

0.13.7

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page