async-task-api-client 0.1.0rc1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- async_task_api_client/__init__.py +4 -0
- async_task_api_client/_errors.py +294 -0
- async_task_api_client/_files.py +162 -0
- async_task_api_client/_generated.py +488 -0
- async_task_api_client/_http.py +617 -0
- async_task_api_client/_me.py +79 -0
- async_task_api_client/_services.py +140 -0
- async_task_api_client/_storage.py +527 -0
- async_task_api_client/_tasks.py +596 -0
- async_task_api_client/py.typed +0 -0
- async_task_api_client/raw.py +97 -0
- async_task_api_client-0.1.0rc1.dist-info/METADATA +465 -0
- async_task_api_client-0.1.0rc1.dist-info/RECORD +15 -0
- async_task_api_client-0.1.0rc1.dist-info/WHEEL +4 -0
- async_task_api_client-0.1.0rc1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: async-task-api-client
|
|
3
|
+
Version: 0.1.0-rc.1
|
|
4
|
+
Summary: Python SDK for AsyncTaskAPI: raw clients, sync and async.
|
|
5
|
+
License: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: httpx<1,>=0.23
|
|
9
|
+
Requires-Dist: typing-extensions<5,>=4.4
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# AsyncTaskAPI SDK (Python)
|
|
13
|
+
|
|
14
|
+
The Python SDK for AsyncTaskAPI: submit tasks to services, read their results, exchange files.
|
|
15
|
+
|
|
16
|
+
It is a **raw** SDK: one small client per resource, and each call is exactly one HTTP request. It never retries,
|
|
17
|
+
never polls and never picks a file strategy for you; that orchestration stays in your application.
|
|
18
|
+
|
|
19
|
+
| Client | Twin | What it does |
|
|
20
|
+
| --- | --- | --- |
|
|
21
|
+
| `MeClient` | `AsyncMeClient` | Who the token belongs to (the consumer), and which services it may call. |
|
|
22
|
+
| `ServicesClient` | `AsyncServicesClient` | The catalogue of services and their live contracts. |
|
|
23
|
+
| `TaskClient` | `AsyncTaskClient` | Submit, read and list the tasks of ONE service, typed by you. |
|
|
24
|
+
| `StorageClient` | `AsyncStorageClient` | Presigned uploads and downloads of files, and the transfers to and from S3. |
|
|
25
|
+
|
|
26
|
+
Plus two helpers, `is_finished(task)` and `ensure_succeeded(task)`, and the errors, all deriving from `SdkError`.
|
|
27
|
+
Everything is importable from `async_task_api_client` (or, identically, `async_task_api_client.raw`).
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
Python 3.10 or later. The SDK depends only on `httpx` (`>=0.23,<1`) and `typing_extensions` (`>=4.4,<5`).
|
|
32
|
+
|
|
33
|
+
It is published on PyPI as `async-task-api-client` (the release candidates too: add `--pre` to pip, or
|
|
34
|
+
`--prerelease allow` to uv, to get them):
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
pip install async-task-api-client
|
|
38
|
+
# or, in a uv project
|
|
39
|
+
uv add async-task-api-client
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Its sources live in the AsyncTaskAPI repository, under `sdk/async-task-api-client/python/`.
|
|
43
|
+
|
|
44
|
+
## Creating a client
|
|
45
|
+
|
|
46
|
+
Every client takes the same keyword arguments: `base_url` (the AsyncTaskAPI instance; a trailing slash is
|
|
47
|
+
ignored), `token` (the consumer's personal access token), and optionally `http_client` and `timeout` (see below).
|
|
48
|
+
`TaskClient` also takes `service`, the name of the service it is bound to.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import os
|
|
52
|
+
|
|
53
|
+
from async_task_api_client import MeClient
|
|
54
|
+
|
|
55
|
+
base_url = "https://async-task-api.example.org"
|
|
56
|
+
token = os.environ["ASYNC_TASK_API_TOKEN"]
|
|
57
|
+
|
|
58
|
+
with MeClient(base_url=base_url, token=token) as client:
|
|
59
|
+
me = client.get()
|
|
60
|
+
|
|
61
|
+
print(me["client_id"])
|
|
62
|
+
for authorization in me["authorizations"]:
|
|
63
|
+
# `service` may be the literal "all", meaning every service.
|
|
64
|
+
print(authorization["service"], authorization.get("quotas"))
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The other examples assume `base_url` and `token` defined as above.
|
|
68
|
+
|
|
69
|
+
The token is sent as `Authorization: Bearer <token>` on each API request. It is never set on the HTTP client, so it
|
|
70
|
+
never reaches S3 nor any other host.
|
|
71
|
+
|
|
72
|
+
### Sync and async twins
|
|
73
|
+
|
|
74
|
+
Every client has an asynchronous twin, with the same name prefixed by `Async`, the same methods and the same
|
|
75
|
+
arguments. Close it with `await client.aclose()` or `async with`:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
import asyncio
|
|
79
|
+
|
|
80
|
+
from async_task_api_client import AsyncServicesClient
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
async def main() -> None:
|
|
84
|
+
async with AsyncServicesClient(base_url=base_url, token=token) as services:
|
|
85
|
+
for service in await services.list():
|
|
86
|
+
print(service["name"], service.get("class"))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
asyncio.run(main())
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Closing, and injecting your own `httpx` client
|
|
93
|
+
|
|
94
|
+
A client without `http_client` creates its own `httpx.Client` (`httpx.AsyncClient` for a twin) and closes it with
|
|
95
|
+
`close()` (`aclose()`) or at the end of the `with` (`async with`) block. Calling a closed client raises
|
|
96
|
+
`ClientClosedError` (also a `RuntimeError`) and sends nothing.
|
|
97
|
+
|
|
98
|
+
Inject your own HTTP client to add a proxy, logging, a shared connection pool or a test double. The SDK never
|
|
99
|
+
modifies nor closes it: you own its lifecycle, and closing an SDK client that uses it does nothing.
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
import httpx
|
|
103
|
+
|
|
104
|
+
from async_task_api_client import ServicesClient, TaskClient
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def log_request(request: httpx.Request) -> None:
|
|
108
|
+
print(request.method, request.url)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
with httpx.Client(timeout=10.0, event_hooks={"request": [log_request]}) as http_client:
|
|
112
|
+
services = ServicesClient(base_url=base_url, token=token, http_client=http_client)
|
|
113
|
+
ocr = TaskClient(base_url=base_url, token=token, service="core-ocr", http_client=http_client)
|
|
114
|
+
detail = services.get("core-ocr")
|
|
115
|
+
task = ocr.create({"language": "fr"})
|
|
116
|
+
# `http_client` was closed by its own `with`, not by the SDK.
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Presigned transfers to and from S3 go through the same HTTP client (its transport, proxy and event hooks run), but
|
|
120
|
+
carry exactly the presigned URL and its signed headers: none of the HTTP client's default headers, query
|
|
121
|
+
parameters, cookies or `auth` reach S3.
|
|
122
|
+
|
|
123
|
+
## Services
|
|
124
|
+
|
|
125
|
+
Services are added to AsyncTaskAPI dynamically, so the SDK knows none of them: a service is a plain name. List the
|
|
126
|
+
catalogue, then read a service's live contract (its input and result JSON Schemas, its file fields) at runtime, to
|
|
127
|
+
build a form or an agent tool description:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from async_task_api_client import ServicesClient
|
|
131
|
+
|
|
132
|
+
with ServicesClient(base_url=base_url, token=token) as services:
|
|
133
|
+
for summary in services.list():
|
|
134
|
+
# `class` is the service class: "immediate", "short" or "long".
|
|
135
|
+
print(summary["name"], summary.get("title"), summary.get("class"), summary.get("files_enabled"))
|
|
136
|
+
detail = services.get("generation-render")
|
|
137
|
+
|
|
138
|
+
input_schema = detail.get("input_schema") # JSON Schema of the input, or None
|
|
139
|
+
output_schema = detail.get("output_schema") # JSON Schema of the result, or None
|
|
140
|
+
file_fields = detail.get("file_fields", []) # the input fields that take a file
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
An unknown service raises `ApiError` with `code == "SERVICE_NOT_FOUND"`.
|
|
144
|
+
|
|
145
|
+
## Tasks
|
|
146
|
+
|
|
147
|
+
A `TaskClient` is bound to ONE service. `create` submits a task and returns it, whether it is still running or
|
|
148
|
+
already finished; `get` reads its current state. The SDK does not poll: loop on `get` yourself (or receive a
|
|
149
|
+
callback) until `is_finished`.
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
import time
|
|
153
|
+
|
|
154
|
+
from async_task_api_client import TaskClient, ensure_succeeded, is_finished
|
|
155
|
+
|
|
156
|
+
with TaskClient(base_url=base_url, token=token, service="generation-render") as render:
|
|
157
|
+
# `wait=10`: the API may hold its answer up to 10 seconds, until the task ends.
|
|
158
|
+
task = render.create({"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10)
|
|
159
|
+
while not is_finished(task):
|
|
160
|
+
time.sleep(1)
|
|
161
|
+
task = render.get(task["task_id"])
|
|
162
|
+
|
|
163
|
+
print(ensure_succeeded(task)["result"]) # raises TaskFailedError if the task failed
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
`create` also takes `callback` (where the API sends the task's final state) and `session_id`, a session label: a
|
|
167
|
+
free label grouping your tasks so you can list them later, for instance after a restart. It grants no right.
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
from async_task_api_client import TaskClient
|
|
171
|
+
|
|
172
|
+
with TaskClient(base_url=base_url, token=token, service="generation-render") as render:
|
|
173
|
+
render.create(
|
|
174
|
+
{"template": "Hello {{ name }}", "data": {"name": "Dupont"}},
|
|
175
|
+
callback={"type": "http", "url": "https://my-app.example.org/hooks/async-task"},
|
|
176
|
+
session_id="case-42",
|
|
177
|
+
)
|
|
178
|
+
page = render.list(session_id="case-42", status=["pending", "in_progress"], limit=50)
|
|
179
|
+
|
|
180
|
+
for summary in page["tasks"]: # most recent first, without input nor result
|
|
181
|
+
print(summary["task_id"], summary["status"], summary.get("progress"))
|
|
182
|
+
print(page["count"], page["limit"], page["offset"])
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Task states
|
|
186
|
+
|
|
187
|
+
A task is a dict discriminated on `status`: `pending`, `in_progress`, `success` or `failure`. Narrow on
|
|
188
|
+
`task["status"]` to reach each state's fields. A failed task is a normal outcome, returned as data, never raised by
|
|
189
|
+
the clients:
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
from async_task_api_client import Task
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def describe(task: Task) -> str:
|
|
196
|
+
if task["status"] == "success":
|
|
197
|
+
return f"done: {task['result']}"
|
|
198
|
+
if task["status"] == "failure":
|
|
199
|
+
error = task.get("error") # match on error["code"], which is stable
|
|
200
|
+
return f"failed: {error['code'] if error else task['error_message']}"
|
|
201
|
+
if task["status"] == "in_progress":
|
|
202
|
+
return f"running: {task.get('progress')}"
|
|
203
|
+
return f"queued at position {task.get('task_position')}"
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
`is_finished(task)` narrows a task to a `FinishedTask` (`success` or `failure`). It is a `TypeGuard`, so its `else`
|
|
207
|
+
branch keeps the plain `Task` type: narrow on `task["status"]` there. `ensure_succeeded(task)` returns the task as
|
|
208
|
+
succeeded, its `result` typed, or raises `TaskFailedError` (with `task_id`, `code` and the failed `task`); it raises
|
|
209
|
+
a plain `SdkError` for a task that is still running.
|
|
210
|
+
|
|
211
|
+
### Typing a service's input and result
|
|
212
|
+
|
|
213
|
+
The SDK never checks a service's input nor its result. By default the input is a `dict[str, Any]` and the result
|
|
214
|
+
`Any`; state your own types as `TaskClient[Input, Result]`:
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
from typing import TypedDict
|
|
218
|
+
|
|
219
|
+
from async_task_api_client import TaskClient, ensure_succeeded
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class RenderInput(TypedDict):
|
|
223
|
+
template: str
|
|
224
|
+
data: dict[str, str]
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class RenderOutput(TypedDict):
|
|
228
|
+
text: str
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
with TaskClient[RenderInput, RenderOutput](base_url=base_url, token=token, service="generation-render") as render:
|
|
232
|
+
task = render.create({"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10)
|
|
233
|
+
|
|
234
|
+
if task["status"] == "success":
|
|
235
|
+
print(task["result"]["text"]) # typed `str`
|
|
236
|
+
|
|
237
|
+
# Or annotate the variable:
|
|
238
|
+
client: TaskClient[RenderInput, RenderOutput] = TaskClient(base_url=base_url, token=token, service="generation-render")
|
|
239
|
+
text: str = ensure_succeeded(client.get("t-1"))["result"]["text"]
|
|
240
|
+
client.close()
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Gotcha: annotating the variable does **not** work with `with`. After `render: TaskClient[RenderInput, RenderOutput]`,
|
|
244
|
+
`with TaskClient(...) as render:` is refused by the type checker: the types do not flow through `__enter__`, which
|
|
245
|
+
returns a client with the default types. With `with`, parametrize the class:
|
|
246
|
+
`with TaskClient[RenderInput, RenderOutput](...) as render:`.
|
|
247
|
+
|
|
248
|
+
## Files
|
|
249
|
+
|
|
250
|
+
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
|
|
251
|
+
(72 hours once attached to a task). A file is never sent with the task: upload it beforehand with a presigned upload,
|
|
252
|
+
then put its file id in the service's file field of the input (`file_fields` of `ServicesClient.get`).
|
|
253
|
+
|
|
254
|
+
### Presigned upload (up to 500 MiB)
|
|
255
|
+
|
|
256
|
+
Reserve a file id, upload the file straight to S3 (one `PUT`, without your token), then put the file id in a task's
|
|
257
|
+
input. From a path, the SDK reads the name, MIME type and size from disk and `upload()` streams that file; from a
|
|
258
|
+
description (`filename`, `mime_type`, `size_bytes`), `upload(file)` takes the content.
|
|
259
|
+
|
|
260
|
+
```python
|
|
261
|
+
from async_task_api_client import StorageClient, TaskClient
|
|
262
|
+
|
|
263
|
+
with (
|
|
264
|
+
StorageClient(base_url=base_url, token=token) as storage,
|
|
265
|
+
TaskClient(base_url=base_url, token=token, service="core-ocr") as ocr,
|
|
266
|
+
):
|
|
267
|
+
upload = storage.presigned_upload("./scans/scan.pdf")
|
|
268
|
+
upload.upload() # streamed from disk
|
|
269
|
+
task = ocr.create({"file_id": upload.file_id})
|
|
270
|
+
|
|
271
|
+
content = b"%PDF-1.7 ..."
|
|
272
|
+
reserved = storage.presigned_upload(
|
|
273
|
+
{"filename": "scan.pdf", "mime_type": "application/pdf", "size_bytes": len(content)}
|
|
274
|
+
)
|
|
275
|
+
reserved.upload(content) # bytes, a binary stream or a path, exactly `size_bytes` long
|
|
276
|
+
task = ocr.create({"file_id": reserved.file_id})
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
A seekable stream is sent from its start, whatever its position: calling `upload` again after a failure sends the
|
|
280
|
+
whole file. A stream that cannot seek (a pipe) is sent from its current position.
|
|
281
|
+
|
|
282
|
+
Upload before `expires_at`. S3 refusing the transfer (expired URL, size or type not matching) raises
|
|
283
|
+
`StorageTransferError`.
|
|
284
|
+
|
|
285
|
+
### Presigned download
|
|
286
|
+
|
|
287
|
+
A succeeded task lists its input and output files in `files`. Ask for a short-lived download URL, then fetch the
|
|
288
|
+
bytes into memory with `download()`, or stream them to disk with `save_to(path)`:
|
|
289
|
+
|
|
290
|
+
```python
|
|
291
|
+
from async_task_api_client import StorageClient, TaskClient, ensure_succeeded
|
|
292
|
+
|
|
293
|
+
with (
|
|
294
|
+
StorageClient(base_url=base_url, token=token) as storage,
|
|
295
|
+
TaskClient(base_url=base_url, token=token, service="generation-render") as render,
|
|
296
|
+
):
|
|
297
|
+
task = ensure_succeeded(render.get("t-1"))
|
|
298
|
+
for file in task.get("files", []):
|
|
299
|
+
if file["role"] == "output":
|
|
300
|
+
storage.presigned_download(file["file_id"]).save_to(f"./out/{file['name']}")
|
|
301
|
+
|
|
302
|
+
content: bytes = storage.presigned_download("f_0123456789abcdef").download()
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
The URL is valid an hour by default. To hand it to a third party, ask for a shorter-lived one with
|
|
306
|
+
`expires_in_seconds` (from 60 s up to the default validity, unless the instance is configured otherwise): the bounds
|
|
307
|
+
are the API's, and a value out of them raises `ApiError` `PRESIGNED_TTL_OUT_OF_RANGE`.
|
|
308
|
+
|
|
309
|
+
```python
|
|
310
|
+
from async_task_api_client import StorageClient
|
|
311
|
+
|
|
312
|
+
with StorageClient(base_url=base_url, token=token) as storage:
|
|
313
|
+
url = storage.presigned_download("f_0123456789abcdef", expires_in_seconds=300).url # valid five minutes
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
`save_to` writes the file whole or not at all: it streams to a temporary file next to `path`, then renames it over
|
|
317
|
+
`path`. On failure or cancellation (S3 refusal, network error, full disk, `task.cancel()`), `path` is either untouched
|
|
318
|
+
or the complete file, never a partial one, and no temporary file remains: a cancellation landing during the final
|
|
319
|
+
rename lets it finish, and still propagates. The directory must exist.
|
|
320
|
+
|
|
321
|
+
## Errors
|
|
322
|
+
|
|
323
|
+
Every error raised by the SDK derives from `SdkError`:
|
|
324
|
+
|
|
325
|
+
| Error | Raised when |
|
|
326
|
+
| --- | --- |
|
|
327
|
+
| `ApiError` | The API answered an error: match on its stable `code` (`status`, `message`, plus `issues` on 422 and `components` on 503). |
|
|
328
|
+
| `AuthenticationError` | The token is missing or refused (`401`, usually from the gateway: `code` is then `None`). |
|
|
329
|
+
| `UnexpectedResponseError` | An answer the SDK cannot read (an HTML page from a proxy, a success that is not JSON...). |
|
|
330
|
+
| `StorageTransferError` | S3 refused a presigned transfer. |
|
|
331
|
+
| `TaskFailedError` | `ensure_succeeded` met a failed task (never raised by the clients). |
|
|
332
|
+
| `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). |
|
|
333
|
+
| `RequestTimeoutError` | A timeout; a `TransportError`, and also the builtin `TimeoutError`. |
|
|
334
|
+
| `ClientClosedError` | A call on a closed client; also a `RuntimeError`. |
|
|
335
|
+
|
|
336
|
+
`TransportError` and `RequestTimeoutError` keep the httpx exception as `__cause__`: you never need to import httpx to
|
|
337
|
+
catch errors. Invalid arguments caught before sending raise `ValueError` or `TypeError` (an empty task id, a `wait`
|
|
338
|
+
outside 0..60, a file that is neither a path nor a tuple), and an unreadable path an `SdkError` naming it.
|
|
339
|
+
|
|
340
|
+
Nothing is ever retried, so a task is never created twice. After a `RequestTimeoutError` on `create`, the task may
|
|
341
|
+
or may not have been created: give a `session_id` to be able to find it with `list`.
|
|
342
|
+
|
|
343
|
+
```python
|
|
344
|
+
from async_task_api_client import (
|
|
345
|
+
ApiError,
|
|
346
|
+
AuthenticationError,
|
|
347
|
+
RequestTimeoutError,
|
|
348
|
+
SdkError,
|
|
349
|
+
TaskClient,
|
|
350
|
+
TaskFailedError,
|
|
351
|
+
TransportError,
|
|
352
|
+
ensure_succeeded,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
with TaskClient(base_url=base_url, token=token, service="generation-render") as render:
|
|
356
|
+
try:
|
|
357
|
+
task = render.create(
|
|
358
|
+
{"template": "Hello {{ name }}", "data": {"name": "Dupont"}}, wait=10, session_id="case-42"
|
|
359
|
+
)
|
|
360
|
+
print(ensure_succeeded(task)["result"])
|
|
361
|
+
except TaskFailedError as error:
|
|
362
|
+
print("The task failed:", error.task_id, error.code)
|
|
363
|
+
except AuthenticationError:
|
|
364
|
+
print("Check ASYNC_TASK_API_TOKEN")
|
|
365
|
+
except ApiError as error:
|
|
366
|
+
if error.code == "REQUEST_VALIDATION_ERROR":
|
|
367
|
+
for issue in error.issues or []:
|
|
368
|
+
print(issue["loc"], issue["msg"])
|
|
369
|
+
elif error.code == "CLIENT_SERVICE_QUOTA_EXCEEDED":
|
|
370
|
+
print("Too many running tasks, try later")
|
|
371
|
+
else:
|
|
372
|
+
raise
|
|
373
|
+
except RequestTimeoutError:
|
|
374
|
+
print("No answer in time: the task may exist, look for it with list(session_id='case-42')")
|
|
375
|
+
except TransportError as error:
|
|
376
|
+
print("Network failure:", error.__cause__)
|
|
377
|
+
except SdkError as error:
|
|
378
|
+
print("Still running, or another SDK error:", error)
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
## Timeouts and cancellation
|
|
382
|
+
|
|
383
|
+
Every method takes a `timeout` keyword, in seconds, and every client a default `timeout`. A call's `timeout`
|
|
384
|
+
overrides the client's, which overrides the HTTP client's own (5 seconds for httpx's default client). `None`
|
|
385
|
+
disables the timeout, as in httpx; leaving the argument out defers to the next level.
|
|
386
|
+
|
|
387
|
+
```python
|
|
388
|
+
from async_task_api_client import MeClient, TaskClient
|
|
389
|
+
|
|
390
|
+
with MeClient(base_url=base_url, token=token, timeout=30) as client:
|
|
391
|
+
me = client.get() # 30 seconds
|
|
392
|
+
me = client.get(timeout=2) # 2 seconds
|
|
393
|
+
me = client.get(timeout=None) # no timeout at all
|
|
394
|
+
|
|
395
|
+
with TaskClient(base_url=base_url, token=token, service="generation-render") as render:
|
|
396
|
+
task = render.create({"template": "Hi"}, wait=20) # read timeout raised to 25 seconds, see below
|
|
397
|
+
task = render.create({"template": "Hi"}, wait=20, timeout=30) # your timeout, kept as is
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
`wait` and `timeout`: when you gave the SDK no timeout (neither on the call nor on the client), a `create` with
|
|
401
|
+
`wait=N` raises the HTTP client's read timeout to `N + 5` seconds when it is shorter, so that the API can hold its
|
|
402
|
+
answer; the connect, write and pool timeouts are kept. A timeout you give, `None` included, is never changed: make
|
|
403
|
+
it longer than `wait`.
|
|
404
|
+
|
|
405
|
+
Async calls are cancelled with asyncio's own tools: `task.cancel()`, `asyncio.wait_for`, or `asyncio.timeout()` on
|
|
406
|
+
Python 3.11+. The SDK never wraps `asyncio.CancelledError`.
|
|
407
|
+
|
|
408
|
+
```python
|
|
409
|
+
import asyncio
|
|
410
|
+
|
|
411
|
+
from async_task_api_client import AsyncMeClient
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
async def main() -> None:
|
|
415
|
+
async with AsyncMeClient(base_url=base_url, token=token) as client:
|
|
416
|
+
me = await asyncio.wait_for(client.get(), timeout=5)
|
|
417
|
+
print(me["client_id"])
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
asyncio.run(main())
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
## Differences from the TypeScript SDK
|
|
424
|
+
|
|
425
|
+
Both SDKs share the same concepts (the same clients, errors and raw semantics), not the same shapes: where the
|
|
426
|
+
TypeScript form is not idiomatic Python, the Python form wins.
|
|
427
|
+
|
|
428
|
+
- `create` returns the task itself, narrowed with `is_finished` or on `status`, instead of a `{finished, task}` pair.
|
|
429
|
+
- Calls take a `timeout` in seconds, and async calls are cancelled the asyncio way, instead of an `AbortSignal`.
|
|
430
|
+
- Transport failures are wrapped in `TransportError` / `RequestTimeoutError` instead of leaking the HTTP library's
|
|
431
|
+
own errors; a closed client raises `ClientClosedError`.
|
|
432
|
+
- Every client exists twice, synchronous and asynchronous (`TaskClient` / `AsyncTaskClient`).
|
|
433
|
+
- Names follow PEP 8 (`presigned_upload`, `save_to`, `ensure_succeeded`), and `presigned_download` takes the file
|
|
434
|
+
id as a plain string, and `expires_in_seconds` as a keyword.
|
|
435
|
+
|
|
436
|
+
## Development
|
|
437
|
+
|
|
438
|
+
The project is managed with [uv](https://docs.astral.sh/uv/), on Python 3.10 (the supported floor). From the
|
|
439
|
+
repository root:
|
|
440
|
+
|
|
441
|
+
```sh
|
|
442
|
+
make client-py-install # install the SDK and the dev tools (locked)
|
|
443
|
+
make client-py-test # unit tests with the coverage floor, no network
|
|
444
|
+
make client-py-typecheck # ty on src/, scripts/ and tests/, including the type-level tests (tests/typecheck/)
|
|
445
|
+
make client-py-lint # ruff check and format check
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
The tests also type-check this README's Python examples with ty.
|
|
449
|
+
|
|
450
|
+
The API types in `src/async_task_api_client/_generated.py` are generated from the API's OpenAPI document
|
|
451
|
+
(`docs/protocol/openapi.json` at the repository root, itself generated from the API code by `make openapi`) and
|
|
452
|
+
committed; never edit them by hand. After the document changed, regenerate them and review the diff:
|
|
453
|
+
|
|
454
|
+
```sh
|
|
455
|
+
make client-py-generate
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
A test fails when the committed types drift from the spec.
|
|
459
|
+
|
|
460
|
+
To check the lowest supported dependency versions:
|
|
461
|
+
|
|
462
|
+
```sh
|
|
463
|
+
uv run --isolated --no-project --python 3.10 --with-editable . --with httpx==0.23.0 \
|
|
464
|
+
--with typing_extensions==4.4.0 --with pytest==8.2.0 --with pytest-asyncio==0.24.0 pytest
|
|
465
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
async_task_api_client/__init__.py,sha256=qOUcKsUewrX-YbOf6MNTek3SNAFgoTZAXjJ8Jj-ECVU,160
|
|
2
|
+
async_task_api_client/_errors.py,sha256=F9KcstwFS7oDInGOhB8c219h_1ZKKlfu9i3M6YfOqeM,11081
|
|
3
|
+
async_task_api_client/_files.py,sha256=7b-EvfnCm77uEkgyWUu388S2jsvxRUrvB7t2d8cp9zI,6550
|
|
4
|
+
async_task_api_client/_generated.py,sha256=j6mA-0yUmgZYExe5ToQDXI30dxEBQpJ1rKRbEvGkZxA,12917
|
|
5
|
+
async_task_api_client/_http.py,sha256=XiCNmS4ichaRCNX6W49RgDXLwKegA8zJJq2AK7Wqplo,26248
|
|
6
|
+
async_task_api_client/_me.py,sha256=srME0XoAMd7OyCjhI0JzRdbm-X2idk8mtebsN7Vrveo,2723
|
|
7
|
+
async_task_api_client/_services.py,sha256=7jIpRO9SYNdmSpFaFYfFNCyZhxu7CCuzAYxTRpqQFz0,5560
|
|
8
|
+
async_task_api_client/_storage.py,sha256=jx8-TEPQwz2JM2oHovq2woCt1_rtHIIQHlC4TZB1-PA,23619
|
|
9
|
+
async_task_api_client/_tasks.py,sha256=t85Vhxef6srTofWkhzxjbdrB43_8bNRzzdPV6QT4QbM,25575
|
|
10
|
+
async_task_api_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
async_task_api_client/raw.py,sha256=JhnR0imvLk28C_1PzfSua3ChyP-KQeuY9fQYEb5uq_4,2093
|
|
12
|
+
async_task_api_client-0.1.0rc1.dist-info/METADATA,sha256=XFGpAnLYwD2KrzPIi5Y1H1fl4nGyv-PcPBJSj5ClZQE,20014
|
|
13
|
+
async_task_api_client-0.1.0rc1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
+
async_task_api_client-0.1.0rc1.dist-info/licenses/LICENSE,sha256=k2aXAfQBeC9nvfsSD9EFZLTdAbG5gqJFr2tRS0jLKgQ,1070
|
|
15
|
+
async_task_api_client-0.1.0rc1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 IA-Generative
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|