Metadata-Version: 2.4
Name: kyvvu
Version: 0.16.0
Summary: Python SDK for AI compliance monitoring and policy enforcement under the EU AI Act
Author-email: "Kyvvu B.V." <info@kyvvu.com>
License: Copyright 2026 Kyvvu B.V.
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
        http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
        
        This license applies only to the contents of the kyvvu-sdk/ directory
        of the Kyvvu monorepo. Other directories in this monorepo are governed
        by their own LICENSE files.
Project-URL: Homepage, https://github.com/kyvvu/platform
Keywords: ai,compliance,eu-ai-act,monitoring,logging,policy-enforcement
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: kyvvu-engine<1.0.0,>=0.6.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: typer>=0.12
Requires-Dist: rich>=13
Requires-Dist: httpx>=0.27
Requires-Dist: tomli-w>=1.0
Requires-Dist: tomli>=2.0; python_version < "3.11"
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.1.0; extra == "langchain"
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: types-PyYAML>=6.0; extra == "dev"
Dynamic: license-file

# 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

```bash
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 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

```python
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

```python
# 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)

```python
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.

```python
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.

```python
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:

```python
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:

```python
@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](../docs/deployment/configuration.md).

---

## CLI

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

```bash
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

```bash
# 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](https://kyvvu.com/terms-of-service/),
[Privacy Policy](https://kyvvu.com/privacy-policy/), and
[Acceptable Use Policy](https://kyvvu.com/aup/).
