# Developer Documentation

Build with NeuralHive from installation to inference.

The NeuralHive Python SDK gives developers a simple client for model access, authentication, model discovery, and inference workflows.

This guide is for **neuralhive 2.1.0**.

<!-- toc -->
## Contents

- [Overview](#overview)
  - [Pricing and billing](#pricing-and-billing)
- [Installation](#installation)
  - [Requirements](#requirements)
  - [Check the installed version](#check-the-installed-version)
  - [What changed in 2.1.0](#what-changed-in-210)
  - [What changed in 2.0.0](#what-changed-in-200)
  - [What changed in 1.2.0](#what-changed-in-120)
- [Authentication](#authentication)
  - [Generate an API key](#generate-an-api-key)
  - [Option 1: Configure once](#option-1-configure-once)
  - [Option 2: Environment variable](#option-2-environment-variable)
  - [Option 3: Direct key in code](#option-3-direct-key-in-code)
  - [Which key is used](#which-key-is-used)
- [Quick Start](#quick-start)
- [Models](#models)
  - [List models](#list-models)
  - [Get model details](#get-model-details)
- [Inference Tasks](#inference-tasks)
  - [Limits and formats](#limits-and-formats)
  - [Long-running methods](#long-running-methods)
  - [List inputs for long-running methods](#list-inputs-for-long-running-methods)
  - [Parallel calls](#parallel-calls)
  - [Object detection example](#object-detection-example)
  - [Text generation example](#text-generation-example)
- [API Reference](#api-reference)
  - [`NeuralhiveClient()`](#neuralhiveclientapi_keynone--timeout600-max_retries2-poll_interval5-job_timeout5000-max_connections20)
  - [Shared return values](#shared-return-values)
  - [`neuralhive.detect()`](#neuralhivedetectimage_path-model_idnone-promptnone-export_tonone-confnone)
  - [`neuralhive.segment()`](#neuralhivesegmentimage_path-model_idnone-promptnone-export_tonone-confnone)
  - [`neuralhive.detect_and_segment()`](#neuralhivedetect_and_segmentimage_path-prompt-export_tonone)
  - [`neuralhive.recognize()`](#neuralhiverecognizeimage_path)
  - [`neuralhive.reidentify()`](#neuralhivereidentifyimage_path-model_idnone)
  - [`neuralhive.estimate_pose()`](#neuralhiveestimate_poseimage_path-export_tonone)
  - [`neuralhive.embed()`](#neuralhiveembedtextnone-image_pathnone-model_idnone)
  - [`neuralhive.generate_text()`](#neuralhivegenerate_textprompt-model_idnone-image_pathsnone-video_pathsnone-system_promptnone-enable_thinkingfalse)
  - [`neuralhive.analyze()`](#neuralhiveanalyzetextnone-image_pathsnone-video_pathsnone)
  - [`neuralhive.generate_image()`](#neuralhivegenerate_imageprompt-export_tonone-heightnone-widthnone)
  - [`neuralhive.edit_image()`](#neuralhiveedit_imageimage_path-prompt-export_tonone)
  - [`neuralhive.transcribe_audio()`](#neuralhivetranscribe_audioaudio_path)
  - [`neuralhive.read_text()`](#neuralhiveread_textfile_path-export_tonone-taskocr)
  - [`neuralhive.detect_layout()`](#neuralhivedetect_layoutfile_path-export_tonone-detection_thresholdnone)
  - [`neuralhive.parse_document()`](#neuralhiveparse_documentfile_path-export_to-parse_modepage)
  - [`neuralhive.generate_3d()`](#neuralhivegenerate_3dimage_path-export_tonone)
- [Error Handling](#error-handling)
- [Examples](#examples)
  - [Generate image](#generate-image)
  - [Analyze image](#analyze-image)
  - [Parse document](#parse-document)
  - [Transcribe many audio files](#transcribe-many-audio-files)
  - [Generate 3D asset](#generate-3d-asset)
<!-- /toc -->

## Overview

NeuralHive SDK is a Python client for accessing NeuralHive models through a consistent API. It helps developers discover available models, run inference, and build AI workflows without working directly with low-level API requests.

The SDK supports common computer vision, multimodal, embedding, generation, document, audio, and 3D asset workflows through simple Python methods.

### Pricing and billing

- Every **successful** inference call is a real request and is **billed** to the account that owns the API key. See [Pricing](https://neuralhive.ai/pricing) for the price of each model.
- Inference calls are the methods listed in [Inference Tasks](#inference-tasks). `list_models()` and `get_model()` do not run a model.
- If the SDK rejects a call before sending it (it raises `InvalidInputError`), nothing is sent, so nothing is billed.
- Calls are not free while you test. Do not call inference methods in a loop until you have checked one result. Keep test inputs small.

## Installation

Install the SDK from pip:

```bash
pip install neuralhive
```

To upgrade an existing installation:

```bash
pip install --upgrade neuralhive
```

### Requirements

- Python 3.9 or newer.
- pip installs the other packages the SDK needs.

### Check the installed version

```bash
neuralhive --version
```

or in Python:

```python
import neuralhive

print(neuralhive.__version__)  # 2.1.0
```

If a method in this guide is missing (for example `parse_document`), upgrade with `pip install --upgrade neuralhive`.

### What changed in 2.1.0

- `detect_and_segment()` takes a **list of images**, with one prompt for all images or one prompt per image. The SDK sends up to 8 images in one request. See [`detect_and_segment()`](#neuralhivedetect_and_segmentimage_path-prompt-export_tonone).
- Results now also have `scores`, `labels` (which object each detection is), `concepts` and `dropped_concepts`. This is true for one image too, and for `detect()` and `segment()` with a `sam3` model.
- One prompt can name up to 10 objects, separated by `,` or `;`, for example `"hard hat, vest, person"`.
- Code written for 2.0.0 keeps working: the one-image result still has `masks`, `boxes`, `score`, `image_height` and `image_width`, with the same types.

### What changed in 2.0.0

2.0.0 is a major release. Code written for 1.x must change in one place: the class name.

- **Breaking:** `Client` is renamed to `NeuralhiveClient`. Change `from neuralhive import Client` to `from neuralhive import NeuralhiveClient`.
- Each client now keeps its own API key. Several clients with different keys can run in the same process, at the same time.
- A client is thread-safe and reuses HTTP connections (a connection pool). See [Parallel calls](#parallel-calls).
- New client settings: `timeout`, `max_retries`, `poll_interval`, `job_timeout`, `max_connections`. See [Settings](#settings).
- A client can be closed: `neuralhive.close()`, or use it in a `with` block.
- `detect()` and `segment()` have a new `conf` parameter (minimum score).
- `detect()` and `segment()` with an `instance_segmentation` model now return `class_names`, `image_height` and `image_width`.
- `detect_layout()` has a new `detection_threshold` parameter.
- `generate_text()` has a new `enable_thinking` parameter (VLM models).
- `neuralhive.__version__` gives the installed version.
- `generate_image()`, `edit_image()`, `transcribe_audio()`, `parse_document()` and `generate_3d()` accept a **list** of inputs. The SDK runs them in parallel and returns a list of results. See [List inputs](#list-inputs-for-long-running-methods).
- New exception: `BatchError`.
- `parse_document()` saves one Markdown (`.md`) file and returns `markdown_path` and `page_count`. There is no JSON file and no `json_path` any more.

### What changed in 1.2.0

- New method: `parse_document()`.
- `read_text()` now returns the text itself (a `str`), and has a new `task` parameter.
- `detect_layout()` now returns the layout result (a `dict` with `count` and `pages`).
- `generate_image()` has new `height` and `width` parameters.
- `generate_image()`, `edit_image()`, `transcribe_audio()`, and `generate_3d()` now raise `TaskFailedError` when the job fails. Before, they returned an empty result.
- New public exception classes (see [Error Handling](#error-handling)).
- The SDK now retries automatically while a model is starting (cold start).

## Authentication

The SDK needs a NeuralHive API key. The recommended approach is to configure it once from the command line.

### Generate an API key

1. Sign in to your NeuralHive account.
2. Open Account Settings / API Keys.
3. Create a new API key.
4. Copy the key and keep it secure.

Store the key securely. For security reasons, you may not be able to view it again after closing.

### Option 1: Configure once

```bash
neuralhive configure --api-key nh_live_your_api_key
```

The key is saved in `~/.neuralhive/credentials`.

### Option 2: Environment variable

```bash
export NEURALHIVE_API_KEY="nh_live_your_api_key"
```

### Option 3: Direct key in code

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient("nh_live_your_api_key")
```

Avoid hardcoding API keys in production code. Prefer the CLI configuration or environment variable setup.

### Which key is used

`NeuralhiveClient()` looks for the key in this order and uses the first one it finds:

1. The key passed to `NeuralhiveClient("nh_live_...")`.
2. The `NEURALHIVE_API_KEY` environment variable.
3. The key saved by `neuralhive configure`.

The key is checked on the first method call, not when the client is created. A wrong key raises `AuthenticationError` on that first call.

## Quick Start

Create a client and list the models allowed for your API key.

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()
models = neuralhive.list_models()
print(models)
```

## Models

### List models

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()
models = neuralhive.list_models()
```

Returns a `list` with one `dict` per model your API key can use:

```python
[
    {"_id": "668384b260d316759df76666", "name": "Ready-Made Object Detection", "task": "object_detection", "is_default": True},
    {"_id": "6a4239916a5c33ece3f9c39d", "name": "Ready-Made OCR", "task": "ocr", "is_default": True},
    ...
]
```

| Key | Type | Meaning |
|---|---|---|
| `_id` | `str` | The model id. Pass it as `model_id`. |
| `name` | `str` | Display name. |
| `task` | `str` | The model family. It decides which SDK methods can use the model (see [Inference Tasks](#inference-tasks)). |
| `is_default` | `bool` | `True` if the SDK uses this model when you leave out `model_id`. |

`task` is one of: `object_detection`, `face_detection`, `instance_segmentation`, `sam3`, `face_recognition`, `person_reid`, `pose_estimation`, `clip`, `text_embeddings`, `slm`, `vlm`, `image_generation`, `image_editing`, `asr`, `ocr`, `layout_detection`, `document_parsing`, `3d_asset_generation`. A model with any other task (for example `pixel_streaming`) has no SDK method.

To find a model for a method, filter by `task`:

```python
sam3_ids = [m["_id"] for m in neuralhive.list_models() if m["task"] == "sam3"]
```

### Get model details

```python
model = neuralhive.get_model("your_model_id")
print(model)
```

Returns a `dict`, for example:

```python
{"_id": "668384b260d316759df76666", "name": "Ready-Made Object Detection", "task": "object_detection",
 "project": "", "deploy_status": "", "is_uploaded": False}
```

## Inference Tasks

Each SDK method works with specific model families. Use `neuralhive.list_models()` to see the models available to your API key. Many methods can use a default model from your allowed models when `model_id` is omitted.

| Task | Description | SDK Method | Supported Model Families (`task`) |
|---|---|---|---|
| Detection | Detect objects, faces, or regions from a local image file. | `neuralhive.detect()` | Object Detection (`object_detection`), Face Detection (`face_detection`), Instance Segmentation (`instance_segmentation`), SAM3 / prompt-based segmentation (`sam3`) |
| Segmentation | Segment image regions from a local image file, optionally with a prompt. | `neuralhive.segment()` | Instance Segmentation (`instance_segmentation`), SAM3 / prompt-based segmentation (`sam3`) |
| Detection + Segmentation | Run prompt-based SAM3 detection and segmentation together. | `neuralhive.detect_and_segment()` | SAM3 / prompt-based segmentation (`sam3`) |
| Face Recognition | Generate face embeddings from a local image file. | `neuralhive.recognize()` | Face Recognition (`face_recognition`) |
| Re-identification | Run person re-identification on a local image file. | `neuralhive.reidentify()` | Person Re-identification (`person_reid`) |
| Pose Estimation | Estimate human pose from a local image file. | `neuralhive.estimate_pose()` | Pose Estimation (`pose_estimation`) |
| Embeddings | Create embeddings from text or a local image file. | `neuralhive.embed()` | Text Embeddings (`text_embeddings`), CLIP / text-image embeddings (`clip`) |
| Text Generation | Generate text from prompts and optional local media files. | `neuralhive.generate_text()` | SLM / text generation (`slm`), VLM / multimodal generation (`vlm`) |
| Analysis | Analyze text, local image files, or local/public videos. | `neuralhive.analyze()` | VLM / multimodal analysis (`vlm`) |
| Image Generation | Generate an image from a prompt, optionally exporting it locally. | `neuralhive.generate_image()` | Image Generation (`image_generation`) |
| Image Editing | Edit a local image file using a text instruction, optionally exporting it locally. | `neuralhive.edit_image()` | Image Editing (`image_editing`) |
| Audio Transcription | Transcribe speech from a local audio file. | `neuralhive.transcribe_audio()` | Audio Transcription (`asr`) |
| OCR | Read/extract text from a local image file. | `neuralhive.read_text()` | OCR (`ocr`) |
| Layout Detection | Detect document layout regions from a local image file. | `neuralhive.detect_layout()` | Layout Detection (`layout_detection`) |
| Document Parsing | Turn a local PDF or image file into a Markdown file. | `neuralhive.parse_document()` | Document Parsing (`document_parsing`) |
| 3D Generation | Generate a 3D asset from a local image file, optionally exporting it locally. | `neuralhive.generate_3d()` | 3D Asset Generation (`3d_asset_generation`) |

### Limits and formats

The SDK reads local files and sends them for you. These rules apply:

| Method | Input rules |
|---|---|
| All image inputs | JPEG or PNG file. |
| `detect()`, `segment()` | `prompt` is required when the model's task is `sam3`. `conf` is 0 to 1, and only for `object_detection` and `instance_segmentation` models. |
| `detect_and_segment()` | `prompt` is required. One prompt can name several objects, separated by `,` or `;` (for example `"hard hat, vest, person"`). Only the first 10 objects are used. With a list of images: one prompt for all, or exactly one prompt per image. |
| `embed()` | Exactly one of `text` or `image_path`. Text Embeddings models accept `text` only. |
| `generate_text()` | `enable_thinking` is only for VLM models. |
| `generate_text()`, `analyze()` with a VLM model | All local images together: at most **5 MB**. All local videos together: at most **30 MB**. Video URLs (`http://` or `https://`) do not count toward the limit. |
| `generate_image()` | `prompt`: 1 to 3000 characters. `height` and `width`: 512 to 2048, and a multiple of 32 (default 1024). |
| `edit_image()` | `prompt`: 1 to 3000 characters. The output size is the input size rounded to a multiple of 32, with the long side at most 1024. An image with a short side under 512 is scaled up to 512 first. |
| `transcribe_audio()` | WAV, FLAC, or MP3 file. |
| `read_text()` | One JPEG or PNG image. No PDF (use `parse_document()`). `task` is one of `ocr`, `table`, `formula`, `chart`, `spotting`, `seal`. |
| `detect_layout()` | One JPEG or PNG image, at most **20 MB**. No PDF. `detection_threshold` is 0.05 to 0.95. |
| `parse_document()` | PDF or image file, at most **2 GB** each. `parse_mode` is `page` or `region`. Give a list for many files. |
| `generate_3d()` | One image of **one object**, best on a plain background. |

### Long-running methods

`generate_image()`, `edit_image()`, `transcribe_audio()`, `parse_document()`, and `generate_3d()` run as jobs on the server. The method waits until the job is done and then returns. If a job fails, the method raises `TaskFailedError`.

If a model has not been used for some time, the server starts it first (a "cold start"). The first call can then take a few minutes. The SDK retries for you (see [Settings](#settings)).

### List inputs for long-running methods

These methods take one input **or a list** of inputs:

| Method | Give a list in |
|---|---|
| `generate_image()` | `prompt` (one image per prompt) |
| `edit_image()` | `image_path` (the same `prompt` is used for every image) |
| `transcribe_audio()` | `audio_path` |
| `parse_document()` | `file_path` |
| `generate_3d()` | `image_path` |

`detect_and_segment()` also takes a list of images. It works a little differently: it sends up to 8 images in **one** request (see [`detect_and_segment()`](#neuralhivedetect_and_segmentimage_path-prompt-export_tonone)).

With a list, the SDK runs the items **in parallel**, on threads, and returns a **list of results in the same order** as your inputs. The other parameters (for example `export_to`) are the same for every item.

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

results = neuralhive.parse_document(
    ["/path/to/a.pdf", "/path/to/b.pdf", "/path/to/c.pdf"],
    export_to="/path/to/parsed",
)

for result in results:
    print(result["page_count"], result["markdown_path"])
```

How it works:

- Each item is its **own job** on the server, and it is **billed on its own**. Three files are three jobs.
- At most `max_connections` items run at the same time (default 20). See [Settings](#settings).
- All items are checked **before** anything is sent. An empty list, an empty item, or a missing file raises `InvalidInputError`, and nothing is billed.
- If some items fail, the others still finish. Then the method raises `BatchError`. Its `results` list has every finished result in input order (`None` for a failed item), and `errors` maps the index of each failed item to its exception:

```python
from neuralhive import BatchError

try:
    results = neuralhive.generate_image(["a red car", "a blue boat", "a green tree"])
except BatchError as error:
    for index, problem in error.errors.items():
        print("item", index, "failed:", problem)
    results = error.results          # finished items are kept; failed ones are None
```

- `parse_document()` with a list never overwrites a file. If a file name is already taken in `export_to`, `_1`, `_2`, ... is added to the new name.
- The server can queue jobs when it is busy, so a long list may take a while.

### Parallel calls

One client is thread-safe. For methods without list input, share the client between your own threads:

```python
from concurrent.futures import ThreadPoolExecutor

from neuralhive import NeuralhiveClient

texts = ["a bus", "a person", "a dog"]

with NeuralhiveClient(max_connections=8) as neuralhive:
    with ThreadPoolExecutor(max_workers=8) as pool:
        vectors = list(pool.map(lambda text: neuralhive.embed(text=text), texts))
```

- Each call is a separate request and is billed separately.
- Set `max_connections` to at least the number of threads.

### Object detection example

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.detect(
    image_path="/absolute/path/to/image.jpg",
)

print(result)
```

### Text generation example

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

response = neuralhive.generate_text(
    prompt="Write a short product description.",
)

print(response)
```

## API Reference

### `NeuralhiveClient(api_key=None, *, timeout=600, max_retries=2, poll_interval=5, job_timeout=5000, max_connections=20)`

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()                      # key from env or `neuralhive configure`
neuralhive = NeuralhiveClient("nh_live_...", timeout=120, max_retries=3)

with NeuralhiveClient() as neuralhive:               # closes the connections at the end
    print(neuralhive.list_models())
```

#### Settings

All settings except `api_key` must be given by name.

| Parameter | Type | Default | Description |
|---|---|---|---|
| `api_key` | `str` | `None` | API key. If not given, see [Which key is used](#which-key-is-used). |
| `timeout` | `float` | `600` | Seconds to wait for one HTTP request. At least 1. |
| `max_retries` | `int` | `2` | How many times to send a call again when the model is still starting (cold start, HTTP 503). The SDK waits 30 seconds before each retry. A 503 is not billed. `0` turns retries off. |
| `poll_interval` | `float` | `5` | Long-running methods: seconds between result checks. At least 0.5. |
| `job_timeout` | `float` | `5000` | Long-running methods: the longest time to wait for a job, in seconds (about 83 minutes). After that, the method raises `TaskFailedError`. The job may still finish on the server. |
| `max_connections` | `int` | `20` | Size of the HTTP connection pool. Set it to at least the number of threads that share this client. |

A wrong setting raises `InvalidInputError` when you create the client.

Network problems are retried for you: a failed connection is tried again up to 3 times. A call that already reached the server is **not** sent again (except the cold-start 503), so you are never billed twice for one call.

#### Threads and several API keys

- A client is **thread-safe**. Share one client between threads. Calls run in parallel and reuse open connections. See [Parallel calls](#parallel-calls).
- Each client keeps **its own** API key. You can create several clients with different keys in the same process, and use them at the same time.
- Create a client once and reuse it. Do not create a new client for every call.

#### `neuralhive.close()`

Closes the client's connections. After `close()`, every method raises `NeuralHiveError`. A `with NeuralhiveClient() as neuralhive:` block calls `close()` for you.

### Shared return values

- `saved_path`: the path of the file written to `export_to`. When the method has an `export_to` parameter and you leave it out, `saved_path` is `None` or not present.
- Box format: `[x_min, y_min, x_max, y_max]` in pixels of the original image.
- `download_url`: a pre-signed link to the result file. It expires after some time. Use `export_to` to keep the file.

### `neuralhive.detect(image_path, model_id=None, prompt=None, export_to=None, conf=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `image_path` | `str` | Yes | Local image file path. |
| `model_id` | `str` | No | Target model identifier. |
| `prompt` | `str` | No | Optional prompt, required for `sam3` models. |
| `export_to` | `str` | No | Export directory path for box-rendered image. |
| `conf` | `float` | No | Minimum score, 0 to 1. Only results with `score >= conf` come back. Server default is 0.5. Only for `object_detection` and `instance_segmentation` models. |

If `model_id` is not provided, the SDK uses the default `object_detection` model from your allowed models.

Returns `dict`. The keys depend on the model's `task`:

| Model task | Returned keys |
|---|---|
| `object_detection` | `boxes`, `classes`, `scores` |
| `face_detection` | `boxes`, `classes` (always `0`), `scores`, `masks` (always empty) |
| `instance_segmentation` | `boxes`, `classes`, `class_names`, `scores`, `masks`, `image_height`, `image_width` |
| `sam3` | see [`detect_and_segment()`](#neuralhivedetect_and_segmentimage_path-prompt-export_tonone) |

- `boxes`: `list[list[float]]`, one box per object.
- `classes`: `list[int]`, the class number per object, starting at 0. For the ready-made models these are COCO class numbers (for example `0` = person, `5` = bus).
- `scores`: `list[float]`, confidence from 0 to 1.
- `class_names` (instance segmentation): `list[str]`, the class name per object, for example `"person"`. Ready-made model: the 80 COCO names. Your fine-tuned models: your dataset's names (older fine-tuned models: `class_0`, `class_1`, ...).
- `masks` (instance segmentation): `list[list[list[int]]]`, one outline per object, as `[x, y]` points in order. Join the points to draw the polygon.
- `image_height`, `image_width` (instance segmentation): `int`, image size in pixels. Not present when nothing is found.
- `saved_path`: `str`, only when `export_to` is provided.

All lists have the same length. Index `i` in each list is the same object.

```python
# object_detection
{"boxes": [[11.86, 229.23, 804.77, 739.51], ...], "classes": [5, 0, ...], "scores": [0.957, 0.91, ...]}

# instance_segmentation
{"boxes": [...], "classes": [0, 0, 0, 5, 0], "class_names": ["person", "person", "person", "bus", "person"],
 "scores": [...], "masks": [[[279, 401], [277, 403], ...], ...], "image_height": 1080, "image_width": 810}
```

### `neuralhive.segment(image_path, model_id=None, prompt=None, export_to=None, conf=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `image_path` | `str` | Yes | Local image file path. |
| `model_id` | `str` | No | Target model identifier. |
| `prompt` | `str` | No | Optional prompt, required for `sam3` models. |
| `export_to` | `str` | No | Export directory path for mask-rendered image. |
| `conf` | `float` | No | Minimum score, 0 to 1 (server default 0.5). Only for `instance_segmentation` models. |

If `model_id` is not provided, the SDK uses the default `instance_segmentation` model from your allowed models.

Returns `dict`. With an `instance_segmentation` model: `boxes`, `classes`, `class_names`, `scores`, `masks`, `image_height`, `image_width` (same as `detect()`). With a `sam3` model: same as `detect_and_segment()`. `saved_path` is added when `export_to` is provided.

### `neuralhive.detect_and_segment(image_path, prompt, export_to=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `image_path` | `str` or `list[str]` | Yes | Local image file path, or a list of paths. |
| `prompt` | `str` or `list[str]` | Yes | What to find, for example `"bus"` or `"hard hat, vest, person"` (up to 10 objects, separated by `,` or `;`). With a list of images: one `str` for all images, or a list with one prompt per image, in the same order. |
| `export_to` | `str` | No | Export directory path for mask+box-rendered image(s). |

#### One image

Returns `dict`:

| Key | Type | Meaning |
|---|---|---|
| `masks` | `list[list[list[int]]]` | One item per detection. Each item is a list of polygons (an object can have several parts). Each polygon is a flat list `[x1, y1, x2, y2, ...]`. |
| `boxes` | `list[list[float]]` | One box per detection. |
| `scores` | `list[float]` | Confidence per detection, 0 to 1. |
| `labels` | `list[str]` | Which object of the prompt each detection is, for example `"person"`. |
| `concepts` | `list[dict]` | Every object of the prompt with its count, for example `{"concept": "bus", "count": 1}`. `count` is `0` when it was not found. |
| `dropped_concepts` | `list[str]` | Objects that were not used, because the prompt had more than 10. |
| `score` | `str` | Confidence of the first detection, as text (for example `"0.949"`). Empty when nothing is found. Kept for older code; prefer `scores`. |
| `image_height` | `str` | Image height in pixels, as text. |
| `image_width` | `str` | Image width in pixels, as text. |
| `saved_path` | `str` | Only when `export_to` is provided. |

```python
result = neuralhive.detect_and_segment("street.jpg", "bus, person")

{"masks": [[[111, 599, 110, 600, ...]], ...], "boxes": [[3.99, 229.1, 805.2, 740.3], ...],
 "scores": [0.949, 0.91, ...], "labels": ["bus", "person", ...],
 "concepts": [{"concept": "bus", "count": 1}, {"concept": "person", "count": 4}], "dropped_concepts": [],
 "score": "0.949", "image_height": "1080", "image_width": "810"}
```

#### A list of images

```python
results = neuralhive.detect_and_segment(
    ["site1.jpg", "site2.jpg", "street.jpg"],
    ["hard hat, vest, person", "helmet, gloves", "bus, car"],   # or one str for all images
)

for result in results:
    print(result["labels"], result["scores"])
```

- The SDK sends up to **8 images in one request**. A longer list is split into groups of 8, and the groups run in parallel.
- Returns a `list` with **one `dict` per image**, in the same order as `image_path`.
- If some groups fail, the method raises `BatchError`. Every image of a failed group is `None` in `error.results`, and `error.errors` has its index.

Each `dict`:

| Key | Type | Meaning |
|---|---|---|
| `masks` | `list[list[list[int]]]` | One item per detection. Each item is a list of polygons (an object can have several parts). Each polygon is a flat list `[x1, y1, x2, y2, ...]` in pixels. |
| `boxes` | `list[list[float]]` | One box per detection. |
| `scores` | `list[float]` | Confidence per detection, 0 to 1. |
| `labels` | `list[str]` | Which object of the prompt each detection is, for example `"vest"`. |
| `concepts` | `list[dict]` | Every object of the prompt with its count, for example `{"concept": "vest", "count": 2}`. `count` is `0` when the object was not found. |
| `dropped_concepts` | `list[str]` | Objects that were not used, because the prompt had more than 10. |
| `image_height`, `image_width` | `int` | Image size in pixels. |
| `saved_path` | `str` | Only when `export_to` is provided. |

`masks[i]`, `boxes[i]`, `scores[i]` and `labels[i]` are the same detection. Detections are grouped by object, in prompt order, and inside a group the highest score comes first.

```python
{"masks": [[[x1, y1, x2, y2, ...]], ...], "boxes": [[12.0, 30.5, 88.1, 140.2], ...],
 "scores": [0.94, 0.86], "labels": ["hard hat", "vest"],
 "concepts": [{"concept": "hard hat", "count": 1}, {"concept": "vest", "count": 1}, {"concept": "person", "count": 0}],
 "dropped_concepts": [], "image_height": 358, "image_width": 538}
```

The model finds what it can see. A prompt like `"no-vest"` finds nothing: find `person` and `vest`, then compare.

### `neuralhive.recognize(image_path)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `image_path` | `str` | Yes | Local image file path. |

Returns `list[list[float]]`: one embedding per detected face. Each embedding has **512** floats.

### `neuralhive.reidentify(image_path, model_id=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `image_path` | `str` | Yes | Local image file path. Best with an image of one person. |
| `model_id` | `str` | No | Target model identifier. |

Returns `dict`. Each list has one item per input image:

| Key | Shape | Meaning |
|---|---|---|
| `embeddings` | `[image][6][512]` floats | 6 feature vectors of 512 floats each. |
| `visibility_scores` | `[image][6]` floats | One visibility score per feature vector. |
| `masks` | `[image][5][96][32]` floats | 5 attention maps of 96×32. |

### `neuralhive.estimate_pose(image_path, export_to=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `image_path` | `str` | Yes | Local image file path. |
| `export_to` | `str` | No | Export directory path for pose-rendered image. |

Returns `dict`:

| Key | Type | Meaning |
|---|---|---|
| `keypoints` | `list[list[list[float]]]` | One item per person. Each person has **133** points as `[x, y]` in pixels, in COCO-WholeBody order (body, feet, face, hands). |
| `scores` | `list[list[float]]` | One item per person: 133 confidence values from 0 to 1. |
| `saved_path` | `str` or `None` | The rendered image path, or `None` when `export_to` is not provided. |

### `neuralhive.embed(text=None, image_path=None, model_id=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `text` | `str` | No | Text input. |
| `image_path` | `str` | No | Local image file path. |
| `model_id` | `str` | No | Target model identifier. |

Provide exactly one input: `text` or `image_path`. If `model_id` is not provided, the SDK uses the default `clip` model from your allowed models.

Returns `list[float]`, one embedding:

| Model task | Size | Inputs |
|---|---|---|
| `clip` | **1024** floats | `text` or `image_path`. Text and image embeddings are in the same space, so you can compare them. |
| `text_embeddings` | **384** floats | `text` only |

### `neuralhive.generate_text(prompt, model_id=None, image_paths=None, video_paths=None, system_prompt=None, enable_thinking=False)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `prompt` | `str` | Yes | Text prompt. |
| `model_id` | `str` | No | Target model identifier. |
| `image_paths` | `str` or `list[str]` | No | Local image file path(s). VLM models only. |
| `video_paths` | `str` or `list[str]` | No | Local video path(s) or public URL(s). VLM models only. |
| `system_prompt` | `str` | No | Optional system prompt. Only sent when the selected model is an SLM model. |
| `enable_thinking` | `bool` | No | Let a VLM model think before it answers. Slower and uses more tokens. Default `False`. VLM models only. |

If `model_id` is not provided, the SDK uses the default `vlm` model from your allowed models. `system_prompt` is only sent when the selected model is an `slm` model.

Returns `str`: the generated text.

### `neuralhive.analyze(text=None, image_paths=None, video_paths=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `text` | `str` | No | Text input. |
| `image_paths` | `str` or `list[str]` | No | Local image file path(s). |
| `video_paths` | `str` or `list[str]` | No | Local video path(s) or public URL(s). |

Provide at least one input: `text`, `image_paths`, or `video_paths`. Always uses the default `vlm` model.

Returns `str`: the model's answer.

### `neuralhive.generate_image(prompt, export_to=None, height=None, width=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `prompt` | `str` or `list[str]` | Yes | Text prompt, 1 to 3000 characters. A list makes one image per prompt, in parallel. |
| `export_to` | `str` | No | Export directory path. Filename comes from response URL. |
| `height` | `int` | No | Image height in pixels: 512 to 2048, and a multiple of 32. Default is 1024. |
| `width` | `int` | No | Image width in pixels: 512 to 2048, and a multiple of 32. Default is 1024. |

Long-running method. Raises `TaskFailedError` if the image cannot be generated.

Returns `dict` (a `list` of them for a list input):

```python
{"download_url": "https://...amazonaws.com/outputs/glm-image/<id>.jpg?...", "saved_path": "/path/to/output/<id>.jpg"}  # saved_path is None without export_to
```

### `neuralhive.edit_image(image_path, prompt, export_to=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `image_path` | `str` or `list[str]` | Yes | Local image file path. A list applies the same edit to every image, in parallel. |
| `prompt` | `str` | Yes | Text instruction for the edit, 1 to 3000 characters. Clear, specific edits work best (for example "change the red jacket to a dark blue jacket"). |
| `export_to` | `str` | No | Export directory path. Filename comes from response URL. |

Long-running method.

Returns `dict` with `download_url` (`str`, a `.jpg` link) and `saved_path` (`str` or `None`). A list input returns a list of them.

### `neuralhive.transcribe_audio(audio_path)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `audio_path` | `str` or `list[str]` | Yes | Local audio file path (WAV, FLAC, or MP3), or a list of paths. |

Long-running method.

Returns `str`: the transcript. A list input returns `list[str]`, in the same order.

### `neuralhive.read_text(file_path, export_to=None, task="ocr")`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `file_path` | `str` | Yes | Local image file path (JPEG or PNG). For PDF files, use `parse_document()`. |
| `export_to` | `str` | No | Export directory path. The text is saved as `ocr-result.txt`. |
| `task` | `str` | No | What to read: `ocr` (default, plain text), `table`, `formula`, `chart`, `spotting`, or `seal`. |

Returns `str`: the text read from the image, with lines separated by `\n`. When `export_to` is provided, returns the saved file path instead.

### `neuralhive.detect_layout(file_path, export_to=None, detection_threshold=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `file_path` | `str` | Yes | Local image file path (JPEG or PNG, at most 20 MB). PDF files are not supported. |
| `export_to` | `str` | No | Export directory path. The result is saved as `layout-detection-result.json`. |
| `detection_threshold` | `float` | No | Minimum score for a region, 0.05 to 0.95. Server default is 0.3. |

Returns `dict`:

```python
{
    "count": 3,                       # regions found on all pages
    "pages": [
        {
            "page": 1, "width": 810, "height": 1080, "count": 3,
            "detections": [
                {
                    "order": 1,                         # reading order
                    "label": "paragraph_title",         # region type, for example text, image, table
                    "score": 0.8022,                    # confidence, 0 to 1
                    "box": [94.43, 101.09, 534.75, 149.35],
                    "polygon_points": [[94, 101], [534, 101], [534, 149], [94, 149]],
                },
            ],
        },
    ],
    "saved_path": "/path/to/output/layout-detection-result.json",  # only with export_to
}
```

### `neuralhive.parse_document(file_path, export_to, parse_mode="page")`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `file_path` | `str` or `list[str]` | Yes | Local PDF or image file path (at most 2 GB), or a list of paths. Each file is its own job; a list runs in parallel. |
| `export_to` | `str` | Yes | Export directory path. The results are saved here. It is created if it does not exist. With a list, a file name that is already taken gets `_1`, `_2`, ... |
| `parse_mode` | `str` | No | `page` (default): each page is read as a whole. `region`: layout regions are found first, then each region is read. |

Long-running method. Raises `TaskFailedError` if the document cannot be parsed.

Returns `dict` (a `list` of them for a list input, in the same order):

| Key | Type | Meaning |
|---|---|---|
| `markdown_path` | `str` | Path of the saved Markdown file. Headings, text, and tables (as Markdown tables), with a `<!-- Page N -->` line before each page. |
| `page_count` | `int` | Number of pages. |

### `neuralhive.generate_3d(image_path, export_to=None)`

| Parameter | Type | Required | Description |
|---|---|---|---|
| `image_path` | `str` or `list[str]` | Yes | Local image file path. Use a photo of one object on a plain background. A list makes one 3D asset per image, in parallel. |
| `export_to` | `str` | No | Export directory path. Filename comes from response URL. |

Long-running method.

Returns `dict` with `download_url` (`str`, a `.glb` 3D model link) and `saved_path` (`str` or `None`). A list input returns a list of them.

## Error Handling

Every error the SDK raises is a subclass of `NeuralHiveError`, which is a subclass of `Exception`. Import the classes from `neuralhive`:

```python
from neuralhive import NeuralhiveClient, InvalidInputError, NeuralHiveError, ServiceUnavailableError, TaskFailedError

neuralhive = NeuralhiveClient()

try:
    result = neuralhive.generate_image("a lighthouse at sunset", height=1024, width=768)
except InvalidInputError as error:
    print("Fix the input:", error)            # not sent, not billed
except (ServiceUnavailableError, TaskFailedError) as error:
    print("Try again later:", error)
except NeuralHiveError as error:
    print("Other SDK error:", error)
```

| Problem | Likely Cause | Fix | Exception |
|---|---|---|---|
| API key not found | No configured key or environment variable. | Run `neuralhive configure` or set `NEURALHIVE_API_KEY`. | `AuthenticationError` |
| Authentication failed | The key is wrong or was revoked. | Create a new key and configure it again. | `AuthenticationError` |
| Access denied | The key is valid but not allowed to do this request. | Check your account and plan. | `PermissionDeniedError` |
| Invalid model id | The model is unavailable or typed incorrectly, or it does not support this method. | Call `neuralhive.list_models()` and use an allowed model with the right `task`. | `ModelNotFoundError` |
| No default model found | `model_id` was omitted, but no default model for that task is available to your API key. | Call `neuralhive.list_models()` or pass a specific `model_id` when the method supports it. | `ModelNotFoundError` |
| Invalid file path | The `image_path`, `file_path`, `audio_path`, `image_paths`, or `video_paths` value does not point to an accessible file. | Use an absolute or correct relative local path and confirm the file exists. | `InvalidInputError` |
| Invalid input | A value breaks a rule in [Limits and formats](#limits-and-formats), for example `height=500` or an unknown `parse_mode`. Checked before sending, so not billed. | Read the error message and fix the value. | `InvalidInputError` |
| Request rejected | The service could not use the input, for example no face was found, or the file is too large. | Check the input against [Limits and formats](#limits-and-formats). | `RequestError` |
| Service temporarily unavailable | The service cannot be reached, or the model was still starting after the SDK's retries. | Wait a minute and call the method again. | `ServiceUnavailableError` |
| Task did not complete | A long-running job failed on the server or did not finish in time. | Call the method again. | `TaskFailedError` |
| Export failed | The `export_to` directory cannot be created or written to. | Choose a writable export path. | `ExportError` |
| Some list items failed | A list call finished, but one or more items failed. | Read `error.errors` (index → exception) and use `error.results` for the finished items. | `BatchError` |

## Examples

### Generate image

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.generate_image(
    prompt="A clean product photo of a black running shoe",
    export_to="/absolute/path/to/output",
    height=1024,
    width=768,
)

print(result["download_url"])
print(result["saved_path"])
```

### Analyze image

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.analyze(
    image_paths="/absolute/path/to/image.jpg",
)

print(result)
```

### Parse document

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.parse_document(
    file_path="/absolute/path/to/report.pdf",
    export_to="/absolute/path/to/output",
)

print(result["page_count"])
with open(result["markdown_path"], encoding="utf-8") as f:
    print(f.read())
```

### Transcribe many audio files

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

transcripts = neuralhive.transcribe_audio(["/path/to/call1.wav", "/path/to/call2.mp3"])

for transcript in transcripts:
    print(transcript)
```

### Generate 3D asset

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.generate_3d(
    image_path="/absolute/path/to/image.jpg",
    export_to="/absolute/path/to/output",
)

print(result["download_url"])
print(result["saved_path"])
```
