zilapi 0.5.0__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.
zilapi/__init__.py ADDED
@@ -0,0 +1,109 @@
1
+ """Official typed Python clients for ZilAPI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._client import AsyncZilAPI, ZilAPI
6
+ from ._version import __version__
7
+ from .errors import (
8
+ APIConnectionError,
9
+ APIResponseValidationError,
10
+ APIStatusError,
11
+ APITimeoutError,
12
+ AuthenticationError,
13
+ BadRequestError,
14
+ ConflictError,
15
+ FileRejectedError,
16
+ FileTooLargeError,
17
+ GoneError,
18
+ IncompleteDownloadError,
19
+ InsufficientCreditError,
20
+ InternalServerError,
21
+ JobFailedError,
22
+ NotFoundError,
23
+ PermissionDeniedError,
24
+ RateLimitError,
25
+ UnprocessableEntityError,
26
+ UnsupportedMediaTypeError,
27
+ UploadError,
28
+ WaitTimeoutError,
29
+ ZilAPIError,
30
+ )
31
+ from .resources.images import AsyncBackgroundRemoval, BackgroundRemoval
32
+ from .types import (
33
+ Credits,
34
+ CursorPage,
35
+ File,
36
+ FileError,
37
+ FileStatus,
38
+ FillerReport,
39
+ FillerSegment,
40
+ Job,
41
+ JobCost,
42
+ JobError,
43
+ JobInput,
44
+ JobOutput,
45
+ JobOutputFile,
46
+ JobPayment,
47
+ JobReceipt,
48
+ JobResult,
49
+ JobStatus,
50
+ Me,
51
+ Model,
52
+ ModelLimits,
53
+ ModelOutput,
54
+ ModelPricing,
55
+ OutputLink,
56
+ )
57
+
58
+ __all__ = [
59
+ "APIConnectionError",
60
+ "APIResponseValidationError",
61
+ "APIStatusError",
62
+ "APITimeoutError",
63
+ "AsyncBackgroundRemoval",
64
+ "AsyncZilAPI",
65
+ "AuthenticationError",
66
+ "BackgroundRemoval",
67
+ "BadRequestError",
68
+ "ConflictError",
69
+ "Credits",
70
+ "CursorPage",
71
+ "File",
72
+ "FileError",
73
+ "FileRejectedError",
74
+ "FileStatus",
75
+ "FileTooLargeError",
76
+ "FillerReport",
77
+ "FillerSegment",
78
+ "GoneError",
79
+ "IncompleteDownloadError",
80
+ "InsufficientCreditError",
81
+ "InternalServerError",
82
+ "Job",
83
+ "JobCost",
84
+ "JobError",
85
+ "JobFailedError",
86
+ "JobInput",
87
+ "JobOutput",
88
+ "JobOutputFile",
89
+ "JobPayment",
90
+ "JobReceipt",
91
+ "JobResult",
92
+ "JobStatus",
93
+ "Me",
94
+ "Model",
95
+ "ModelLimits",
96
+ "ModelOutput",
97
+ "ModelPricing",
98
+ "NotFoundError",
99
+ "OutputLink",
100
+ "PermissionDeniedError",
101
+ "RateLimitError",
102
+ "UnprocessableEntityError",
103
+ "UnsupportedMediaTypeError",
104
+ "UploadError",
105
+ "WaitTimeoutError",
106
+ "ZilAPI",
107
+ "ZilAPIError",
108
+ "__version__",
109
+ ]
zilapi/_base.py ADDED
@@ -0,0 +1,283 @@
1
+ """Shared policy and transformations, without transport or filesystem IO."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import math
7
+ import platform
8
+ import random
9
+ import re
10
+ from collections.abc import Callable, Mapping
11
+ from datetime import datetime, timezone
12
+ from email.utils import parsedate_to_datetime
13
+ from pathlib import PurePath
14
+ from typing import Any, TypeVar
15
+ from urllib.parse import quote
16
+ from uuid import uuid4
17
+
18
+ import httpx
19
+
20
+ from . import errors
21
+ from ._version import __version__
22
+
23
+ MAX_RETRY_AFTER = 60
24
+ T = TypeVar("T")
25
+ logger = logging.getLogger("zilapi")
26
+ _SIGNED_QUERY = re.compile(r"(?i)(signature|x-amz-credential|x-amz-security-token|token|sig)=")
27
+
28
+
29
+ class _RedactSignedURLs(logging.Filter):
30
+ """Strip query strings that carry signatures from httpx's own request log lines."""
31
+
32
+ def filter(self, record: logging.LogRecord) -> bool:
33
+ if isinstance(record.args, tuple) and record.args:
34
+ record.args = tuple(_redact(arg) for arg in record.args)
35
+ return True
36
+
37
+
38
+ def _redact(value: Any) -> Any:
39
+ if isinstance(value, (httpx.URL, str)):
40
+ text = str(value)
41
+ if "?" in text and _SIGNED_QUERY.search(text.split("?", 1)[1]):
42
+ return text.split("?", 1)[0] + "?[redacted]"
43
+ return value
44
+
45
+
46
+ def install_log_redaction() -> None:
47
+ """Add the redaction filter to httpx's loggers once (idempotent)."""
48
+ for name in ("httpx", "httpcore"):
49
+ target = logging.getLogger(name)
50
+ if not any(isinstance(f, _RedactSignedURLs) for f in target.filters):
51
+ target.addFilter(_RedactSignedURLs())
52
+
53
+
54
+ USER_AGENT = f"zilapi-python/{__version__} python/{platform.python_version()} httpx/{httpx.__version__}"
55
+ STATUS_ERRORS: dict[int, type[errors.APIStatusError]] = {
56
+ 400: errors.BadRequestError,
57
+ 401: errors.AuthenticationError,
58
+ 402: errors.InsufficientCreditError,
59
+ 403: errors.PermissionDeniedError,
60
+ 404: errors.NotFoundError,
61
+ 409: errors.ConflictError,
62
+ 410: errors.GoneError,
63
+ 413: errors.FileTooLargeError,
64
+ 415: errors.UnsupportedMediaTypeError,
65
+ 422: errors.UnprocessableEntityError,
66
+ 429: errors.RateLimitError,
67
+ }
68
+ CONTENT_TYPES = {
69
+ ".wav": "audio/wav",
70
+ ".mp3": "audio/mpeg",
71
+ ".m4a": "audio/mp4",
72
+ ".mp4": "video/mp4",
73
+ ".aac": "audio/aac",
74
+ ".flac": "audio/flac",
75
+ ".ogg": "audio/ogg",
76
+ ".oga": "audio/ogg",
77
+ ".opus": "audio/opus",
78
+ ".webm": "audio/webm",
79
+ ".aif": "audio/aiff",
80
+ ".aiff": "audio/aiff",
81
+ ".caf": "audio/x-caf",
82
+ ".amr": "audio/amr",
83
+ ".mka": "audio/x-matroska",
84
+ ".mkv": "video/x-matroska",
85
+ ".mov": "video/quicktime",
86
+ ".wv": "audio/wavpack",
87
+ ".png": "image/png",
88
+ ".jpg": "image/jpeg",
89
+ ".jpeg": "image/jpeg",
90
+ ".webp": "image/webp",
91
+ }
92
+
93
+
94
+ class Multipart:
95
+ """A multipart/form-data body held in memory, so a retried request resends the same bytes."""
96
+
97
+ def __init__(self, data: Mapping[str, str], files: Mapping[str, tuple[str, bytes, str]]) -> None:
98
+ self.data = dict(data)
99
+ self.files = dict(files)
100
+
101
+
102
+ MISSING_KEY = (
103
+ "Missing API key: pass api_key or set the ZILAPI_KEY environment variable "
104
+ "(ZILAPI_API_KEY, the older name, also works)"
105
+ )
106
+
107
+
108
+ def resolve_config(api_key: str | None, base_url: str | None, env: Mapping[str, str]) -> tuple[str, str]:
109
+ # ZILAPI_KEY is the name the docs use; ZILAPI_API_KEY is the older name and still read when it is unset.
110
+ key = (env.get("ZILAPI_KEY") or env.get("ZILAPI_API_KEY")) if api_key is None else api_key
111
+ if not key:
112
+ raise errors.ZilAPIError(MISSING_KEY)
113
+ base = (base_url or env.get("ZILAPI_BASE_URL") or "https://api.zilapi.com").rstrip("/")
114
+ # The host only: request paths already start with /v1, so a copied ".../v1" base is trimmed too.
115
+ if base.lower().endswith("/v1"):
116
+ base = base[:-3].rstrip("/")
117
+ return key, base
118
+
119
+
120
+ def timeout_value(timeout: float | httpx.Timeout) -> httpx.Timeout:
121
+ return timeout if isinstance(timeout, httpx.Timeout) else httpx.Timeout(timeout, connect=min(10, timeout))
122
+
123
+
124
+ def api_headers(key: str, defaults: Mapping[str, str] | None) -> httpx.Headers:
125
+ headers = httpx.Headers(defaults)
126
+ headers.update({"Authorization": f"Bearer {key}", "Accept": "application/json", "User-Agent": USER_AGENT})
127
+ return headers
128
+
129
+
130
+ def idempotency_key(value: str | None, *, max_length: int = 255) -> str:
131
+ key = str(uuid4()) if value is None else value
132
+ if not key or len(key) > max_length:
133
+ raise ValueError(f"idempotency_key must contain 1 to {max_length} characters")
134
+ return key
135
+
136
+
137
+ def segment(value: str) -> str:
138
+ # Dot-only segments must not be normalized by the URL parser.
139
+ return quote(value, safe="").replace(".", "%2E") if value in (".", "..") else quote(value, safe="")
140
+
141
+
142
+ def model_path(model_id: str) -> str:
143
+ if model_id.count("/") != 1:
144
+ raise ValueError("model_id must have exactly one '/' (provider/model)")
145
+ provider, model = model_id.split("/")
146
+ return f"/v1/models/{segment(provider)}/{segment(model)}"
147
+
148
+
149
+ def content_type_for(filename: str, content_type: str | None) -> str:
150
+ result = content_type or CONTENT_TYPES.get(PurePath(filename).suffix.lower())
151
+ if not result:
152
+ raise ValueError("Unknown extension; provide content_type explicitly")
153
+ return result
154
+
155
+
156
+ def retry_after(headers: Mapping[str, str]) -> float | None:
157
+ value = headers.get("Retry-After")
158
+ if value is None:
159
+ return None
160
+ try:
161
+ seconds = float(value)
162
+ except ValueError:
163
+ try:
164
+ date = parsedate_to_datetime(value)
165
+ if date.tzinfo is None:
166
+ date = date.replace(tzinfo=timezone.utc)
167
+ seconds = (date - datetime.now(timezone.utc)).total_seconds()
168
+ except (ValueError, TypeError, OverflowError):
169
+ return None
170
+ return max(0, seconds) if math.isfinite(seconds) else None
171
+
172
+
173
+ def retry_delay(attempt: int, response: httpx.Response | None = None) -> float | None:
174
+ if response is not None:
175
+ if response.status_code != 429 and not 500 <= response.status_code <= 599:
176
+ return None
177
+ after = retry_after(response.headers)
178
+ if after is not None:
179
+ return after if after <= MAX_RETRY_AFTER else None
180
+ ceiling = min(8.0, 0.5 * 2 ** min(attempt, 5))
181
+ return random.uniform(ceiling / 2, ceiling) # noqa: S311 - jitter is not cryptographic
182
+
183
+
184
+ def is_safe(method: str, headers: httpx.Headers) -> bool:
185
+ return method == "GET" or (method == "POST" and "Idempotency-Key" in headers)
186
+
187
+
188
+ def status_error(response: httpx.Response, *, storage: bool = False) -> errors.APIStatusError:
189
+ body: Any
190
+ if storage:
191
+ # Storage error bodies can echo the signed request; never keep them.
192
+ body = f"Storage request failed with HTTP {response.status_code}"
193
+ else:
194
+ try:
195
+ body = response.json()
196
+ except ValueError:
197
+ body = response.text
198
+ cls = STATUS_ERRORS.get(
199
+ response.status_code,
200
+ errors.InternalServerError if response.status_code >= 500 else errors.APIStatusError,
201
+ )
202
+ headers = httpx.Headers({"X-Request-Id": response.headers.get("X-Request-Id", "")}) if storage else None
203
+ error = cls(status=response.status_code, body=body, headers=headers or response.headers)
204
+ if isinstance(error, errors.RateLimitError):
205
+ error.retry_after = retry_after(response.headers)
206
+ return error
207
+
208
+
209
+ class ResponseBody(dict[str, Any]):
210
+ """A decoded success body that remembers its status and headers for error reporting."""
211
+
212
+ status: int = 200
213
+ headers: httpx.Headers = httpx.Headers()
214
+
215
+
216
+ def success_body(response: httpx.Response) -> ResponseBody:
217
+ """Decode a successful API response, turning non-JSON bodies into SDK errors."""
218
+ if not response.content and response.status_code == 204:
219
+ body: Any = {}
220
+ else:
221
+ try:
222
+ body = response.json()
223
+ except ValueError:
224
+ body = None
225
+ if not isinstance(body, dict):
226
+ raise errors.APIResponseValidationError(
227
+ status=response.status_code, body=response.text[:500], headers=response.headers
228
+ )
229
+ result = ResponseBody(body)
230
+ result.status = response.status_code
231
+ result.headers = response.headers
232
+ return result
233
+
234
+
235
+ def parse(parser: Callable[[Mapping[str, Any]], T], data: Mapping[str, Any]) -> T:
236
+ """Build a typed object, reporting missing or malformed fields as an SDK error."""
237
+ try:
238
+ return parser(data)
239
+ except (KeyError, TypeError, ValueError, AttributeError) as exc:
240
+ raise errors.APIResponseValidationError(
241
+ status=getattr(data, "status", 200),
242
+ body=dict(data),
243
+ headers=getattr(data, "headers", httpx.Headers()),
244
+ detail=f"The API response is missing or has an invalid field ({type(exc).__name__}: {exc})",
245
+ ) from exc
246
+
247
+
248
+ def connection_error(exc: httpx.TransportError, url: str) -> errors.APIConnectionError:
249
+ cls = errors.APITimeoutError if isinstance(exc, httpx.TimeoutException) else errors.APIConnectionError
250
+ return cls("Request timed out" if cls is errors.APITimeoutError else "Connection failed", request=url)
251
+
252
+
253
+ def log_request(
254
+ method: str,
255
+ url: str,
256
+ attempt: int,
257
+ response: httpx.Response | None = None,
258
+ delay: float | None = None,
259
+ *,
260
+ storage: bool = False,
261
+ ) -> None:
262
+ parsed = httpx.URL(url)
263
+ location = f"{parsed.scheme}://{parsed.host}" if storage else parsed.raw_path.decode("ascii")
264
+ logger.debug(
265
+ "%s %s status=%s request_id=%s attempt=%s retry_delay=%s",
266
+ method,
267
+ location,
268
+ response.status_code if response is not None else None,
269
+ response.headers.get("X-Request-Id") if response is not None else None,
270
+ attempt + 1,
271
+ delay,
272
+ )
273
+
274
+
275
+ def poll_delay(elapsed: float, timeout: float | None, interval: float) -> float:
276
+ return interval if timeout is None else min(interval, max(0, timeout - elapsed))
277
+
278
+
279
+ def validate_poll(timeout: float | None, *intervals: float) -> None:
280
+ if timeout is not None and (timeout < 0 or not math.isfinite(timeout)):
281
+ raise ValueError("timeout must be finite and nonnegative, or None")
282
+ if any(value <= 0 or not math.isfinite(value) for value in intervals):
283
+ raise ValueError("poll intervals must be finite and positive")
zilapi/_client.py ADDED
@@ -0,0 +1,301 @@
1
+ """HTTP clients and retry orchestration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import copy
7
+ import os
8
+ import time
9
+ from collections.abc import Awaitable, Callable, Mapping
10
+ from typing import Any
11
+
12
+ import httpx
13
+
14
+ from ._base import (
15
+ USER_AGENT,
16
+ Multipart,
17
+ api_headers,
18
+ connection_error,
19
+ install_log_redaction,
20
+ is_safe,
21
+ log_request,
22
+ parse,
23
+ resolve_config,
24
+ retry_delay,
25
+ status_error,
26
+ success_body,
27
+ timeout_value,
28
+ )
29
+ from .resources.audio import AsyncAudio, Audio
30
+ from .resources.credits import AsyncCredits, CreditsResource
31
+ from .resources.files import AsyncFiles, Files
32
+ from .resources.images import AsyncImages, Images
33
+ from .resources.jobs import AsyncJobs, Jobs
34
+ from .resources.models import AsyncModels, Models
35
+ from .types import Me
36
+
37
+ # Storage clients honour HTTP(S)_PROXY, NO_PROXY, SSL_CERT_FILE and SSL_CERT_DIR like the API
38
+ # client does. httpx (>=0.25) never reads .netrc implicitly, and these clients carry no API key.
39
+ STORAGE_TIMEOUT = httpx.Timeout(300, connect=10)
40
+
41
+
42
+ class _Storage:
43
+ def __init__(self) -> None:
44
+ self.sync: httpx.Client | None = None
45
+ self.async_: httpx.AsyncClient | None = None
46
+
47
+
48
+ class _Config:
49
+ def _configure(
50
+ self,
51
+ api_key: str | None,
52
+ base_url: str | None,
53
+ timeout: float | httpx.Timeout,
54
+ max_retries: int,
55
+ default_headers: Mapping[str, str] | None,
56
+ ) -> None:
57
+ self._api_key, self.base_url = resolve_config(api_key, base_url, os.environ)
58
+ self.timeout = timeout_value(timeout)
59
+ self.max_retries = max_retries
60
+ self._validate_retries()
61
+ self._headers = api_headers(self._api_key, default_headers)
62
+ self._storage = _Storage()
63
+ self._owns_storage = True
64
+ self._monotonic: Callable[[], float] = time.monotonic
65
+ install_log_redaction()
66
+
67
+ def _validate_retries(self) -> None:
68
+ if self.max_retries < 0:
69
+ raise ValueError("max_retries must be nonnegative")
70
+
71
+ def __repr__(self) -> str:
72
+ mode = (
73
+ "live"
74
+ if self._api_key.startswith("zil_live_")
75
+ else ("test" if self._api_key.startswith("zil_test_") else "unknown")
76
+ )
77
+ return f"{type(self).__name__}(base_url={self.base_url!r}, mode={mode!r})"
78
+
79
+
80
+ class ZilAPI(_Config):
81
+ """Synchronous ZilAPI client; use as a context manager to release connections."""
82
+
83
+ def __init__(
84
+ self,
85
+ api_key: str | None = None,
86
+ *,
87
+ base_url: str | None = None,
88
+ timeout: float | httpx.Timeout = 60.0,
89
+ max_retries: int = 2,
90
+ http_client: httpx.Client | None = None,
91
+ default_headers: Mapping[str, str] | None = None,
92
+ ) -> None:
93
+ self._configure(api_key, base_url, timeout, max_retries, default_headers)
94
+ self._owns_http_client = http_client is None
95
+ self._http_client = http_client if http_client is not None else httpx.Client()
96
+ self._sleep: Callable[[float], None] = time.sleep
97
+ self._wire()
98
+
99
+ def _wire(self) -> None:
100
+ self.models = Models(self)
101
+ self.files = Files(self)
102
+ self.audio = Audio(self)
103
+ self.images = Images(self)
104
+ self.jobs = Jobs(self)
105
+ self.credits = CreditsResource(self)
106
+
107
+ def with_options(
108
+ self, *, max_retries: int | None = None, timeout: float | httpx.Timeout | None = None
109
+ ) -> ZilAPI:
110
+ """Return a configured view sharing connections; the original client owns them."""
111
+ other = copy.copy(self)
112
+ if max_retries is not None:
113
+ other.max_retries = max_retries
114
+ if timeout is not None:
115
+ other.timeout = timeout_value(timeout)
116
+ other._validate_retries()
117
+ other._owns_http_client = other._owns_storage = False
118
+ other._wire()
119
+ return other
120
+
121
+ def _request(
122
+ self,
123
+ method: str,
124
+ path: str,
125
+ *,
126
+ json: Mapping[str, Any] | None = None,
127
+ headers: Mapping[str, str] | None = None,
128
+ params: Mapping[str, str | int] | None = None,
129
+ multipart: Multipart | None = None,
130
+ ) -> dict[str, Any]:
131
+ merged = httpx.Headers(self._headers)
132
+ merged.update(headers or {})
133
+ url = self.base_url + path
134
+ safe = is_safe(method, merged)
135
+ for attempt in range(self.max_retries + 1):
136
+ response = None
137
+ try:
138
+ response = self._http_client.request(
139
+ method,
140
+ url,
141
+ json=json,
142
+ data=multipart.data if multipart is not None else None,
143
+ files=multipart.files if multipart is not None else None,
144
+ params=params,
145
+ headers=merged,
146
+ timeout=self.timeout,
147
+ follow_redirects=False,
148
+ auth=None,
149
+ )
150
+ except httpx.TransportError as exc:
151
+ delay = retry_delay(attempt) if safe and attempt < self.max_retries else None
152
+ log_request(method, url, attempt, delay=delay)
153
+ if delay is None:
154
+ raise connection_error(exc, url) from exc
155
+ else:
156
+ delay = retry_delay(attempt, response) if safe and attempt < self.max_retries else None
157
+ log_request(method, str(response.request.url), attempt, response, delay)
158
+ if response.is_success:
159
+ return success_body(response)
160
+ if delay is None:
161
+ raise status_error(response)
162
+ if response is not None:
163
+ response.close()
164
+ self._sleep(delay)
165
+ raise RuntimeError("Unreachable retry state")
166
+
167
+ def _storage_client(self) -> httpx.Client:
168
+ if self._storage.sync is None:
169
+ self._storage.sync = httpx.Client(timeout=STORAGE_TIMEOUT)
170
+ self._storage.sync.headers.clear()
171
+ self._storage.sync.headers["User-Agent"] = USER_AGENT
172
+ return self._storage.sync
173
+
174
+ def me(self) -> Me:
175
+ """Retrieve the authenticated account and key details."""
176
+ return parse(Me.from_dict, self._request("GET", "/v1/me"))
177
+
178
+ def close(self) -> None:
179
+ """Close connections owned by this client."""
180
+ if self._owns_http_client:
181
+ self._http_client.close()
182
+ if self._owns_storage and self._storage.sync is not None:
183
+ self._storage.sync.close()
184
+
185
+ def __enter__(self) -> ZilAPI:
186
+ return self
187
+
188
+ def __exit__(self, *args: object) -> None:
189
+ self.close()
190
+
191
+
192
+ class AsyncZilAPI(_Config):
193
+ """Asynchronous ZilAPI client; use with ``async with`` to release connections."""
194
+
195
+ def __init__(
196
+ self,
197
+ api_key: str | None = None,
198
+ *,
199
+ base_url: str | None = None,
200
+ timeout: float | httpx.Timeout = 60.0,
201
+ max_retries: int = 2,
202
+ http_client: httpx.AsyncClient | None = None,
203
+ default_headers: Mapping[str, str] | None = None,
204
+ ) -> None:
205
+ self._configure(api_key, base_url, timeout, max_retries, default_headers)
206
+ self._owns_http_client = http_client is None
207
+ self._http_client = http_client if http_client is not None else httpx.AsyncClient()
208
+ self._sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
209
+ self._wire()
210
+
211
+ def _wire(self) -> None:
212
+ self.models = AsyncModels(self)
213
+ self.files = AsyncFiles(self)
214
+ self.audio = AsyncAudio(self)
215
+ self.images = AsyncImages(self)
216
+ self.jobs = AsyncJobs(self)
217
+ self.credits = AsyncCredits(self)
218
+
219
+ def with_options(
220
+ self, *, max_retries: int | None = None, timeout: float | httpx.Timeout | None = None
221
+ ) -> AsyncZilAPI:
222
+ """Return a configured view sharing connections; the original client owns them."""
223
+ other = copy.copy(self)
224
+ if max_retries is not None:
225
+ other.max_retries = max_retries
226
+ if timeout is not None:
227
+ other.timeout = timeout_value(timeout)
228
+ other._validate_retries()
229
+ other._owns_http_client = other._owns_storage = False
230
+ other._wire()
231
+ return other
232
+
233
+ async def _request(
234
+ self,
235
+ method: str,
236
+ path: str,
237
+ *,
238
+ json: Mapping[str, Any] | None = None,
239
+ headers: Mapping[str, str] | None = None,
240
+ params: Mapping[str, str | int] | None = None,
241
+ multipart: Multipart | None = None,
242
+ ) -> dict[str, Any]:
243
+ merged = httpx.Headers(self._headers)
244
+ merged.update(headers or {})
245
+ url = self.base_url + path
246
+ safe = is_safe(method, merged)
247
+ for attempt in range(self.max_retries + 1):
248
+ response = None
249
+ try:
250
+ response = await self._http_client.request(
251
+ method,
252
+ url,
253
+ json=json,
254
+ data=multipart.data if multipart is not None else None,
255
+ files=multipart.files if multipart is not None else None,
256
+ params=params,
257
+ headers=merged,
258
+ timeout=self.timeout,
259
+ follow_redirects=False,
260
+ auth=None,
261
+ )
262
+ except httpx.TransportError as exc:
263
+ delay = retry_delay(attempt) if safe and attempt < self.max_retries else None
264
+ log_request(method, url, attempt, delay=delay)
265
+ if delay is None:
266
+ raise connection_error(exc, url) from exc
267
+ else:
268
+ delay = retry_delay(attempt, response) if safe and attempt < self.max_retries else None
269
+ log_request(method, str(response.request.url), attempt, response, delay)
270
+ if response.is_success:
271
+ return success_body(response)
272
+ if delay is None:
273
+ raise status_error(response)
274
+ if response is not None:
275
+ await response.aclose()
276
+ await self._sleep(delay)
277
+ raise RuntimeError("Unreachable retry state")
278
+
279
+ def _storage_client(self) -> httpx.AsyncClient:
280
+ if self._storage.async_ is None:
281
+ self._storage.async_ = httpx.AsyncClient(timeout=STORAGE_TIMEOUT)
282
+ self._storage.async_.headers.clear()
283
+ self._storage.async_.headers["User-Agent"] = USER_AGENT
284
+ return self._storage.async_
285
+
286
+ async def me(self) -> Me:
287
+ """Retrieve the authenticated account and key details."""
288
+ return parse(Me.from_dict, await self._request("GET", "/v1/me"))
289
+
290
+ async def aclose(self) -> None:
291
+ """Close connections owned by this client."""
292
+ if self._owns_http_client:
293
+ await self._http_client.aclose()
294
+ if self._owns_storage and self._storage.async_ is not None:
295
+ await self._storage.async_.aclose()
296
+
297
+ async def __aenter__(self) -> AsyncZilAPI:
298
+ return self
299
+
300
+ async def __aexit__(self, *args: object) -> None:
301
+ await self.aclose()