> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-ru/nachalo-raboty/python-quickstart.md).

# Быстрый старт SDK на Python

{% hint style="success" %}
**Что вы создадите:** За 5 минут вы поискaете на рынке GPU, арендуете сервер и подключитесь по SSH — всё через код или CLI.
{% endhint %}

## Требования

* **Python 3.9+** установлен
* **Аккаунт Clore.ai** — [зарегистрируйтесь здесь](https://clore.ai)
* **API-ключ** — получите его в вашем [панели управления Clore.ai](https://clore.ai)
* **Средства** — минимум \~5$ в BTC, CLORE, USDT или USDC

***

## Шаг 1: Установите SDK

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

Проверьте установку:

```bash
clore --version
```

***

## Шаг 2: Настройте ваш API-ключ

**Вариант A: Переменная окружения (рекомендуется)**

```bash
export CLORE_API_KEY=your_api_key_here
```

**Вариант B: Конфигурация через CLI (сохраняется в `~/.clore/config.json`)**

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

***

## Шаг 3: Поиск GPU

### CLI

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

Вы увидите таблицу с ID серверов, характеристиками GPU, ОЗУ, ценой и расположением.

### 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"Server {s.id}: {s.gpu_count}x {s.gpu_model} — ${s.price_usd:.4f}/h — {s.location}")
```

**Вывод:**

```
Server 142: 1x NVIDIA GeForce RTX 4090 — $0.0800/h — EU
Server 305: 1x NVIDIA GeForce RTX 4090 — $0.0950/h — US
Server 891: 2x NVIDIA GeForce RTX 4090 — $0.1200/h — EU
```

{% hint style="info" %}
**Совет:** Метод `marketplace()` фильтрует на стороне клиента. Вы также можете фильтровать по `min_gpu_count`, `min_ram_gb`, и `available_only` (по умолчанию: `True`).
{% endhint %}

***

## Шаг 4: Развертывание (Аренда сервера)

### 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"Order created! ID: {order.id}")
print(f"IP: {order.pub_cluster}")
print(f"Ports: {order.tcp_ports}")
```

{% hint style="warning" %}
**Первый запуск занимает 1–5 минут.** Сервер загружает Docker-образ и запускает сервисы. Если `pub_cluster` равен `None`, подождите и проверьте снова с помощью `my_orders()`.
{% endhint %}

***

## Шаг 5: Подключение по SSH

### CLI (автоматическое подключение)

```bash
clore ssh 38
```

CLI находит заказ, определяет публичный IP и SSH-порт и выполняет `ssh` за вас.

### Ручное SSH

```bash
ssh root@<pub_cluster> -p <ssh_port>
# Пароль: MySecurePass123
```

***

## Шаг 6: Очистка (Cleanup)

Когда закончите, отмените заказ, чтобы прекратить выставление счёта:

### CLI

```bash
clore cancel 38
```

### Python

```python
client.cancel_order(order_id=38, issue="Done with my work")
print("Order cancelled")
```

***

## Полный скрипт: Поиск → Развертывание → Мониторинг → Отмена

```python
from clore_ai import CloreAI
import time

client = CloreAI()  # Использует переменную окружения CLORE_API_KEY

# 1. Найти самый дешёвый RTX 4090
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("Нет RTX 4090 доступного дешевле $5/ч")
    exit(1)

best = servers[0]
print(f"Лучшее предложение: Server {best.id} — ${best.price_usd:.4f}/h — {best.location}")

# 2. Развернуть
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"Order {order.id} created!")

# 3. Ждать назначения 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"Готово! SSH: ssh root@{current.pub_cluster} -p {current.tcp_ports.get('22', 22)}")
        break
    print("Ожидание запуска сервера...")
    time.sleep(10)

# 4. ... выполняйте вашу работу ...

# 5. Отмените по завершении
client.cancel_order(order_id=order.id)
print("Заказ отменён, выставление счёта прекращено.")
```

***

## Что дальше

| Руководство                                                                 | Чему вы научитесь                                                            |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| [Руководство по Python SDK](/guides/guides_v2-ru/prodvinutye/python-sdk.md) | Асинхронные операции, спотовый рынок, управление серверами, обработка ошибок |
| [Автоматизация CLI](/guides/guides_v2-ru/prodvinutye/cli-automation.md)     | Bash-скрипты, интеграция CI/CD, массовое развертывание                       |
| [Интеграция API](/guides/guides_v2-ru/prodvinutye/api-integration.md)       | Подключение AI-сервисов, запущенных на Clore, к вашим приложениям            |
| [Сравнение GPU](/guides/guides_v2-ru/nachalo-raboty/gpu-comparison.md)      | Выбор подходящего GPU для вашей нагрузки                                     |

***

**Удачной аренды GPU! 🚀**


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-ru/nachalo-raboty/python-quickstart.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
