# User Guide: How to Use the Kindred AI SDK

This guide explains exactly how to download, install, and use the Kindred AI SDK to route API requests to your server.

## Step 1: Installation

### Option A: Install from Local Directory (Development)

```bash
# Navigate to the SDK directory
cd sidecar/SDK

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

### Option B: Install from PyPI (When Published)

```bash
pip install kindred-ai[all]
```

## Step 2: Set Your Server Endpoint

You have two ways to specify where requests should be routed:

### Method 1: Environment Variables (Easiest - Recommended)

Set environment variables with your server URL and agent token:

```bash
# Linux/Mac
export KINDRED_URL="http://your-server.com:8080"
export KINDRED_AGENT_TOKEN="your-token-here"

# Windows (Command Prompt)
set KINDRED_URL=http://your-server.com:8080
set KINDRED_AGENT_TOKEN=your-token-here

# Windows (PowerShell)
$env:KINDRED_URL="http://your-server.com:8080"
$env:KINDRED_AGENT_TOKEN="your-token-here"
```

**Note:** The `KINDRED_AGENT_TOKEN` is provided by Kindred and is used to identify which agent/user is making requests. It will be automatically added as an `X-Kindred-Agent-Token` header to all intercepted requests.

### Method 2: Specify in Code

You can also specify the endpoint directly in your Python code (see Step 3).

## Step 3: Add SDK Initialization to Your Code

You need to add **just 2-3 lines** at the start of your application to enable interception.

### Minimal Setup (Using Environment Variable)

Add this at the **very beginning** of your application (before any HTTP requests):

```python
from kindred_ai import Interceptor

# Initialize the interceptor - uses KINDRED_URL and KINDRED_AGENT_TOKEN env vars
Interceptor.init(verbose=True)  # verbose=True shows what's being rerouted
```

### Complete Example

Here's a complete example showing how minimal the changes are:

**Before (Original Code):**
```python
import requests

# Your existing code - no changes needed!
response = requests.get("https://api.stripe.com/v1/charges")
response = requests.post("https://api.openai.com/v1/chat/completions", json={...})
```

**After (With SDK - Only 2 lines added):**
```python
from kindred_ai import Interceptor
Interceptor.init(verbose=True)  # <-- ADD THIS

import requests

# Your existing code - NO CHANGES NEEDED!
# Requests whose URLs are in your restricted list will be routed through Kindred.
response = requests.get("https://api.stripe.com/v1/charges")
response = requests.post("https://api.openai.com/v1/chat/completions", json={...})
```

## Step 4: What Gets Rerouted?

Once initialized, HTTP requests whose URLs are in your restricted list (or match your explicit rules) are automatically intercepted:
- ✅ `requests` library
- ✅ `httpx` library (both sync and async)
- ✅ Any library that uses `requests` or `httpx` under the hood (like OpenAI SDK, Anthropic SDK, etc.)

### Example with OpenAI SDK

```python
from kindred_ai import Interceptor
Interceptor.init(verbose=True)  # <-- Just add this

from openai import OpenAI

# No changes to your OpenAI code!
client = OpenAI(api_key="sk-...")
response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello!"}]
)
# This request automatically goes to your server instead of OpenAI!
```

## Step 5: URL Rewriting Behavior

The SDK preserves the original path and query parameters:

**Original Request:**
```
https://api.stripe.com/v1/charges?limit=10
```

**Your Endpoint:**
```
http://your-server.com:8080/proxy
```

**Final Rerouted URL (when using Kindred URL directly):**
```
http://your-server.com:8080/v1/charges?limit=10
```

All headers, query parameters, and request bodies are preserved and forwarded to your server.

**Important:** If `KINDRED_AGENT_TOKEN` is set, it will be automatically added as an `X-Kindred-Agent-Token` header to all intercepted requests. This allows your server to identify which agent/user is making the request.

## Complete Working Example

Here's a complete example you can copy and use:

```python
#!/usr/bin/env python3
"""
Example: Using the Kindred AI SDK
"""

# Step 1: Import and initialize (add these 2 lines)
from kindred_ai import Interceptor
Interceptor.init(verbose=True)  # Shows rerouting in logs

# Step 2: Your existing code - no changes needed!
import requests

# These requests will automatically go through Kindred if in the restricted list
response1 = requests.get("https://api.stripe.com/v1/charges")
print(f"Request went to: {response1.url}")

response2 = requests.post(
    "https://api.openai.com/v1/chat/completions",
    json={"model": "gpt-4", "messages": [{"role": "user", "content": "Hello"}]}
)
print(f"Request went to: {response2.url}")

# Step 3: Clean up (optional, but recommended)
Interceptor.stop()
```

## Advanced: Using Specific Rules Instead of Catch-All

If you want to route specific domains to different endpoints (manual rules):

```python
from kindred_ai import Interceptor

rules = {
    "api.stripe.com": "http://your-server.com:8080/stripe",
    "api.openai.com": "http://your-server.com:8080/openai",
    "*": "http://your-server.com:8080/default"  # Catch-all for others
}

Interceptor.init(routing_rules=rules, verbose=True)
```

## Troubleshooting

### Check if Interceptor is Active

```python
from kindred_ai import Interceptor

if Interceptor.is_active():
    print("Interceptor is running!")
    print("Current rules:", Interceptor.get_rules())
```

### View What's Being Rerouted

Set `verbose=True` when initializing to see logs:

```python
Interceptor.init(verbose=True)
```

You'll see output like:
```
[Kindred AI] Rewriting request: https://api.stripe.com/v1/charges -> http://your-server.com:8080/v1/charges
```

### Verify Environment Variable

```python
import os
print("KINDRED_URL:", os.getenv("KINDRED_URL"))
```

## Summary: What Users Need to Do

1. **Install:** `pip install -e ".[all]"` (or from PyPI when published)
2. **Set environment variables:** `export KINDRED_URL="http://your-server.com:8080"` and `export KINDRED_AGENT_TOKEN="your-token"`
3. **Add 2 lines to their code:**
   ```python
   from kindred_ai import Interceptor
   Interceptor.init(verbose=True)
   ```
4. **That's it!** Requests whose URLs are in the restricted list (or match your rules) are now automatically routed through Kindred.

No other code changes needed - the SDK intercepts matching requests transparently!

