# Python SDK Quick Start

Get up and running with the official `clore-ai` Python SDK in under 5 minutes. By the end of this guide, you'll search the GPU marketplace, create an order, and manage it — all from Python and the terminal.

***

## Step 1: Install the SDK

```bash
pip install clore-ai
```

Verify the installation:

```bash
clore --version
```

***

## Step 2: Get Your API Key

1. Go to [clore.ai](https://clore.ai) and sign in
2. Navigate to your profile / API settings
3. Copy your API key

Set it up (choose one):

```bash
# Option A: Environment variable (recommended)
export CLORE_API_KEY=your_api_key_here

# Option B: CLI config (persistent)
clore config set api_key YOUR_API_KEY
```

***

## Step 3: Your First Script

Create a file called `my_first_gpu.py`:

```python
from clore_ai import CloreAI

# Initialize client (picks up CLORE_API_KEY from env)
client = CloreAI()

# 1. Browse the marketplace
print("🔍 Searching for RTX 4090 GPUs...")
servers = client.marketplace(gpu="RTX 4090", max_price_usd=1.0)

if not servers:
    print("No servers found matching criteria")
    exit()

# Sort by price
servers.sort(key=lambda s: s.price_usd or float("inf"))

print(f"Found {len(servers)} servers:\n")
for s in servers[:5]:
    print(f"  ID {s.id}: {s.gpu_count}x {s.gpu_model} — ${s.price_usd:.4f}/h — {s.location}")

# 2. Rent the cheapest one
best = servers[0]
print(f"\n🚀 Renting server {best.id}...")

order = client.create_order(
    server_id=best.id,
    image="cloreai/ubuntu22.04-cuda12",
    type="on-demand",
    currency="bitcoin",
    ssh_password="MySecurePass123",
    ports={"22": "tcp", "8888": "http"},
)

print(f"✅ Order created!")
print(f"   Order ID: {order.id}")
print(f"   IP: {order.pub_cluster}")

# 3. Check your orders
print("\n📦 Your active orders:")
orders = client.my_orders()
for o in orders:
    print(f"  Order {o.id}: {o.type} — {o.status} @ {o.pub_cluster}")

# 4. Check wallet balance
print("\n💰 Wallet balances:")
wallets = client.wallets()
for w in wallets:
    print(f"  {w.name}: {w.balance:.8f}")
```

Run it:

```bash
python my_first_gpu.py
```

***

## Step 4: Using the CLI

You can do the same operations from the terminal without writing any Python.

### Search the marketplace

```bash
# Find RTX 4090 GPUs under $1/hour, sorted by price
clore search --gpu "RTX 4090" --max-price 1.0 --sort price --limit 10
```

### Deploy a server

```bash
clore deploy 123 \
  --image cloreai/ubuntu22.04-cuda12 \
  --type on-demand \
  --currency bitcoin \
  --ssh-password MySecurePass123 \
  --port 22:tcp \
  --port 8888:http
```

### List orders

```bash
clore orders
```

### SSH into your instance

```bash
clore ssh 456
```

### Cancel an order

```bash
clore cancel 456
```

### Check balances

```bash
clore wallets
```

### Spot market

```bash
# View spot offers for a server
clore spot 123

# Update your spot bid
clore spot-price 456 0.000003
```

***

## Step 5: Async Operations

For advanced use cases (concurrent API calls, integration with async frameworks), use the `AsyncCloreAI` client:

```python
import asyncio
from clore_ai import AsyncCloreAI

async def main():
    async with AsyncCloreAI() as client:
        # Search multiple GPU types concurrently
        rtx4090, a100, rtx3090 = await asyncio.gather(
            client.marketplace(gpu="RTX 4090"),
            client.marketplace(gpu="A100"),
            client.marketplace(gpu="RTX 3090"),
        )

        print(f"RTX 4090: {len(rtx4090)} servers")
        print(f"A100:     {len(a100)} servers")
        print(f"RTX 3090: {len(rtx3090)} servers")

        # Create an order
        if rtx4090:
            best = min(rtx4090, key=lambda s: s.price_usd or float("inf"))
            order = await client.create_order(
                server_id=best.id,
                image="cloreai/pytorch",
                type="spot",
                currency="bitcoin",
                spot_price=0.0001,
            )
            print(f"Created spot order {order.id}")

asyncio.run(main())
```

***

## Troubleshooting

### `AuthError: API key required for this endpoint`

Your API key isn't being found. Check:

```bash
# Is it set?
echo $CLORE_API_KEY

# Or check the config
clore config get api_key
```

Fix: set the key in your environment or pass it directly:

```python
client = CloreAI(api_key="your_key_here")
```

### `RateLimitError: Rate limit exceeded`

The SDK auto-retries with exponential backoff up to `max_retries` times. If you still hit this, you're making too many requests. The built-in rate limiter enforces 1 req/sec — avoid creating your own parallel loops that bypass it.

### `InvalidInputError` when creating an order

Double-check:

* `server_id` exists and is available (check `marketplace()` first)
* `image` is a valid Docker image
* `type` is exactly `"on-demand"` or `"spot"`
* `currency` is a valid payment method (e.g. `"bitcoin"`, `"CLORE-Blockchain"`)
* For spot orders, `spot_price` must be set

### Connection refused when using `clore ssh`

The server might still be starting up. Wait 30–60 seconds after order creation and try again. Check the order status:

```bash
clore orders
```

### `ModuleNotFoundError: No module named 'clore_ai'`

Make sure you installed the SDK in the right Python environment:

```bash
pip install clore-ai

# Check it's installed
pip show clore-ai
```

***

## What's Next?

* [**SDK API Reference**](https://docs.clore.ai/dev/reference/python-sdk) — every method, parameter, and model
* [**Automation Recipes**](https://docs.clore.ai/dev/advanced-use-cases/sdk-automation-recipes) — auto-scaler, spot bidding bot, training pipeline
* [**CI/CD Integration**](https://docs.clore.ai/dev/devops-and-automation/cicd-clore-sdk) — GitHub Actions, GitLab CI, Docker
* [**Automating GPU Rental**](https://docs.clore.ai/dev/getting-started/automation-basics) — raw `requests` approach (for learning)

> 📚 See also: [Clore.ai Python SDK — Automate Your GPU Workflows in 5 Minutes](https://blog.clore.ai/cloreai-python-sdk-automate-your-gpu-workflows-in-5-minutes/)
