# Using the Official clore-ai SDK

> **Note:** This chapter previously covered building a custom SDK from scratch. With the release of the official `clore-ai` package, we recommend using it instead. The custom client approach is still documented in [Clore Client Reference](https://docs.clore.ai/dev/reference/clore-client).

***

## Why Use the Official SDK?

| Feature        | Custom `CloreClient`  | Official `clore-ai`                                            |
| -------------- | --------------------- | -------------------------------------------------------------- |
| Rate limiting  | Manual `time.sleep()` | Built-in (1 req/sec + create\_order cooldown)                  |
| Retries        | Manual or `tenacity`  | Automatic exponential backoff                                  |
| Type safety    | Raw dicts             | Pydantic models (`MarketplaceServer`, `Order`, `Wallet`, etc.) |
| Async          | Build your own        | `AsyncCloreAI` included                                        |
| CLI            | None                  | `clore search`, `clore deploy`, `clore ssh`, etc.              |
| Error handling | Generic `Exception`   | Typed hierarchy (`AuthError`, `RateLimitError`, etc.)          |
| Install        | Copy-paste class      | `pip install clore-ai`                                         |

***

## Quick Migration

### Before

```python
from clore_client import CloreClient

client = CloreClient(api_key="your-key")
servers = client.get_marketplace()
cheapest = client.find_cheapest(gpu_type="RTX 4090")
order = client.create_order(server_id=cheapest["id"], image="nvidia/cuda:12.1.0-base-ubuntu22.04")
running = client.wait_for_order(order["order_id"])
```

### After

```python
from clore_ai import CloreAI

client = CloreAI(api_key="your-key")
servers = client.marketplace(gpu="RTX 4090", max_price_usd=1.0)
servers.sort(key=lambda s: s.price_usd or float("inf"))
order = client.create_order(
    server_id=servers[0].id,
    image="cloreai/ubuntu22.04-cuda12",
    type="on-demand",
    currency="bitcoin",
)
print(f"Order {order.id} @ {order.pub_cluster}")
```

Key differences:

* **No `get_` prefix** — `marketplace()` not `get_marketplace()`
* **Returns typed objects** — `servers[0].gpu_model` not `servers[0]["gpu_array"][0]`
* **Filtering built-in** — pass `gpu=`, `max_price_usd=` directly to `marketplace()`
* **Rate limiting automatic** — no need for `time.sleep()` between calls

***

## Advanced Patterns

### Context Manager

```python
with CloreAI() as client:
    wallets = client.wallets()
    servers = client.marketplace(gpu="A100")
# .close() called automatically
```

### Async Client

```python
import asyncio
from clore_ai import AsyncCloreAI

async def main():
    async with AsyncCloreAI() as client:
        # Concurrent marketplace queries
        rtx4090, a100 = await asyncio.gather(
            client.marketplace(gpu="RTX 4090"),
            client.marketplace(gpu="A100"),
        )
        print(f"4090: {len(rtx4090)} | A100: {len(a100)}")

asyncio.run(main())
```

### Structured Error Handling

```python
from clore_ai import CloreAI
from clore_ai.exceptions import AuthError, RateLimitError, InvalidInputError

try:
    order = client.create_order(...)
except AuthError:
    print("Bad API key")
except InvalidInputError as e:
    print(f"Invalid params: {e}")
except RateLimitError:
    print("Rate limited (auto-retry exhausted)")
```

### Server Management (Hosts)

```python
# Your servers
my_servers = client.my_servers()

# Get config
config = client.server_config("MyGPU")

# Update settings
client.set_server_settings(
    name="MyGPU",
    availability=True,
    mrl=96,
    on_demand=0.0001,
    spot=0.00000113,
)
```

### Spot Market

```python
# View spot market data
market = client.spot_marketplace(server_id=6)
if market.offers:
    for offer in market.offers:
        print(f"Order {offer.order_id}: price={offer.price}")

# Update your bid
client.set_spot_price(order_id=39, price=0.000003)
```

### CLI One-Liners

```bash
# Search, deploy, manage — all from terminal
clore search --gpu "RTX 4090" --max-price 1.0 --sort price
clore deploy 123 --image cloreai/pytorch --type spot --currency bitcoin --spot-price 0.0001
clore orders
clore ssh 456
clore cancel 456
```

***

## Next Steps

* [**SDK API Reference**](https://docs.clore.ai/dev/reference/python-sdk) — every method, model, and exception
* [**SDK Quick Start**](https://docs.clore.ai/dev/getting-started/python-sdk-quickstart) — 5-minute tutorial
* [**Automation Recipes**](https://docs.clore.ai/dev/advanced-use-cases/sdk-automation-recipes) — auto-scaler, spot bot, training pipeline
* [**CI/CD Integration**](https://docs.clore.ai/dev/devops-and-automation/cicd-clore-sdk) — GitHub Actions, GitLab CI, Docker
