Skip to content
Navigation Menu
{{ message }}
forked from replicate/replicate-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.py
More file actions
330 lines (259 loc) · 10.1 KB
/
Copy pathclient.py
File metadata and controls
330 lines (259 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import asyncio
import os
import random
import time
from datetime import datetime
from typing import Iterable, Mapping, Optional, Union
import httpx
from .__about__ import __version__
from .collection import AsyncCollections, Collections
from .exceptions import APIError, ModelError
from .model import AsyncModels, Models
from .prediction import AsyncPredictions, Prediction, Predictions
from .training import AsyncTrainings, Trainings
from .version import VersionIdentifier
class Client:
"""A Replicate API client library"""
def __init__(
self,
api_token: str,
*,
base_url: Optional[str] = None,
timeout: Optional[httpx.Timeout] = None,
**kwargs,
) -> None:
super().__init__()
base_url = base_url or os.environ.get(
"REPLICATE_API_BASE_URL", "https://api.replicate.com/v1"
)
timeout = timeout or httpx.Timeout(
5.0, read=30.0, write=30.0, connect=5.0, pool=10.0
)
headers = {
"Authorization": f"Token {api_token}",
"User-Agent": f"replicate-python/{__version__}",
}
self._client = self._build_client(
**kwargs,
base_url=base_url,
headers=headers,
timeout=timeout,
)
def _build_client(self, **kwargs) -> httpx.Client:
return httpx.Client(transport=RetryTransport(httpx.HTTPTransport()), **kwargs)
def request(self, method: str, path: str, **kwargs) -> httpx.Response:
resp = self._client.request(method, path, **kwargs)
if 400 <= resp.status_code < 600:
raise APIError.from_response(resp)
return resp
@property
def collections(self) -> Collections:
return Collections(client=self)
@property
def models(self) -> Models:
return Models(client=self)
@property
def predictions(self) -> Predictions:
return Predictions(client=self)
@property
def trainings(self) -> Trainings:
return Trainings(client=self)
def run(
self,
identifier: VersionIdentifier | str,
input: dict,
webhook: Optional[str] = None,
webhook_completed: Optional[str] = None,
webhook_events_filter: Optional[list[str]] = None,
*,
poll_interval: float = 1.0,
**kwargs,
) -> any:
"""
Run a model and wait for its output.
Args:
identifier: The model version to run, in the form `owner/name:version`
kwargs: The input to the model, as a dictionary
Returns:
The output of the model
Throws:
Identifier.InvalidError: If the model identifier is invalid
ModelError: If the prediction fails
"""
if not isinstance(identifier, VersionIdentifier):
identifier = VersionIdentifier.from_string(identifier)
prediction = self.predictions.create(
identifier.version,
input,
webhook,
webhook_completed,
webhook_events_filter,
**kwargs,
)
prediction = self.wait(prediction, poll_interval=poll_interval)
if prediction.status == "failed":
raise ModelError(prediction.error)
return prediction.output
def wait(self, prediction: Prediction, *, poll_interval: float = 1.0) -> Prediction:
"""
Wait for a prediction to complete.
Args:
prediction: The prediction to wait for.
"""
while prediction.status not in ["succeeded", "failed", "canceled"]:
if poll_interval > 0:
time.sleep(poll_interval)
prediction = self.predictions.get(prediction.id)
return prediction
class AsyncClient(Client):
"""An asynchronous Replicate API client library"""
def _build_client(self, **kwargs) -> httpx.AsyncClient:
return httpx.AsyncClient(
transport=RetryTransport(httpx.HTTPTransport()), **kwargs
)
async def request(self, method: str, path: str, **kwargs) -> httpx.Response:
resp = await self._client.request(method, path, **kwargs)
if 400 <= resp.status_code < 600:
raise APIError.from_response(resp)
return resp
@property
def collections(self) -> AsyncCollections:
return AsyncCollections(client=self)
@property
def models(self) -> AsyncModels:
return AsyncModels(client=self)
@property
def predictions(self) -> AsyncPredictions:
return AsyncPredictions(client=self)
@property
def trainings(self) -> AsyncTrainings:
return AsyncTrainings(client=self)
async def run(
self,
identifier: VersionIdentifier | str,
input: dict,
webhook: Optional[str] = None,
webhook_completed: Optional[str] = None,
webhook_events_filter: Optional[list[str]] = None,
*,
poll_interval: float = 1.0,
**kwargs,
) -> any:
if not isinstance(identifier, VersionIdentifier):
identifier = VersionIdentifier.from_string(identifier)
prediction = await self.predictions.create(
identifier.version,
input,
webhook,
webhook_completed,
webhook_events_filter,
**kwargs,
)
prediction = await self.wait(prediction, poll_interval=poll_interval)
if prediction.status == "failed":
raise ModelError(prediction.error)
return prediction.output
async def wait(
self, prediction: Prediction, *, poll_interval: float = 1.0
) -> Prediction:
while prediction.status not in ["succeeded", "failed", "canceled"]:
await asyncio.sleep(poll_interval)
prediction = await self.predictions.get(prediction.id)
return prediction
# Adapted from https://github.com/encode/httpx/issues/108#issuecomment-1132753155
class RetryTransport(httpx.AsyncBaseTransport, httpx.BaseTransport):
"""A custom HTTP transport that automatically retries requests using an exponential backoff strategy
for specific HTTP status codes and request methods.
"""
RETRYABLE_METHODS = frozenset(["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"])
RETRYABLE_STATUS_CODES = frozenset([413, 429, 503, 504])
MAX_BACKOFF_WAIT = 60
def __init__(
self,
wrapped_transport: Union[httpx.BaseTransport, httpx.AsyncBaseTransport],
max_attempts: int = 10,
max_backoff_wait: float = MAX_BACKOFF_WAIT,
backoff_factor: float = 0.1,
jitter_ratio: float = 0.1,
retryable_methods: Iterable[str] = None,
retry_status_codes: Iterable[int] = None,
) -> None:
self.wrapped_transport = wrapped_transport
if jitter_ratio < 0 or jitter_ratio > 0.5:
raise ValueError(
f"jitter ratio should be between 0 and 0.5, actual {jitter_ratio}"
)
self.max_attempts = max_attempts
self.backoff_factor = backoff_factor
self.retryable_methods = (
frozenset(retryable_methods)
if retryable_methods
else self.RETRYABLE_METHODS
)
self.retry_status_codes = (
frozenset(retry_status_codes)
if retry_status_codes
else self.RETRYABLE_STATUS_CODES
)
self.jitter_ratio = jitter_ratio
self.max_backoff_wait = max_backoff_wait
def _calculate_sleep(
self, attempts_made: int, headers: Union[httpx.Headers, Mapping[str, str]]
) -> float:
retry_after_header = (headers.get("Retry-After") or "").strip()
if retry_after_header:
if retry_after_header.isdigit():
return float(retry_after_header)
try:
parsed_date = datetime.fromisoformat(retry_after_header).astimezone()
diff = (parsed_date - datetime.now().astimezone()).total_seconds()
if diff > 0:
return min(diff, self.max_backoff_wait)
except ValueError:
pass
backoff = self.backoff_factor * (2 ** (attempts_made - 1))
jitter = (backoff * self.jitter_ratio) * random.choice([1, -1])
total_backoff = backoff + jitter
return min(total_backoff, self.max_backoff_wait)
def handle_request(self, request: httpx.Request) -> httpx.Response:
response = self.wrapped_transport.handle_request(request)
if request.method not in self.retryable_methods:
return response
remaining_attempts = self.max_attempts - 1
attempts_made = 1
while True:
if (
remaining_attempts < 1
or response.status_code not in self.retry_status_codes
):
return response
response.close()
sleep_for = self._calculate_sleep(attempts_made, response.headers)
time.sleep(sleep_for)
response = self.wrapped_transport.handle_request(request)
attempts_made += 1
remaining_attempts -= 1
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
response = await self.wrapped_transport.handle_async_request(request)
if request.method not in self.retryable_methods:
return response
remaining_attempts = self.max_attempts - 1
attempts_made = 1
while True:
if (
remaining_attempts < 1
or response.status_code not in self.retry_status_codes
):
return response
response.close()
sleep_for = self._calculate_sleep(attempts_made, response.headers)
time.sleep(sleep_for)
response = await self.wrapped_transport.handle_async_request(request)
attempts_made += 1
remaining_attempts -= 1
async def aclose(self) -> None:
transport: httpx.AsyncBaseTransport = self._wrapped_transport
await transport.aclose()
def close(self) -> None:
transport: httpx.BaseTransport = self._wrapped_transport
transport.close()
You can’t perform that action at this time.
