Metadata-Version: 2.5
Name: async-task-api-client
Version: 0.1.0-rc.1
Summary: Python SDK for AsyncTaskAPI: raw clients, sync and async.
License: MIT
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.23
Requires-Dist: typing-extensions<5,>=4.4
Description-Content-Type: text/markdown

# AsyncTaskAPI SDK (Python)

The Python SDK for AsyncTaskAPI: submit tasks to services, read their results, exchange files.

It is a **raw** SDK: one small client per resource, and each call is exactly one HTTP request. It never retries,
never polls and never picks a file strategy for you; that orchestration stays in your application.

| Client | Twin | What it does |
| --- | --- | --- |
| `MeClient` | `AsyncMeClient` | Who the token belongs to (the consumer), and which services it may call. |
| `ServicesClient` | `AsyncServicesClient` | The catalogue of services and their live contracts. |
| `TaskClient` | `AsyncTaskClient` | Submit, read and list the tasks of ONE service, typed by you. |
| `StorageClient` | `AsyncStorageClient` | Presigned uploads and downloads of files, and the transfers to and from S3. |

Plus two helpers, `is_finished(task)` and `ensure_succeeded(task)`, and the errors, all deriving from `SdkError`.
Everything is importable from `async_task_api_client` (or, identically, `async_task_api_client.raw`).

## Installation

Python 3.10 or later. The SDK depends only on `httpx` (`>=0.23,<1`) and `typing_extensions` (`>=4.4,<5`).

It is published on PyPI as `async-task-api-client` (the release candidates too: add `--pre` to pip, or
`--prerelease allow` to uv, to get them):

```sh
pip install async-task-api-client
# or, in a uv project
uv add async-task-api-client
```

Its sources live in the AsyncTaskAPI repository, under `sdk/async-task-api-client/python/`.

## Creating a client

