kovernance 0.1.0
Python SDK for Kovernance AI Agent Governance Platform
Requires Python: >=3.9
Keywords: agents, ai, audit, compliance, governance, observability

# Kovernance SDK for Python

[![PyPI version](https://badge.fury.io/py/kovernance.svg)](https://badge.fury.io/py/kovernance)
[![Python versions](https://img.shields.io/pypi/pyversions/kovernance.svg)](https://pypi.org/project/kovernance/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

The official Python SDK for [Kovernance](https://kovernance.io) - the AI Agent Governance Platform.

Track, audit, and govern your AI agents with ease. Kovernance provides observability, compliance, and risk management for AI systems.

## Installation

```bash
pip install kovernance
```

## Quick Start

```python
from kovernance import KovernanceClient, trace, span

# Initialize the client
kov = KovernanceClient(
    api_key="kov_your_api_key",
    agent_id="my-ai-agent",
)

# Option 1: Log events manually
kov.log_event(
    event_type="decision",
    action="approve_request",
    input_data={"request_id": "req-123"},
    output={"approved": True, "reason": "All criteria met"},
    metadata={"user_id": "user-456"},
)

# Option 2: Use the @trace decorator for automatic function tracing
@trace(kov)
def process_customer_request(request: dict) -> dict:
    # Your logic here
    return {"status": "processed"}

# Option 3: Use span for block-level tracing
with span(kov, "database_query") as s:
    results = db.query("SELECT * FROM users")
    s.set_output({"rows_returned": len(results)})
```

## Features

### Manual Event Logging

Log any event with full control over the data:

```python
kov.log_event(
    event_type="llm_call",          # Type of event
    action="generate_response",      # Specific action
    input_data={"prompt": "..."},    # Input data
    output={"response": "..."},      # Output/result
    metadata={"model": "gpt-4"},     # Additional metadata
    session_id="session-123",        # Group related events
    parent_event_id="evt-parent",    # Link to parent event
)
```

### Batch Ingestion

Send multiple events efficiently:

```python
events = [
    {"event_type": "step", "action": "start", "metadata": {"step": 1}},
    {"event_type": "step", "action": "process", "metadata": {"step": 2}},
    {"event_type": "step", "action": "complete", "metadata": {"step": 3}},
]

kov.batch_ingest(events)
```

### Function Tracing with @trace

Automatically trace function calls:

```python
@trace(kov, event_type="tool_call", name="web_search")
def search_web(query: str) -> list:
    # Function is automatically traced
    # Captures: arguments, return value, duration, errors
    return perform_search(query)
```

Options:
- `event_type`: Custom event type (default: "function_call")
- `name`: Custom function name for logging
- `capture_args`: Whether to capture arguments (default: True)
- `capture_result`: Whether to capture return value (default: True)
- `capture_exceptions`: Whether to capture exceptions (default: True)

### Block Tracing with span

Trace arbitrary code blocks:

```python
with span(kov, "external_api_call", metadata={"api": "weather"}) as s:
    response = requests.get("https://api.weather.com/...")
    s.set_output({"status_code": response.status_code})
    s.add_metadata("response_time_ms", response.elapsed.total_seconds() * 1000)
```

### Async Support

Full async/await support:

```python
from kovernance import AsyncKovernanceClient, async_span

async with AsyncKovernanceClient(api_key="...", agent_id="...") as kov:
    await kov.log_event(event_type="async_op", action="start")

    async with async_span(kov, "async_operation") as s:
        result = await some_async_function()
        s.set_output({"result": result})
```

## Framework Integrations

### CrewAI

```python
from crewai import Agent, Crew, Task
from kovernance import KovernanceClient, trace

kov = KovernanceClient(api_key="...", agent_id="research-crew")

@trace(kov, event_type="crew_execution")
def run_research_crew(topic: str):
    crew = Crew(agents=[...], tasks=[...])
    return crew.kickoff()
```

See [examples/crewai](examples/crewai/) for more details.

### LangGraph

```python
from langgraph.graph import StateGraph
from kovernance import KovernanceClient, trace

kov = KovernanceClient(api_key="...", agent_id="support-agent")

@trace(kov, event_type="node_execution")
def classify_intent(state):
    # Node logic
    return state
```

See [examples/langgraph](examples/langgraph/) for more details.

## Configuration

### Environment Variables

```bash
export KOVERNANCE_API_KEY="kov_your_api_key"
export KOVERNANCE_BASE_URL="https://api.kovernance.io"  # Optional
```

### Client Options

```python
kov = KovernanceClient(
    api_key="kov_xxx",                    # Required: API key
    agent_id="my-agent",                  # Required: Agent identifier
    base_url="https://api.kovernance.io", # Optional: API base URL
    timeout=30.0,                         # Optional: Request timeout
    organization_id="org-123",            # Optional: Multi-tenant org ID
)
```

## Error Handling

```python
from kovernance import (
    KovernanceError,      # Base exception
    ConfigurationError,   # Invalid configuration
    AuthenticationError,  # Auth failures (401)
    APIError,            # General API errors
    ValidationError,     # Input validation errors
    RateLimitError,      # Rate limit exceeded (429)
)

try:
    kov.log_event(event_type="test", action="test")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except APIError as e:
    print(f"API error: {e.status_code} - {e.response_body}")
```

## Development

### Local Setup

```bash
# Clone the repository
git clone https://github.com/kovernance/kovernance-sdk-python.git
cd kovernance-sdk-python

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Run linting
ruff check src tests
mypy src
```

### Testing Against Local Backend

```python
kov = KovernanceClient(
    api_key="your-local-key",
    agent_id="test-agent",
    base_url="http://localhost:8000",  # Local Kovernance backend
)
```

## License

MIT License - see [LICENSE](LICENSE) for details.

## Links

- [Documentation](https://docs.kovernance.io/sdk/python)
- [Kovernance Platform](https://kovernance.io)
- [GitHub Issues](https://github.com/kovernance/kovernance-sdk-python/issues)
- [Changelog](CHANGELOG.md)