|
1 | 1 | import os |
2 | 2 | import re |
3 | | -from json import JSONDecodeError |
4 | | -from typing import Any, Dict, Iterator, Optional, Union |
| 3 | +from typing import Any, Iterator, Optional, Union |
5 | 4 |
|
6 | | -import requests |
7 | | -from requests.adapters import HTTPAdapter, Retry |
8 | | -from requests.cookies import RequestsCookieJar |
| 5 | +import httpx |
9 | 6 |
|
10 | | -from replicate.__about__ import __version__ |
11 | | -from replicate.deployment import DeploymentCollection |
12 | | -from replicate.exceptions import ModelError, ReplicateError |
13 | | -from replicate.model import ModelCollection |
14 | | -from replicate.prediction import PredictionCollection |
15 | | -from replicate.training import TrainingCollection |
| 7 | +from .__about__ import __version__ |
| 8 | +from .deployment import DeploymentCollection |
| 9 | +from .exceptions import ModelError, ReplicateError |
| 10 | +from .model import ModelCollection |
| 11 | +from .prediction import PredictionCollection |
| 12 | +from .training import TrainingCollection |
16 | 13 |
|
17 | 14 |
|
18 | 15 | class Client: |
19 | | - def __init__(self, api_token: Optional[str] = None) -> None: |
| 16 | + """A Replicate API client library""" |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + api_token: Optional[str] = None, |
| 21 | + *, |
| 22 | + base_url: Optional[str] = None, |
| 23 | + timeout: Optional[httpx.Timeout] = None, |
| 24 | + **kwargs, |
| 25 | + ) -> None: |
20 | 26 | super().__init__() |
21 | | - # Client is instantiated at import time, so do as little as possible. |
22 | | - # This includes resolving environment variables -- they might be set programmatically. |
23 | | - self.api_token = api_token |
24 | | - self.base_url = os.environ.get( |
| 27 | + |
| 28 | + api_token = api_token or os.environ.get("REPLICATE_API_TOKEN") |
| 29 | + |
| 30 | + base_url = base_url or os.environ.get( |
25 | 31 | "REPLICATE_API_BASE_URL", "https://api.replicate.com" |
26 | 32 | ) |
27 | | - self.poll_interval = float(os.environ.get("REPLICATE_POLL_INTERVAL", "0.5")) |
28 | 33 |
|
29 | | - # TODO: make thread safe |
30 | | - self.read_session = _create_session() |
31 | | - read_retries = Retry( |
32 | | - total=5, |
33 | | - backoff_factor=2, |
34 | | - # Only retry 500s on GET so we don't unintionally mutute data |
35 | | - allowed_methods=["GET"], |
36 | | - # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors |
37 | | - status_forcelist=[ |
38 | | - 429, |
39 | | - 500, |
40 | | - 502, |
41 | | - 503, |
42 | | - 504, |
43 | | - 520, |
44 | | - 521, |
45 | | - 522, |
46 | | - 523, |
47 | | - 524, |
48 | | - 526, |
49 | | - 527, |
50 | | - ], |
| 34 | + timeout = timeout or httpx.Timeout( |
| 35 | + 5.0, read=30.0, write=30.0, connect=5.0, pool=10.0 |
51 | 36 | ) |
52 | | - self.read_session.mount("http://", HTTPAdapter(max_retries=read_retries)) |
53 | | - self.read_session.mount("https://", HTTPAdapter(max_retries=read_retries)) |
54 | | - |
55 | | - self.write_session = _create_session() |
56 | | - write_retries = Retry( |
57 | | - total=5, |
58 | | - backoff_factor=2, |
59 | | - allowed_methods=["POST", "PUT"], |
60 | | - # Only retry POST/PUT requests on rate limits, so we don't unintionally mutute data |
61 | | - status_forcelist=[429], |
62 | | - ) |
63 | | - self.write_session.mount("http://", HTTPAdapter(max_retries=write_retries)) |
64 | | - self.write_session.mount("https://", HTTPAdapter(max_retries=write_retries)) |
65 | | - |
66 | | - def _request(self, method: str, path: str, **kwargs) -> requests.Response: |
67 | | - # from requests.Session |
68 | | - if method in ["GET", "OPTIONS"]: |
69 | | - kwargs.setdefault("allow_redirects", True) |
70 | | - if method in ["HEAD"]: |
71 | | - kwargs.setdefault("allow_redirects", False) |
72 | | - kwargs.setdefault("headers", {}) |
73 | | - kwargs["headers"].update(self._headers()) |
74 | | - session = self.read_session |
75 | | - if method in ["POST", "PUT", "DELETE", "PATCH"]: |
76 | | - session = self.write_session |
77 | | - resp = session.request(method, self.base_url + path, **kwargs) |
78 | | - if 400 <= resp.status_code < 600: |
79 | | - try: |
80 | | - raise ReplicateError(resp.json()["detail"]) |
81 | | - except (JSONDecodeError, KeyError): |
82 | | - pass |
83 | | - raise ReplicateError(f"HTTP error: {resp.status_code, resp.reason}") |
84 | | - return resp |
85 | 37 |
|
86 | | - def _headers(self) -> Dict[str, str]: |
87 | | - return { |
88 | | - "Authorization": f"Token {self._api_token()}", |
| 38 | + self.poll_interval = float(os.environ.get("REPLICATE_POLL_INTERVAL", "0.5")) |
| 39 | + |
| 40 | + headers = { |
| 41 | + "Authorization": f"Token {api_token}", |
89 | 42 | "User-Agent": f"replicate-python/{__version__}", |
90 | 43 | } |
91 | 44 |
|
92 | | - def _api_token(self) -> str: |
93 | | - token = self.api_token |
94 | | - # Evaluate lazily in case environment variable is set with dotenv, or something |
95 | | - if token is None: |
96 | | - token = os.environ.get("REPLICATE_API_TOKEN") |
97 | | - if not token: |
98 | | - raise ReplicateError( |
99 | | - """No API token provided. You need to set the REPLICATE_API_TOKEN environment variable or create a client with `replicate.Client(api_token=...)`. |
| 45 | + transport = kwargs.pop("transport", httpx.HTTPTransport()) |
100 | 46 |
|
101 | | -You can find your API key on https://replicate.com""" |
102 | | - ) |
103 | | - return token |
| 47 | + self._client = self._build_client( |
| 48 | + **kwargs, |
| 49 | + base_url=base_url, |
| 50 | + headers=headers, |
| 51 | + timeout=timeout, |
| 52 | + transport=transport, |
| 53 | + ) |
| 54 | + |
| 55 | + def _build_client(self, **kwargs) -> httpx.Client: |
| 56 | + return httpx.Client(**kwargs) |
| 57 | + |
| 58 | + def _request(self, method: str, path: str, **kwargs) -> httpx.Response: |
| 59 | + resp = self._client.request(method, path, **kwargs) |
| 60 | + |
| 61 | + if 400 <= resp.status_code < 600: |
| 62 | + raise ReplicateError(resp.json()["detail"]) |
| 63 | + |
| 64 | + return resp |
104 | 65 |
|
105 | 66 | @property |
106 | 67 | def models(self) -> ModelCollection: |
@@ -150,21 +111,3 @@ def run(self, model_version: str, **kwargs) -> Union[Any, Iterator[Any]]: |
150 | 111 | if prediction.status == "failed": |
151 | 112 | raise ModelError(prediction.error) |
152 | 113 | return prediction.output |
153 | | - |
154 | | - |
155 | | -class _NonpersistentCookieJar(RequestsCookieJar): |
156 | | - """ |
157 | | - A cookie jar that doesn't persist cookies between requests. |
158 | | - """ |
159 | | - |
160 | | - def set(self, name, value, **kwargs) -> None: |
161 | | - return |
162 | | - |
163 | | - def set_cookie(self, cookie, *args, **kwargs) -> None: |
164 | | - return |
165 | | - |
166 | | - |
167 | | -def _create_session() -> requests.Session: |
168 | | - s = requests.Session() |
169 | | - s.cookies = _NonpersistentCookieJar() |
170 | | - return s |
0 commit comments