Every client takes the same keyword arguments: `base_url` (the AsyncTaskAPI instance; a trailing slash is
ignored), `token` (the consumer's personal access token), and optionally `http_client` and `timeout` (see below).
`TaskClient` also takes `service`, the name of the service it is bound to.

```python
import os

from async_task_api_client import MeClient

base_url = "https://async-task-api.example.org"
token = os.environ["ASYNC_TASK_API_TOKEN"]

with MeClient(base_url=base_url, token=token) as client:
    me = client.get()

print(me["client_id"])
for authorization in me["authorizations"]:
    # `service` may be the literal "all", meaning every service.
    print(authorization["service"], authorization.get("quotas"))
```

The other examples assume `base_url` and `token` defined as above.

The token is sent as `Authorization: Bearer <token>` on each API request. It is never set on the HTTP client, so it
never reaches S3 nor any other host.

### Sync and async twins

Every client has an asynchronous twin, with the same name prefixed by `Async`, the same methods and the same
arguments. Close it with `await client.aclose()` or `async with`:

```python
import asyncio

from async_task_api_client import AsyncServicesClient


async def main() -> None:
    async with AsyncServicesClient(base_url=base_url, token=token) as services:
        for service in await services.list():
            print(service["name"], service.get("class"))


asyncio.run(main())
```

### Closing, and injecting your own `httpx` client

A client without `http_client` creates its own `httpx.Client` (`httpx.AsyncClient` for a twin) and closes it with
`close()` (`aclose()`) or at the end of the `with` (`async with`) block. Calling a closed client raises
`ClientClosedError` (also a `RuntimeError`) and sends nothing.

Inject your own HTTP client to add a proxy, logging, a shared connection pool or a test double. The SDK never
modifies nor closes it: you own its lifecycle, and closing an SDK client that uses it does nothing.

```python
import httpx

from async_task_api_client import ServicesClient, TaskClient


def log_request(request: httpx.Request) -> None:
    print(request.method, request.url)


with httpx.Client(timeout=10.0, event_hooks={"request": [log_request]}) as http_client:
    services = ServicesClient(base_url=base_url, token=token, http_client=http_client)
    ocr = TaskClient(base_url=base_url, token=token, service="core-ocr", http_client=http_client)
    detail = services.get("core-ocr")
    task = ocr.create({"language": "fr"})
# `http_client` was closed by its own `with`, not by the SDK.
```

Presigned transfers to and from S3 go through the same HTTP client (its transport, proxy and event hooks run), but
carry exactly the presigned URL and its signed headers: none of the HTTP client's default headers, query
parameters, cookies or `auth` reach S3.

## Services

Services are added to AsyncTaskAPI dynamically, so the SDK knows none of them: a service is a plain name. List the
catalogue, then read a service's live contract (its input and result JSON Schemas, its file fields) at runtime, to
build a form or an agent tool description:

```python
from async_task_api_client import ServicesClient

with ServicesClient(base_url=base_url, token=token) as services:
    for summary in services.list():
        # `class` is the service class: "immediate", "short" or "long".
        print(summary["name"], summary.get("title"), summary.get("class"), summary.get("files_enabled"))
    detail = services.get("generation-render")

input_schema = detail.get("input_schema")  # JSON Schema of the input, or None
output_schema = detail.get("output_schema")  # JSON Schema of the result, or None
file_fields = detail.get("file_fields", [])  # the input fields that take a file
```

An unknown service raises `ApiError` with `code == "SERVICE_NOT_FOUND"`.

## Tasks

A `TaskClient` is bound to ONE service. `create` submits a task and returns it, whether it is still running or
already finished; `get` reads its current state. The SDK does not poll: loop on `get` yourself (or receive a
callback) until `is_finished`.

```python
import time

from async_task_api_client import TaskClient, ensure_succeeded, is_finished

with TaskClient(base_url=base_url, token=token, service="generation-render") as render:
    # `wait=10`: the API may hold its answer up to 10 seconds, until the task ends.
    task = render.create({"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10)
    while not is_finished(task):
        time.sleep(1)
        task = render.get(task["task_id"])

print(ensure_succeeded(task)["result"])  # raises TaskFailedError if the task failed
```

`create` also takes `callback` (where the API sends the task's final state) and `session_id`, a session label: a
free label grouping your tasks so you can list them later, for instance after a restart. It grants no right.

```python
from async_task_api_client import TaskClient

with TaskClient(base_url=base_url, token=token, service="generation-render") as render:
    render.create(
        {"template": "Hello {{ name }}", "data": {"name": "Dupont"}},
        callback={"type": "http", "url": "https://my-app.example.org/hooks/async-task"},
        session_id="case-42",
    )
    page = render.list(session_id="case-42", status=["pending", "in_progress"], limit=50)

for summary in page["tasks"]:  # most recent first, without input nor result
    print(summary["task_id"], summary["status"], summary.get("progress"))
print(page["count"], page["limit"], page["offset"])
```

### Task states

A task is a dict discriminated on `status`: `pending`, `in_progress`, `success` or `failure`. Narrow on
`task["status"]` to reach each state's fields. A failed task is a normal outcome, returned as data, never raised by
the clients:

```python
from async_task_api_client import Task


def describe(task: Task) -> str:
    if task["status"] == "success":
        return f"done: {task['result']}"
    if task["status"] == "failure":
        error = task.get("error")  # match on error["code"], which is stable
        return f"failed: {error['code'] if error else task['error_message']}"
    if task["status"] == "in_progress":
        return f"running: {task.get('progress')}"
    return f"queued at position {task.get('task_position')}"
```

`is_finished(task)` narrows a task to a `FinishedTask` (`success` or `failure`). It is a `TypeGuard`, so its `else`
branch keeps the plain `Task` type: narrow on `task["status"]` there. `ensure_succeeded(task)` returns the task as
succeeded, its `result` typed, or raises `TaskFailedError` (with `task_id`, `code` and the failed `task`); it raises
a plain `SdkError` for a task that is still running.

### Typing a service's input and result

The SDK never checks a service's input nor its result. By default the input is a `dict[str, Any]` and the result
`Any`; state your own types as `TaskClient[Input, Result]`:

```python
from typing import TypedDict

from async_task_api_client import TaskClient, ensure_succeeded


class RenderInput(TypedDict):
    template: str
    data: dict[str, str]


class RenderOutput(TypedDict):
    text: str


with TaskClient[RenderInput, RenderOutput](base_url=base_url, token=token, service="generation-render") as render:
    task = render.create({"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10)

if task["status"] == "success":
    print(task["result"]["text"])  # typed `str`

# Or annotate the variable:
client: TaskClient[RenderInput, RenderOutput] = TaskClient(base_url=base_url, token=token, service="generation-render")
text: str = ensure_succeeded(client.get("t-1"))["result"]["text"]
client.close()
```

Gotcha: annotating the variable does **not** work with `with`. After `render: TaskClient[RenderInput, RenderOutput]`,
`with TaskClient(...) as render:` is refused by the type checker: the types do not flow through `__enter__`, which
returns a client with the default types. With `with`, parametrize the class:
`with TaskClient[RenderInput, RenderOutput](...) as render:`.

## Files

A file is referenced only by its file id (`f_<hex>`); a file id is single-use, and files are kept for a limited time
(72 hours once attached to a task). A file is never sent with the task: upload it beforehand with a presigned upload,
then put its file id in the service's file field of the input (`file_fields` of `ServicesClient.get`).

### Presigned upload (up to 500 MiB)

Reserve a file id, upload the file straight to S3 (one `PUT`, without your token), then put the file id in a task's
input. From a path, the SDK reads the name, MIME type and size from disk and `upload()` streams that file; from a
description (`filename`, `mime_type`, `size_bytes`), `upload(file)` takes the content.

```python
from async_task_api_client import StorageClient, TaskClient

with (
    StorageClient(base_url=base_url, token=token) as storage,
    TaskClient(base_url=base_url, token=token, service="core-ocr") as ocr,
):
    upload = storage.presigned_upload("./scans/scan.pdf")
    upload.upload()  # streamed from disk
    task = ocr.create({"file_id": upload.file_id})

    content = b"%PDF-1.7 ..."
    reserved = storage.presigned_upload(
        {"filename": "scan.pdf", "mime_type": "application/pdf", "size_bytes": len(content)}
    )
    reserved.upload(content)  # bytes, a binary stream or a path, exactly `size_bytes` long
    task = ocr.create({"file_id": reserved.file_id})
```

A seekable stream is sent from its start, whatever its position: calling `upload` again after a failure sends the
whole file. A stream that cannot seek (a pipe) is sent from its current position.

Upload before `expires_at`. S3 refusing the transfer (expired URL, size or type not matching) raises
`StorageTransferError`.

### Presigned download

A succeeded task lists its input and output files in `files`. Ask for a short-lived download URL, then fetch the
bytes into memory with `download()`, or stream them to disk with `save_to(path)`:

```python
from async_task_api_client import StorageClient, TaskClient, ensure_succeeded

with (
    StorageClient(base_url=base_url, token=token) as storage,
    TaskClient(base_url=base_url, token=token, service="generation-render") as render,
):
    task = ensure_succeeded(render.get("t-1"))
    for file in task.get("files", []):
        if file["role"] == "output":
            storage.presigned_download(file["file_id"]).save_to(f"./out/{file['name']}")

    content: bytes = storage.presigned_download("f_0123456789abcdef").download()
```

The URL is valid an hour by default. To hand it to a third party, ask for a shorter-lived one with
`expires_in_seconds` (from 60 s up to the default validity, unless the instance is configured otherwise): the bounds
are the API's, and a value out of them raises `ApiError` `PRESIGNED_TTL_OUT_OF_RANGE`.

```python
from async_task_api_client import StorageClient

with StorageClient(base_url=base_url, token=token) as storage:
    url = storage.presigned_download("f_0123456789abcdef", expires_in_seconds=300).url  # valid five minutes
```

`save_to` writes the file whole or not at all: it streams to a temporary file next to `path`, then renames it over
`path`. On failure or cancellation (S3 refusal, network error, full disk, `task.cancel()`), `path` is either untouched
or the complete file, never a partial one, and no temporary file remains: a cancellation landing during the final
rename lets it finish, and still propagates. The directory must exist.

## Errors

Every error raised by the SDK derives from `SdkError`:

| Error | Raised when |
| --- | --- |
| `ApiError` | The API answered an error: match on its stable `code` (`status`, `message`, plus `issues` on 422 and `components` on 503). |
| `AuthenticationError` | The token is missing or refused (`401`, usually from the gateway: `code` is then `None`). |
| `UnexpectedResponseError` | An answer the SDK cannot read (an HTML page from a proxy, a success that is not JSON...). |
| `StorageTransferError` | S3 refused a presigned transfer. |
| `TaskFailedError` | `ensure_succeeded` met a failed task (never raised by the clients). |
| `TransportError` | No answer: DNS, refused or broken connection, invalid `base_url`, a streamed body httpx cannot send again (a redirect followed by an injected client). |
| `RequestTimeoutError` | A timeout; a `TransportError`, and also the builtin `TimeoutError`. |
| `ClientClosedError` | A call on a closed client; also a `RuntimeError`. |

`TransportError` and `RequestTimeoutError` keep the httpx exception as `__cause__`: you never need to import httpx to
catch errors. Invalid arguments caught before sending raise `ValueError` or `TypeError` (an empty task id, a `wait`
outside 0..60, a file that is neither a path nor a tuple), and an unreadable path an `SdkError` naming it.

Nothing is ever retried, so a task is never created twice. After a `RequestTimeoutError` on `create`, the task may
or may not have been created: give a `session_id` to be able to find it with `list`.

```python
from async_task_api_client import (
    ApiError,
    AuthenticationError,
    RequestTimeoutError,
    SdkError,
    TaskClient,
    TaskFailedError,
    TransportError,
    ensure_succeeded,
)

with TaskClient(base_url=base_url, token=token, service="generation-render") as render:
    try:
        task = render.create(
            {"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10, session_id="case-42"
        )
        print(ensure_succeeded(task)["result"])
    except TaskFailedError as error:
        print("The task failed:", error.task_id, error.code)
    except AuthenticationError:
        print("Check ASYNC_TASK_API_TOKEN")
    except ApiError as error:
        if error.code == "REQUEST_VALIDATION_ERROR":
            for issue in error.issues or []:
                print(issue["loc"], issue["msg"])
        elif error.code == "CLIENT_SERVICE_QUOTA_EXCEEDED":
            print("Too many running tasks, try later")
        else:
            raise
    except RequestTimeoutError:
        print("No answer in time: the task may exist, look for it with list(session_id='case-42')")
    except TransportError as error:
        print("Network failure:", error.__cause__)
    except SdkError as error:
        print("Still running, or another SDK error:", error)
```

## Timeouts and cancellation

Every method takes a `timeout` keyword, in seconds, and every client a default `timeout`. A call's `timeout`
overrides the client's, which overrides the HTTP client's own (5 seconds for httpx's default client). `None`
disables the timeout, as in httpx; leaving the argument out defers to the next level.

```python
from async_task_api_client import MeClient, TaskClient

with MeClient(base_url=base_url, token=token, timeout=30) as client:
    me = client.get()  # 30 seconds
    me = client.get(timeout=2)  # 2 seconds
    me = client.get(timeout=None)  # no timeout at all

with TaskClient(base_url=base_url, token=token, service="generation-render") as render:
    task = render.create({"template": "Hi"}, wait=20)  # read timeout raised to 25 seconds, see below
    task = render.create({"template": "Hi"}, wait=20, timeout=30)  # your timeout, kept as is
```

`wait` and `timeout`: when you gave the SDK no timeout (neither on the call nor on the client), a `create` with
`wait=N` raises the HTTP client's read timeout to `N + 5` seconds when it is shorter, so that the API can hold its
answer; the connect, write and pool timeouts are kept. A timeout you give, `None` included, is never changed: make
it longer than `wait`.

Async calls are cancelled with asyncio's own tools: `task.cancel()`, `asyncio.wait_for`, or `asyncio.timeout()` on
Python 3.11+. The SDK never wraps `asyncio.CancelledError`.

```python
import asyncio

from async_task_api_client import AsyncMeClient


async def main() -> None:
    async with AsyncMeClient(base_url=base_url, token=token) as client:
        me = await asyncio.wait_for(client.get(), timeout=5)
        print(me["client_id"])


asyncio.run(main())
```

## Differences from the TypeScript SDK

Both SDKs share the same concepts (the same clients, errors and raw semantics), not the same shapes: where the
TypeScript form is not idiomatic Python, the Python form wins.

- `create` returns the task itself, narrowed with `is_finished` or on `status`, instead of a `{finished, task}` pair.
- Calls take a `timeout` in seconds, and async calls are cancelled the asyncio way, instead of an `AbortSignal`.
- Transport failures are wrapped in `TransportError` / `RequestTimeoutError` instead of leaking the HTTP library's
  own errors; a closed client raises `ClientClosedError`.
- Every client exists twice, synchronous and asynchronous (`TaskClient` / `AsyncTaskClient`).
- Names follow PEP 8 (`presigned_upload`, `save_to`, `ensure_succeeded`), and `presigned_download` takes the file
  id as a plain string, and `expires_in_seconds` as a keyword.

## Development

The project is managed with [uv](https://docs.astral.sh/uv/), on Python 3.10 (the supported floor). From the
repository root:

```sh
make client-py-install         # install the SDK and the dev tools (locked)
make client-py-test            # unit tests with the coverage floor, no network
make client-py-typecheck       # ty on src/, scripts/ and tests/, including the type-level tests (tests/typecheck/)
make client-py-lint            # ruff check and format check
```

The tests also type-check this README's Python examples with ty.

The API types in `src/async_task_api_client/_generated.py` are generated from the API's OpenAPI document
(`docs/protocol/openapi.json` at the repository root, itself generated from the API code by `make openapi`) and
committed; never edit them by hand. After the document changed, regenerate them and review the diff:

```sh
make client-py-generate
```

A test fails when the committed types drift from the spec.

To check the lowest supported dependency versions:

```sh
uv run --isolated --no-project --python 3.10 --with-editable . --with httpx==0.23.0 \
  --with typing_extensions==4.4.0 --with pytest==8.2.0 --with pytest-asyncio==0.24.0 pytest
```
