# MixrPay Agent SDK for Python

Enable AI agents to make autonomous payments.

## Installation

```bash
pip install mixrpay
```

## Setup

```bash
export MIXRPAY_SESSION_KEY=sk_live_...
```

Session keys are created by wallet owners at [mixrpay.com/wallet/sessions](https://www.mixrpay.com/wallet/sessions).

## Basic Usage

```python
from mixrpay import AgentWallet

wallet = AgentWallet(session_key="sk_live_...")

# Call a paid API
response = await wallet.call_merchant_api(
    url="https://api.merchant.com/generate",
    merchant_public_key="pk_live_...",
    price_usd=0.05,
    json={"prompt": "Hello world"}
)

data = response.json()
```

## Pre-Flight Checks

```python
# Check if wallet can afford an amount before calling
check = await wallet.can_afford(0.50)
if check.can_afford:
    response = await wallet.call_merchant_api(...)
else:
    print(f"Insufficient funds. Have: ${check.current_balance}")

# Run diagnostics for debugging
diag = await wallet.run_diagnostics()
print(f"Balance: ${diag.balance_usd}")
print(f"Latency: {diag.latency_ms}ms")
print(f"Recommendations: {diag.recommendations}")
```

## Error Handling

```python
from mixrpay import (
    AgentWallet,
    MixrPayError,
    InsufficientBalanceError,
    SessionLimitExceededError,
    PaymentFailedError,
)

try:
    response = await wallet.call_merchant_api(...)
except InsufficientBalanceError as e:
    print(f"Low balance. Top up: {e.top_up_url}")
except SessionLimitExceededError:
    print("Session limit exceeded")
except MixrPayError as e:
    # Check if error is retryable
    if e.is_retryable():
        delay = e.retry_after_ms / 1000 if e.retry_after_ms else 1
        await asyncio.sleep(delay)
        return await retry()
    raise
```

## Spending Controls

```python
wallet = AgentWallet(
    session_key="sk_live_...",
    max_payment_usd=1.0,  # Client-side safety limit
    on_payment=lambda p: print(f"Paid ${p.amount_usd}"),
)

# Check balance
balance = await wallet.get_balance()
stats = wallet.get_spending_stats()
```

## Context Manager

```python
async with AsyncAgentWallet(session_key="sk_live_...") as wallet:
    response = await wallet.call_merchant_api(...)
```

## LangChain Integration

```python
from langchain.tools import BaseTool
from mixrpay import AgentWallet

class PaidSearchTool(BaseTool):
    name = "paid_search"
    description = "Premium search ($0.05/query)"
    
    def __init__(self, session_key: str):
        super().__init__()
        self.wallet = AgentWallet(session_key=session_key)
    
    async def _arun(self, query: str) -> str:
        response = await self.wallet.call_merchant_api(
            url="https://api.search.com/query",
            merchant_public_key="pk_live_...",
            price_usd=0.05,
            json={"query": query}
        )
        return response.json()["results"]
```

## What's New in v0.6.0

- `can_afford(amount_usd)` - Pre-flight balance check
- `is_retryable()` on all errors - Determine if operation should be retried
- `retry_after_ms` on errors - Suggested retry delay
- Enhanced `run_diagnostics()` - Session limits, latency, recommendations
- `request_id` and `correlation_id` in payment events

## Documentation

Full documentation at [mixrpay.com/docs](https://www.mixrpay.com/docs)

## License

MIT
