Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,27 @@ All notable changes to this project are documented here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres
to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.6.2]

### Fixed

- `client.states()` sends the `country` query parameter, which the API
requires. Before, every call returned 400. The parameter is `country="US"`
by default. The docstring now names the engines that accept `state`:
ChatGPT, Gemini and Bing AI Mode.
- The client does not retry a `client.monitor.*` request after a read timeout,
a dropped connection, a 502 or a 504. In these cases the server can complete
the first request and charge for it, so a retry can charge again. The client
still retries such a request when the connection did not open, and on a
429, 500 or 503. An async task create follows the same rule, except when it
has an `idempotency_key` (for a batch, when each task has one). GET requests
keep all retries.

### Changed

- The default request timeout is 320 seconds, up from 300. The server stops a
sync request after 5 minutes, and the client now waits for that response.

## [0.6.1]

### Changed
Expand Down
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,18 @@ Valid `task_type` values: `CHATGPT`, `GEMINI`, `AIMODE`, `BING_AIMODE`,
client = Cloro(
api_key="sk_live_...",
base_url="https://api.cloro.dev", # override if needed
timeout=300.0, # per-request seconds (the default)
timeout=320.0, # per-request seconds (the default)
max_retries=2, # timeouts, connection errors, 429/5xx
)
```

A request that can charge credits twice is retried only when the server cannot
have run it. A `client.monitor.*` call, or an async task without an
`idempotency_key`, is retried when the connection did not open, and on a 429,
500 or 503. It is not retried after a timeout, a dropped connection, a 502 or a
504, because the server can complete the first request and charge for it. Use
the async queue with an `idempotency_key` if you want retries in those cases.

The client is a context manager and pools connections:

```python
Expand Down Expand Up @@ -214,7 +221,8 @@ client.countries() # supported countries
client.countries(model="chatgpt")
client.countries(model="bing_aimode")
client.countries(model="bing")
client.states() # US states for location-targeted Google
client.states() # US states for the `state` field (ChatGPT, Gemini, Bing AI Mode)
client.states(country="US") # the same, with the country given
```

## Links
Expand Down
47 changes: 39 additions & 8 deletions src/cloro/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
from .resources.monitor import MonitorResource

DEFAULT_BASE_URL = "https://api.cloro.dev"
DEFAULT_TIMEOUT = 300.0 # a sync request can run for several minutes
# The server stops a sync request after 5 minutes. The extra 20 seconds let
# the client get that response before its own timeout starts.
DEFAULT_TIMEOUT = 320.0
DEFAULT_MAX_RETRIES = 2

_STATUS_MAP = {
Expand All @@ -41,6 +43,12 @@
# Status codes that are safe to retry with backoff.
_RETRY_STATUS = {429, 500, 502, 503, 504}

# The subset that is safe to retry for a request that is not idempotent.
# The server charges credits only for a 200, so a 429, 500 or 503 from the
# API did not charge. A 502 or 504 comes from a gateway, and the API can
# still complete the request and charge for it after the gateway responds.
_RETRY_STATUS_NOT_IDEMPOTENT = {429, 500, 503}


def _backoff(attempt: int) -> float:
"""Exponential backoff: 0.5s, 1s, 2s, ... capped at 8s."""
Expand Down Expand Up @@ -93,8 +101,14 @@ class Cloro:
api_key: Your cloro API key (``sk_live_...``). Falls back to the
``CLORO_API_KEY`` environment variable.
base_url: Override the API base URL (default ``https://api.cloro.dev``).
timeout: Per-request timeout in seconds.
timeout: Per-request timeout in seconds (default 320).
max_retries: Retries for timeouts, connection errors, and 429/5xx.
A request that is not idempotent (``client.monitor.*``, or an
async task without an ``idempotency_key``) is retried only when
the server cannot have run it: a connection that did not open,
a 429, a 500 or a 503. The client does not retry it after a
timeout, because the server can complete the first request and
charge for it.
http_client: Inject a preconfigured ``httpx.Client`` (proxies, custom
transport, testing). If provided, ``timeout`` is ignored.

Expand Down Expand Up @@ -140,9 +154,13 @@ def countries(self, model: Optional[str] = None) -> Any:
params = {"model": model} if model else None
return self.request("GET", "/v1/countries", params=params)

def states(self) -> Any:
"""List supported US states (for location-targeted Google requests)."""
return self.request("GET", "/v1/states")
def states(self, country: str = "US") -> Any:
"""List the states that ``country`` supports for the ``state`` field.

The ``state`` field is available on ChatGPT, Gemini and Bing AI Mode
requests. A country without state targeting returns an empty list.
"""
return self.request("GET", "/v1/states", params={"country": country})

# -- transport ------------------------------------------------------

Expand All @@ -161,7 +179,17 @@ def request(
*,
json: Any = None,
params: Optional[Dict[str, Any]] = None,
idempotent: Optional[bool] = None,
) -> Any:
"""Send a request, with retries.

``idempotent`` tells if the request is safe to send again after it
possibly reached the server. It defaults to ``True`` for GET and to
``False`` for all other methods.
"""
if idempotent is None:
idempotent = method.upper() == "GET"
retry_status = _RETRY_STATUS if idempotent else _RETRY_STATUS_NOT_IDEMPOTENT
url = f"{self.base_url}{path}"
attempt = 0
while True:
Expand All @@ -170,20 +198,23 @@ def request(
method, url, json=json, params=params, headers=self._headers()
)
except httpx.TimeoutException as exc:
if attempt < self.max_retries:
# A connect or pool timeout means the request was not sent.
not_sent = isinstance(exc, (httpx.ConnectTimeout, httpx.PoolTimeout))
if (idempotent or not_sent) and attempt < self.max_retries:
attempt += 1
time.sleep(_backoff(attempt))
continue
raise APITimeoutError(f"Request to {url} timed out") from exc
except httpx.HTTPError as exc:
if attempt < self.max_retries:
not_sent = isinstance(exc, httpx.ConnectError)
if (idempotent or not_sent) and attempt < self.max_retries:
attempt += 1
time.sleep(_backoff(attempt))
continue
raise APIConnectionError(str(exc)) from exc

if response.status_code >= 400:
if response.status_code in _RETRY_STATUS and attempt < self.max_retries:
if response.status_code in retry_status and attempt < self.max_retries:
attempt += 1
retry_after = _parse_retry_after(response)
time.sleep(retry_after if retry_after is not None else _backoff(attempt))
Expand Down
2 changes: 1 addition & 1 deletion src/cloro/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.6.1"
__version__ = "0.6.2"
13 changes: 11 additions & 2 deletions src/cloro/resources/async_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ def create(
"webhook": webhook,
}
)
resp = self._client.request("POST", "/v1/async/task", json=body)
# With a key, the server does not create a second task on a retry.
resp = self._client.request(
"POST", "/v1/async/task", json=body, idempotent="idempotencyKey" in body
)
return AsyncTask._from_summary(resp["task"])

def create_batch(self, tasks: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
Expand All @@ -116,7 +119,13 @@ def create_batch(self, tasks: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
``task`` field; failed items carry an ``error`` field.
"""
body = [_to_request(t) for t in tasks]
resp = self._client.request("POST", "/v1/async/task/batch", json=body)
# The batch is safe to send again only if each task has a key.
resp = self._client.request(
"POST",
"/v1/async/task/batch",
json=body,
idempotent=bool(body) and all("idempotencyKey" in t for t in body),
)
return resp.get("results", [])

# -- read -----------------------------------------------------------
Expand Down
125 changes: 125 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,3 +356,128 @@ def handler(request: httpx.Request) -> httpx.Response:
assert len(results) == 2
assert results[0]["task"]["id"] == "t-1"
assert results[1]["error"]["code"] == "VALIDATION_ERROR"


def test_states_sends_country():
seen = []

def handler(request: httpx.Request) -> httpx.Response:
seen.append(str(request.url))
return httpx.Response(200, json=[{"code": "CA", "name": "California"}])

client = make_client(handler)
assert client.states() == [{"code": "CA", "name": "California"}]
client.states(country="GB")
assert seen == [
"https://api.cloro.dev/v1/states?country=US",
"https://api.cloro.dev/v1/states?country=GB",
]


# -- retries --------------------------------------------------------------


@pytest.fixture(autouse=True)
def no_backoff_sleep(monkeypatch):
monkeypatch.setattr("cloro._client.time.sleep", lambda _s: None)


def counting_handler(*outcomes):
"""Return a handler that gives each outcome in turn, and a call counter.

An outcome is an exception class to raise, or a status code to return.
The last outcome repeats.
"""
calls = {"n": 0}

def handler(request: httpx.Request) -> httpx.Response:
outcome = outcomes[min(calls["n"], len(outcomes) - 1)]
calls["n"] += 1
if isinstance(outcome, type):
raise outcome("boom", request=request)
return httpx.Response(outcome, json={"success": outcome == 200})

return handler, calls


def test_monitor_does_not_retry_read_timeout():
handler, calls = counting_handler(httpx.ReadTimeout, 200)
client = make_client(handler, max_retries=2)
with pytest.raises(cloro.APITimeoutError):
client.monitor.chatgpt(prompt="x", country="US")
assert calls["n"] == 1


def test_monitor_does_not_retry_after_the_request_was_sent():
handler, calls = counting_handler(httpx.RemoteProtocolError, 200)
client = make_client(handler, max_retries=2)
with pytest.raises(cloro.APIConnectionError):
client.monitor.chatgpt(prompt="x", country="US")
assert calls["n"] == 1


@pytest.mark.parametrize("exc", [httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout])
def test_monitor_retries_when_the_request_was_not_sent(exc):
handler, calls = counting_handler(exc, 200)
client = make_client(handler, max_retries=2)
assert client.monitor.chatgpt(prompt="x", country="US")["success"] is True
assert calls["n"] == 2


@pytest.mark.parametrize("status", [502, 504])
def test_monitor_does_not_retry_gateway_errors(status):
handler, calls = counting_handler(status, 200)
client = make_client(handler, max_retries=2)
with pytest.raises(cloro.InternalServerError):
client.monitor.chatgpt(prompt="x", country="US")
assert calls["n"] == 1


@pytest.mark.parametrize("status", [500, 503])
def test_monitor_retries_errors_that_did_not_charge(status):
handler, calls = counting_handler(status, 200)
client = make_client(handler, max_retries=2)
assert client.monitor.chatgpt(prompt="x", country="US")["success"] is True
assert calls["n"] == 2


@pytest.mark.parametrize("outcome", [httpx.ReadTimeout, 502])
def test_get_retries_timeouts_and_gateway_errors(outcome):
handler, calls = counting_handler(outcome, 200)
client = make_client(handler, max_retries=2)
client.countries()
assert calls["n"] == 2


def test_async_create_retries_timeout_only_with_idempotency_key():
handler, calls = counting_handler(httpx.ReadTimeout)
client = make_client(handler, max_retries=2)
with pytest.raises(cloro.APITimeoutError):
client.async_tasks.create(task_type="CHATGPT", payload={"prompt": "x", "country": "US"})
assert calls["n"] == 1

handler, calls = counting_handler(httpx.ReadTimeout)
client = make_client(handler, max_retries=2)
with pytest.raises(cloro.APITimeoutError):
client.async_tasks.create(
task_type="CHATGPT", payload={"prompt": "x", "country": "US"}, idempotency_key="k-1"
)
assert calls["n"] == 3


def test_async_batch_retries_timeout_only_when_every_task_has_a_key():
task = {"task_type": "CHATGPT", "payload": {"prompt": "x", "country": "US"}}

handler, calls = counting_handler(httpx.ReadTimeout)
client = make_client(handler, max_retries=2)
with pytest.raises(cloro.APITimeoutError):
client.async_tasks.create_batch([{**task, "idempotency_key": "k-1"}, task])
assert calls["n"] == 1

handler, calls = counting_handler(httpx.ReadTimeout)
client = make_client(handler, max_retries=2)
with pytest.raises(cloro.APITimeoutError):
client.async_tasks.create_batch(
[{**task, "idempotency_key": "k-1"}, {**task, "idempotencyKey": "k-2"}]
)
assert calls["n"] == 3