# Inicio rápido del SDK de Python

{% hint style="success" %}
**Lo que vas a construir:** En 5 minutos, buscarás en el mercado de GPU, alquilarás un servidor y te conectarás via SSH — todo desde código o CLI.
{% endhint %}

## Requisitos previos

* **Python 3.9+** instalado
* **Cuenta de Clore.ai** — [regístrate aquí](https://clore.ai)
* **Clave API** — consíguela desde tu [panel de Clore.ai](https://clore.ai)
* **Fondos** — mínimo \~ $5 en BTC, CLORE, USDT o USDC

***

## Paso 1: Instala el SDK

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

Verifica la instalación:

```bash
clore --version
```

***

## Paso 2: Configura tu clave API

**Opción A: Variable de entorno (recomendada)**

```bash
export CLORE_API_KEY=tu_clave_api_aqui
```

**Opción B: Configuración por CLI (se guarda en `~/.clore/config.json`)**

```bash
clore config set api_key YOUR_API_KEY
```

***

## Paso 3: Busca una GPU

### CLI

```bash
clore search --gpu "RTX 4090" --max-price 5.0 --sort price --limit 10
```

Verás una tabla con IDs de servidores, especificaciones de GPU, RAM, precio y ubicación.

### Python

```python
from clore_ai import CloreAI

client = CloreAI()

servers = client.marketplace(gpu="RTX 4090", max_price_usd=5.0)
for s in servers[:5]:
    print(f"Servidor {s.id}: {s.gpu_count}x {s.gpu_model} — ${s.price_usd:.4f}/h — {s.location}")
```

**Salida:**

```
Servidor 142: 1x NVIDIA GeForce RTX 4090 — $0.0800/h — UE
Servidor 305: 1x NVIDIA GeForce RTX 4090 — $0.0950/h — EE. UU.
Servidor 891: 2x NVIDIA GeForce RTX 4090 — $0.1200/h — UE
```

{% hint style="info" %}
**Consejo:** El `marketplace()` método filtra del lado del cliente. También puedes filtrar por `min_gpu_count`, `min_ram_gb`, y `available_only` (predeterminado: `True`).
{% endhint %}

***

## Paso 4: Desplegar (Alquilar un servidor)

### CLI

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

### Python

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

print(f"¡Orden creada! ID: {order.id}")
print(f"IP: {order.pub_cluster}")
print(f"Puertos: {order.tcp_ports}")
```

{% hint style="warning" %}
**El primer arranque tarda entre 1 y 5 minutos.** El servidor descarga la imagen Docker y inicia los servicios. Si `pub_cluster` es `None`, espera y revisa de nuevo con `my_orders()`.
{% endhint %}

***

## Paso 5: Conectarse via SSH

### CLI (conexión automática)

```bash
clore ssh 38
```

La CLI busca la orden, encuentra la IP pública y el puerto SSH, y ejecuta `ssh` por ti.

### SSH manual

```bash
ssh root@<pub_cluster> -p <ssh_port>
# Contraseña: MySecurePass123
```

***

## Paso 6: Limpieza

Cuando termines, cancela la orden para detener la facturación:

### CLI

```bash
clore cancel 38
```

### Python

```python
client.cancel_order(order_id=38, issue="He terminado mi trabajo")
print("Orden cancelada")
```

***

## Script completo: Buscar → Desplegar → Monitorizar → Cancelar

```python
from clore_ai import CloreAI
import time

client = CloreAI()  # Usa la variable de entorno CLORE_API_KEY

# 1. Encontrar la RTX 4090 más barata
servers = client.marketplace(gpu="RTX 4090", max_price_usd=5.0)
servers.sort(key=lambda s: s.price_usd or float("inf"))

if not servers:
    print("No hay RTX 4090 disponibles por debajo de $5/h")
    exit(1)

best = servers[0]
print(f"Mejor oferta: Servidor {best.id} — ${best.price_usd:.4f}/h — {best.location}")

# 2. Desplegar
order = client.create_order(
    server_id=best.id,
    image="cloreai/ubuntu22.04-cuda12",
    type="on-demand",
    currency="bitcoin",
    ssh_password="MySecurePass123",
    ports={"22": "tcp"}
)
print(f"¡Orden {order.id} creada!")

# 3. Esperar la asignación de IP
for _ in range(12):
    orders = client.my_orders()
    current = next((o for o in orders if o.id == order.id), None)
    if current and current.pub_cluster:
        print(f"¡Listo! SSH: ssh root@{current.pub_cluster} -p {current.tcp_ports.get('22', 22)}")
        break
    print("Esperando a que el servidor inicie...")
    time.sleep(10)

# 4. ... haz tu trabajo ...

# 5. Cancela cuando termines
client.cancel_order(order_id=order.id)
print("Orden cancelada, facturación detenida.")
```

***

## Qué sigue

| Guía                                                                        | Lo que aprenderás                                                              |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| [Guía del SDK de Python](/guides/guides_v2-es/avanzado/python-sdk.md)       | Operaciones asíncronas, mercado spot, gestión de servidores, manejo de errores |
| [Automatización con CLI](/guides/guides_v2-es/avanzado/cli-automation.md)   | Scripts Bash, integración CI/CD, despliegue por lotes                          |
| [Integración de API](/guides/guides_v2-es/avanzado/api-integration.md)      | Conecta servicios de IA que se ejecutan en Clore con tus aplicaciones          |
| [Comparación de GPU](/guides/guides_v2-es/primeros-pasos/gpu-comparison.md) | Elige la GPU adecuada para tu carga de trabajo                                 |

***

**¡Feliz alquiler de GPU! 🚀**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-es/primeros-pasos/python-quickstart.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
