# Authevo Python SDK

Official Python SDK for [Authevo](https://authevo.com) - Cryptographically verifiable agent actions with policy enforcement.

[![PyPI version](https://badge.fury.io/py/authevo.svg)](https://badge.fury.io/py/authevo)
[![Downloads](https://pepy.tech/badge/authevo)](https://pepy.tech/project/authevo)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

## Features

- ✅ **Cryptographic Signatures**: Ed25519 signatures for every action
- ✅ **Policy Enforcement**: OPA integration for runtime policy evaluation
- ✅ **Automatic Retries**: Exponential backoff on transient failures
- ✅ **Idempotency**: Built-in idempotency key generation
- ✅ **Framework Integrations**: LangChain and CrewAI support
- ✅ **Async/Await**: Full async support for high performance
- ✅ **Type Safe**: Comprehensive type hints

## Installation

```bash
pip install authevo
```

### Optional Dependencies

```bash
# LangChain integration
pip install authevo[langchain]

# CrewAI integration
pip install authevo[crewai]

# All integrations
pip install authevo[all]

# Development dependencies
pip install authevo[dev]
```

## Quick Start

```python
import asyncio
from authevo import AuthevoAgent

async def main():
    # Generate a new agent
    async with AuthevoAgent.generate() as agent:
        print(f"Agent DID: {agent.keypair.did}")
        
        # Register with the API
        await agent.register(name="My Agent")
        
        # Execute a verifiable action
        result = await agent.execute_action(
            action="refund",
            payload={"orderId": "123", "amount": 50}
        )
        
        print(f"Action submitted: {result['id']}")
        print(f"Policy decision: {result['policyDecision']['decision']}")

asyncio.run(main())
```

## Configuration

Configure the SDK via environment variables or code:

### Environment Variables

```bash
export AUTHEVO_API_URL="https://api.authevo.com"
export AUTHEVO_API_KEY="authevo_..."
export AUTHEVO_TIMEOUT=30
export AUTHEVO_MAX_RETRIES=3
```

### Programmatic Configuration

```python
from authevo import AuthevoAgent, AuthevoConfig

config = AuthevoConfig(
    api_url="https://api.authevo.com",
    api_key="authevo_...",
    timeout=30,
    max_retries=3
)

agent = AuthevoAgent.generate(config=config)
```

## Framework Integrations

### LangChain

```python
from authevo import AuthevoAgent
from authevo.langchain import VerifiableTool
from langchain.agents import initialize_agent
from langchain.llms import OpenAI

# Create Authevo agent
agent = AuthevoAgent.generate()

# Wrap as LangChain tool
refund_tool = VerifiableTool(
    name="process_refund",
    description="Process customer refund with policy enforcement",
    authevo_agent=agent,
    action="refund"
)

# Use with LangChain
llm = OpenAI(temperature=0)
langchain_agent = initialize_agent(
    tools=[refund_tool],
    llm=llm,
    agent="zero-shot-react-description"
)

result = langchain_agent.run("Process a refund for order-123, amount $50")
```

### CrewAI

```python
from authevo import AuthevoAgent
from authevo.crewai import verifiable_task

agent = AuthevoAgent.generate()

@verifiable_task(agent=agent, action="refund")
def process_refund(order_id: str, amount: float):
    # Your refund logic here
    return {"status": "refunded", "amount": amount}

# Function automatically verifies before execution
result = process_refund("order-456", 75.0)
```

## Error Handling

The SDK provides specific exceptions for different error scenarios:

```python
from authevo import (
    AuthevoAgent,
    PolicyDeniedError,
    AuthenticationError,
    RateLimitError,
    NetworkError
)

async with AuthevoAgent.generate() as agent:
    try:
        result = await agent.execute_action(
            action="refund",
            payload={"orderId": "123", "amount": 500}
        )
    except PolicyDeniedError as e:
        print(f"Action denied by policy: {e.reason}")
        print(f"Policy ID: {e.policy_id}")
    except AuthenticationError:
        print("Invalid API key")
    except RateLimitError as e:
        print(f"Rate limited. Retry after {e.retry_after}s")
    except NetworkError as e:
        print(f"Network error: {e}")
```

## Automatic Retries

The SDK automatically retries on transient failures with exponential backoff:

```python
# Default: 3 retries with 2s base delay
# Attempt 1: immediate
# Attempt 2: wait 2s
# Attempt 3: wait 4s
# Attempt 4: wait 8s

# Customize retry behavior
config = AuthevoConfig(
    api_url="https://api.authevo.com",
    max_retries=5  # Up to 5 retry attempts
)
```

## Examples

See the [`examples/`](examples/) directory for more:

- [`basic_usage.py`](examples/basic_usage.py) - Basic SDK usage
- [`langchain_example.py`](examples/langchain_example.py) - LangChain integration
- [`crewai_example.py`](examples/crewai_example.py) - CrewAI integration

## Documentation

- [Quick Start Guide](https://docs.authevo.com/sdk/python/quickstart)
- [API Reference](https://docs.authevo.com/sdk/python/api-reference)
- [LangChain Integration](https://docs.authevo.com/sdk/python/langchain)
- [CrewAI Integration](https://docs.authevo.com/sdk/python/crewai)

## Development

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

# Run tests
pytest

# Format code
black authevo/ tests/

# Type checking
mypy authevo/
```

## License

MIT - See [LICENSE](LICENSE) for details.

## Support

- [Documentation](https://docs.authevo.com)
- [GitHub Issues](https://github.com/authevo/authevo-python/issues)
- [Discord Community](https://discord.gg/authevo)
