Metadata-Version: 2.3
Name: woodwide
Version: 0.9.0
Summary: The official Python library for the wood-wide API
Project-URL: Homepage, https://github.com/Wood-Wide-AI/wwai-python-sdk
Project-URL: Repository, https://github.com/Wood-Wide-AI/wwai-python-sdk
Author: Wood Wide
License: Apache-2.0
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: OS Independent
Classifier: Operating System :: POSIX
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: anyio<5,>=3.5.0
Requires-Dist: distro<2,>=1.7.0
Requires-Dist: httpx<1,>=0.23.0
Requires-Dist: pydantic<3,>=1.9.0
Requires-Dist: sniffio
Requires-Dist: typing-extensions<5,>=4.14
Provides-Extra: aiohttp
Requires-Dist: aiohttp; extra == 'aiohttp'
Requires-Dist: httpx-aiohttp>=0.1.9; extra == 'aiohttp'
Description-Content-Type: text/markdown

# Wood Wide Python SDK

<!-- prettier-ignore -->
[![PyPI version](https://img.shields.io/pypi/v/woodwide.svg?label=pypi%20(stable))](https://pypi.org/project/woodwide/)

The Wood Wide Python SDK provides typed access to the Wood Wide API from Python 3.9 or later. It includes:

- High-level workflow helpers for dataset ingestion, model training, batch inference, result retrieval, and data connection imports.
- Typed resource clients for direct access to every documented API endpoint.
- Synchronous and asynchronous interfaces powered by [httpx](https://github.com/encode/httpx).

The resource clients and request and response models are generated with [Stainless](https://www.stainless.com/). The workflow helpers compose those generated methods into common multi-step operations.

## Documentation

- [High-level helpers and API reference](https://github.com/Wood-Wide-AI/wwai-python-sdk/tree/main/api.md)
- [Wood Wide documentation](https://docs.woodwide.ai/)

## Installation

```sh
# install from PyPI
pip install woodwide
```

## Quick start

Set the `WOODWIDE_API_KEY` environment variable, then create a client. Passing `api_key` explicitly is also supported.

```python
from woodwide import WoodWide

client = WoodWide()

jobs = client.jobs.list()
print(jobs.items)
```

For local development, [python-dotenv](https://pypi.org/project/python-dotenv/) can load `WOODWIDE_API_KEY` from a `.env` file. Do not commit API keys to source control.

## High-level workflow helpers

High-level workflow helpers compose common API operations. Helpers that monitor jobs return only after the job succeeds; they raise `RuntimeError` if it fails, is rejected, or is canceled, and `TimeoutError` if it exceeds the configured timeout. Transfer and result-iteration helpers expose HTTP and argument errors appropriate to their operations.

All helpers can be imported directly from `woodwide`:

| Workflow | Synchronous helper | Asynchronous helper |
| --- | --- | --- |
| Wait for any job | `wait_for_job` | `async_wait_for_job` |
| Wait for training | `wait_for_training` | `async_wait_for_training` |
| Upload and ingest a dataset | `ingest_dataset` | `async_ingest_dataset` |
| Ingest a large dataset by signed URL | `ingest_large_dataset` | `async_ingest_large_dataset` |
| Train a model | `train_model` | `async_train_model` |
| Run batch inference | `infer_batch_and_wait` | `async_infer_batch_and_wait` |
| Download job results | `download_job_results` | `async_download_job_results` |
| Iterate through result rows | `iter_result_rows` | `async_iter_result_rows` |
| Import connection data | `import_connection_data` | `async_import_connection_data` |

### Ingest, train, and infer

The following example runs a complete synchronous workflow. Each operation waits for its job to succeed before returning.

```python
from pathlib import Path

from woodwide import WoodWide
from woodwide import download_job_results
from woodwide import infer_batch_and_wait
from woodwide import ingest_dataset
from woodwide import train_model

client = WoodWide()

dataset = ingest_dataset(
    client,
    file=Path("customers.csv"),
    dataset_name="customers",
)

model = train_model(
    client,
    model_type="anomaly",
    dataset_id=dataset.submission.id,
)

inference = infer_batch_and_wait(
    client,
    model.submission.id,
    dataset_id=dataset.submission.id,
    output_type="parquet",
)

download_job_results(
    client,
    inference.job.id,
    "customer_anomalies.parquet",
)
```

Workflow results retain both the initial API response and the completed job. For example, `TrainModelResult.submission` is the original `ModelTrainResponse`, while `TrainModelResult.job` is the successful `JobDetail` returned after polling.

### Ingest large files

Use `ingest_large_dataset` when a file should be uploaded directly to object storage instead of sent through the multipart dataset endpoint. The helper prepares a signed upload, streams the file, signals completion, and waits for ingestion.

```python
from pathlib import Path

from woodwide import WoodWide, ingest_large_dataset

client = WoodWide()

dataset = ingest_large_dataset(
    client,
    file=Path("large_dataset.parquet"),
    dataset_name="large-dataset",
)

print(dataset.submission.id)
print(dataset.job.status)
```

Paths and seekable binary file objects are streamed. If the filename cannot be inferred, provide `filename`; if the MIME type cannot be inferred, provide `content_type`.

### Iterate through result rows

`iter_result_rows` handles offset pagination and yields one row at a time. The API supports pages of up to 500 rows.

```python
from woodwide import WoodWide, iter_result_rows

client = WoodWide()

for row in iter_result_rows(
    client,
    "job_A8K2P9QX",
    columns=["id", "anomaly_score"],
    page_size=500,
):
    print(row)
```

### Import data from a connection

`import_connection_data` supports table, query, and object imports from an existing data connection.

```python
from woodwide import WoodWide, import_connection_data

client = WoodWide()

result = import_connection_data(
    client,
    "conn_A8K2P9QX",
    mode="table",
    table_schema="public",
    table_name="customers",
    dataset_name="warehouse-customers",
)

print(result.submission.dataset_id)
```

### Wait for an existing job

Submission endpoints return job IDs for asynchronous work. Pass the job ID—not a model or dataset ID—to `wait_for_job` or `wait_for_training`.

```python
from woodwide import WoodWide, wait_for_job

client = WoodWide()
job = wait_for_job(client, "job_A8K2P9QX", timeout=1800, poll_interval=5)
print(job.status)
```

`timeout` is the maximum total time to wait. `poll_interval` controls the delay between job status requests.

## Async usage

Use `AsyncWoodWide` with the `async_` workflow helpers. Asynchronous row iteration uses `async for`.

```python
import asyncio
from pathlib import Path

from woodwide import AsyncWoodWide
from woodwide import async_ingest_dataset


async def main() -> None:
    async with AsyncWoodWide() as client:
        dataset = await async_ingest_dataset(
            client,
            file=Path("customers.csv"),
            dataset_name="customers",
        )
        print(dataset.submission.id)


asyncio.run(main())
```

The synchronous and asynchronous clients expose the same generated resources and parameters.

### With aiohttp

By default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend.

You can enable this by installing `aiohttp`:

```sh
# install from PyPI
pip install woodwide[aiohttp]
```

Then instantiate the client with `http_client=DefaultAioHttpClient()`:

```python
import asyncio

from woodwide import AsyncWoodWide, DefaultAioHttpClient


async def main() -> None:
    async with AsyncWoodWide(
        http_client=DefaultAioHttpClient(),
    ) as client:
        jobs = await client.jobs.list()
        print(jobs.items)


asyncio.run(main())
```

## Direct API access

Use resource methods when you need direct control over individual HTTP operations. These methods return immediately after the corresponding endpoint responds; asynchronous server work can then be monitored with `wait_for_job`.

```python
from pathlib import Path

from woodwide import WoodWide, wait_for_job

client = WoodWide()

submission = client.datasets.create(
    file=Path("customers.csv"),
    dataset_name="customers",
)

if submission.job_id is not None:
    job = wait_for_job(client, submission.job_id)
    print(job.status)
```

See [api.md](https://github.com/Wood-Wide-AI/wwai-python-sdk/tree/main/api.md) for every generated resource method and response type.

### Request and response types

Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like:

- Serializing back into JSON, `model.to_json()`
- Converting to a dictionary, `model.to_dict()`

Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.

### Nested request parameters

Nested parameters are dictionaries, typed using `TypedDict`, for example:

```python
from woodwide import WoodWide

client = WoodWide()

response = client.datasets.upload(
    file={
        "bytes": 1048576,
        "content_type": "text/csv",
        "filename": "customers.csv",
    },
)
print(response.upload.upload_url)
```

This low-level call only prepares a signed upload. The application must still upload the file to `response.upload.upload_url` and call `client.datasets.complete(response.version_id)`. Use `ingest_large_dataset` to manage that complete workflow automatically.

### File parameters

Request parameters that correspond to file uploads can be passed as `bytes`, or a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`.

```python
from pathlib import Path
from woodwide import WoodWide

client = WoodWide()

client.datasets.create(file=Path("customers.csv"))
```

The asynchronous client accepts the same values and reads `PathLike` inputs asynchronously. For large files, prefer `ingest_large_dataset` or `async_ingest_large_dataset` so file bytes are sent directly to object storage.

## Handling errors

When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `woodwide.APIConnectionError` is raised.

When the API returns a non-success status code (that is, 4xx or 5xx), a subclass of `woodwide.APIStatusError` is raised. The exception includes `status_code` and `response` properties.

All errors inherit from `woodwide.APIError`.

```python
import woodwide
from woodwide import WoodWide

client = WoodWide()

try:
    client.jobs.list()
except woodwide.APIConnectionError as exc:
    print("The server could not be reached")
    print(exc.__cause__)  # The underlying exception, commonly raised by httpx.
except woodwide.RateLimitError:
    print("A 429 status code was received; we should back off a bit.")
except woodwide.APIStatusError as exc:
    print("Another non-200-range status code was received")
    print(exc.status_code)
    print(exc.response)
```

Error codes are as follows:

| Status Code | Error Type                 |
| ----------- | -------------------------- |
| 400         | `BadRequestError`          |
| 401         | `AuthenticationError`      |
| 403         | `PermissionDeniedError`    |
| 404         | `NotFoundError`            |
| 422         | `UnprocessableEntityError` |
| 429         | `RateLimitError`           |
| >=500       | `InternalServerError`      |
| N/A         | `APIConnectionError`       |

### Retries

Certain errors are automatically retried twice by default with a short exponential backoff. Connection errors, HTTP 408 Request Timeout, HTTP 409 Conflict, HTTP 429 Rate Limit, and HTTP 5xx server errors are retried.

You can use the `max_retries` option to configure or disable retry settings:

```python
from woodwide import WoodWide

# Configure the default for all requests:
client = WoodWide(
    # default is 2
    max_retries=0,
)

# Or, configure per-request:
client.with_options(max_retries=5).jobs.list()
```

### Timeouts

By default requests time out after 60 seconds. You can configure this with a `timeout` option,
which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object:

```python
import httpx

from woodwide import WoodWide

# Configure the default for all requests:
client = WoodWide(
    # 20 seconds (default is 1 minute)
    timeout=20.0,
)

# More granular control:
client = WoodWide(
    timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)

# Override per-request:
client.with_options(timeout=5.0).jobs.list()
```

On timeout, the SDK raises `APITimeoutError`.

Note that requests that time out are [retried twice by default](https://github.com/Wood-Wide-AI/wwai-python-sdk/tree/main/#retries).

## Advanced

### Logging

We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.

You can enable logging by setting the environment variable `WOODWIDE_LOG` to `info`.

```sh
export WOODWIDE_LOG=info
```

Or to `debug` for more verbose logging.

### How to tell whether `None` means `null` or missing

In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`:

```python
if response.my_field is None:
    if "my_field" not in response.model_fields_set:
        print('Received JSON without a "my_field" property.')
    else:
        print('Received JSON with "my_field": null.')
```

### Accessing raw response data (e.g. headers)

Access the raw response by prefixing an HTTP method call with `.with_raw_response`:

```python
from woodwide import WoodWide

client = WoodWide()
response = client.jobs.with_raw_response.list()
print(response.headers.get("X-My-Header"))

job = response.parse()  # get the object that `jobs.list()` would have returned
print(job.items)
```

These methods return an [`APIResponse`](https://github.com/Wood-Wide-AI/wwai-python-sdk/tree/main/src/woodwide/_response.py) object.

The async client returns an [`AsyncAPIResponse`](https://github.com/Wood-Wide-AI/wwai-python-sdk/tree/main/src/woodwide/_response.py) with the same structure, the only difference being `await`able methods for reading the response content.

#### `.with_streaming_response`

The above interface eagerly reads the full response body when you make the request, which may not always be what you want.

To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.

```python
with client.jobs.with_streaming_response.list() as response:
    print(response.headers.get("X-My-Header"))

    for line in response.iter_lines():
        print(line)
```

The context manager is required so that the response will reliably be closed.

### Making custom/undocumented requests

This library is typed for convenient access to the documented API.

If you need to access undocumented endpoints, params, or response properties, the library can still be used.

#### Undocumented endpoints

Use `client.get`, `client.post`, and the other HTTP methods to call endpoints that are not represented by generated resources. Client options such as retries are applied to these requests.

```python
import httpx

response = client.post(
    "/foo",
    cast_to=httpx.Response,
    body={"my_param": True},
)

print(response.headers.get("x-foo"))
```

#### Undocumented request params

Use the `extra_query`, `extra_body`, and `extra_headers` request options to send parameters that are not represented by a generated method signature.

#### Undocumented response properties

Undocumented response properties are available as attributes such as `response.unknown_prop`. They are also available as a dictionary through [`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).

### Configuring the HTTP client

You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:

- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)
- Custom [transports](https://www.python-httpx.org/advanced/transports/)
- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality

```python
import httpx
from woodwide import WoodWide, DefaultHttpxClient

client = WoodWide(
    # Or use the `WOODWIDE_BASE_URL` env var
    base_url="http://my.test.server.example.com:8083",
    http_client=DefaultHttpxClient(
        proxy="http://my.test.proxy.example.com",
        transport=httpx.HTTPTransport(local_address="0.0.0.0"),
    ),
)
```

You can also customize the client on a per-request basis by using `with_options()`:

```python
client.with_options(http_client=DefaultHttpxClient(...))
```

### Managing HTTP resources

By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.

```python
from woodwide import WoodWide

with WoodWide() as client:
    # Make requests here.
    ...

# HTTP client is now closed
```

## Versioning

This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:

1. Changes that only affect static types, without breaking runtime behavior.
2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_
3. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an [issue](https://www.github.com/Wood-Wide-AI/wwai-python-sdk/issues) with questions, bugs, or suggestions.

### Determining the installed version

If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.

You can determine the version that is being used at runtime with:

```python
import woodwide

print(woodwide.__version__)
```

## Requirements

Python 3.9 or higher.

## Contributing

See [the contributing documentation](https://github.com/Wood-Wide-AI/wwai-python-sdk/tree/main/./CONTRIBUTING.md).
