aifree 0.3.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.
- aifree/__init__.py +7 -0
- aifree/_client.py +565 -0
- aifree/_version.py +1 -0
- aifree/py.typed +0 -0
- aifree/types.py +342 -0
- aifree-0.3.0.dist-info/METADATA +137 -0
- aifree-0.3.0.dist-info/RECORD +8 -0
- aifree-0.3.0.dist-info/WHEEL +4 -0
aifree/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Python client for the aifree.dev API v1: verified free AI offers,
|
|
2
|
+
free LLM API tiers and the models they serve (data CC BY 4.0)."""
|
|
3
|
+
|
|
4
|
+
from ._client import DEFAULT_BASE_URL, AifreeError, AsyncClient, Client
|
|
5
|
+
from ._version import __version__
|
|
6
|
+
|
|
7
|
+
__all__ = ["DEFAULT_BASE_URL", "AifreeError", "AsyncClient", "Client", "__version__"]
|
aifree/_client.py
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import datetime as dt
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, cast
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .types import (
|
|
13
|
+
BestList,
|
|
14
|
+
BestListSummary,
|
|
15
|
+
Building,
|
|
16
|
+
Category,
|
|
17
|
+
Change,
|
|
18
|
+
ChangeKind,
|
|
19
|
+
ChangesHub,
|
|
20
|
+
DeadlinesPage,
|
|
21
|
+
EligibilityResult,
|
|
22
|
+
FreeType,
|
|
23
|
+
Item,
|
|
24
|
+
ModelDetail,
|
|
25
|
+
ModelSummary,
|
|
26
|
+
Offer,
|
|
27
|
+
OfferStatus,
|
|
28
|
+
Refill,
|
|
29
|
+
Page,
|
|
30
|
+
Provider,
|
|
31
|
+
Startup,
|
|
32
|
+
WhereResult,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
DEFAULT_BASE_URL = "https://aifree.dev/api/v1"
|
|
36
|
+
DEFAULT_TIMEOUT = 15.0
|
|
37
|
+
|
|
38
|
+
DateLike = Union[str, dt.date, dt.datetime]
|
|
39
|
+
ListOrOne = Union[str, Iterable[str]]
|
|
40
|
+
Params = Dict[str, str]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class AifreeError(Exception):
|
|
44
|
+
"""A non-2xx answer from the API.
|
|
45
|
+
|
|
46
|
+
``code`` is the API's stable error code (``not_found``, ``rate_limited``,
|
|
47
|
+
``invalid_request``…), ``retry_after`` the seconds to wait on a 429 or 5xx
|
|
48
|
+
(``None`` otherwise) and ``details`` the per-field problems of a 400.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
message: str,
|
|
54
|
+
*,
|
|
55
|
+
status: int,
|
|
56
|
+
code: Optional[str] = None,
|
|
57
|
+
retry_after: Optional[int] = None,
|
|
58
|
+
details: Optional[List[str]] = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
super().__init__(message)
|
|
61
|
+
self.message = message
|
|
62
|
+
self.status = status
|
|
63
|
+
self.code = code
|
|
64
|
+
self.retry_after = retry_after
|
|
65
|
+
self.details = details or []
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _retry_after(body_value: Any, header: Optional[str]) -> Optional[int]:
|
|
69
|
+
for value in (body_value, header):
|
|
70
|
+
try:
|
|
71
|
+
n = float(value) if isinstance(value, (int, float, str)) else None
|
|
72
|
+
except ValueError:
|
|
73
|
+
n = None
|
|
74
|
+
if n is not None and 0 < n < math.inf:
|
|
75
|
+
return math.ceil(n)
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _error(response: httpx.Response) -> AifreeError:
|
|
80
|
+
try:
|
|
81
|
+
body = response.json()
|
|
82
|
+
except ValueError:
|
|
83
|
+
body = None
|
|
84
|
+
if not isinstance(body, dict):
|
|
85
|
+
body = {}
|
|
86
|
+
details = body.get("details") if isinstance(body.get("details"), list) else None
|
|
87
|
+
message = str(body.get("error") or f"HTTP {response.status_code}")
|
|
88
|
+
if details:
|
|
89
|
+
message = f"{message}: {'; '.join(str(d) for d in details)}"
|
|
90
|
+
code = body.get("code")
|
|
91
|
+
return AifreeError(
|
|
92
|
+
message,
|
|
93
|
+
status=response.status_code,
|
|
94
|
+
code=code if isinstance(code, str) else None,
|
|
95
|
+
retry_after=_retry_after(body.get("retryAfter"), response.headers.get("retry-after")),
|
|
96
|
+
details=[str(d) for d in details] if details else None,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _csv(value: Optional[ListOrOne]) -> Optional[str]:
|
|
101
|
+
if value is None:
|
|
102
|
+
return None
|
|
103
|
+
if isinstance(value, str):
|
|
104
|
+
return value
|
|
105
|
+
return ",".join(value)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _bool(value: Optional[bool]) -> Optional[str]:
|
|
109
|
+
return None if value is None else ("true" if value else "false")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _date(value: Optional[DateLike], *, day_only: bool = False) -> Optional[str]:
|
|
113
|
+
if value is None or isinstance(value, str):
|
|
114
|
+
return value
|
|
115
|
+
if isinstance(value, dt.datetime):
|
|
116
|
+
if day_only:
|
|
117
|
+
if value.tzinfo is not None:
|
|
118
|
+
value = value.astimezone(dt.timezone.utc)
|
|
119
|
+
return value.date().isoformat()
|
|
120
|
+
if value.tzinfo is None:
|
|
121
|
+
raise ValueError("changed_since: a datetime needs a time zone (or pass a date)")
|
|
122
|
+
return value.isoformat()
|
|
123
|
+
return value.isoformat()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _params(**values: Optional[Union[str, int]]) -> Params:
|
|
127
|
+
return {k: str(v) for k, v in values.items() if v is not None}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _slug(value: str) -> str:
|
|
131
|
+
return "-".join(value.strip().lower().split())
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _quote(value: str) -> str:
|
|
135
|
+
return quote(value, safe="")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# Request builders shared by the sync and async clients: (path, params).
|
|
139
|
+
Request = Tuple[str, Params]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _offers_request(
|
|
143
|
+
*,
|
|
144
|
+
q: Optional[str],
|
|
145
|
+
category: Optional[Union[Category, Iterable[Category]]],
|
|
146
|
+
audience: Optional[Union[str, Iterable[str]]],
|
|
147
|
+
free_type: Optional[Union[FreeType, Iterable[FreeType]]],
|
|
148
|
+
card_required: Optional[bool],
|
|
149
|
+
region: Optional[str],
|
|
150
|
+
commercial_use: Optional[Union[str, Iterable[str]]],
|
|
151
|
+
refill: Optional[Union[Refill, Iterable[Refill]]],
|
|
152
|
+
status: Optional[Union[OfferStatus, Iterable[OfferStatus]]],
|
|
153
|
+
changed_since: Optional[DateLike],
|
|
154
|
+
fields: Optional[Iterable[str]],
|
|
155
|
+
page: Optional[int],
|
|
156
|
+
limit: Optional[int],
|
|
157
|
+
) -> Request:
|
|
158
|
+
return "/offers", _params(
|
|
159
|
+
q=q,
|
|
160
|
+
category=_csv(category),
|
|
161
|
+
audience=_csv(audience),
|
|
162
|
+
freeType=_csv(free_type),
|
|
163
|
+
cardRequired=_bool(card_required),
|
|
164
|
+
region=region,
|
|
165
|
+
commercialUse=_csv(commercial_use),
|
|
166
|
+
refill=_csv(refill),
|
|
167
|
+
status=_csv(status),
|
|
168
|
+
changedSince=_date(changed_since),
|
|
169
|
+
fields=_csv(fields),
|
|
170
|
+
page=page,
|
|
171
|
+
limit=limit,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _models_request(
|
|
176
|
+
*,
|
|
177
|
+
q: Optional[str],
|
|
178
|
+
family: Optional[str],
|
|
179
|
+
provider: Optional[str],
|
|
180
|
+
changed_since: Optional[DateLike],
|
|
181
|
+
page: Optional[int],
|
|
182
|
+
limit: Optional[int],
|
|
183
|
+
) -> Request:
|
|
184
|
+
return "/models", _params(
|
|
185
|
+
q=q,
|
|
186
|
+
family=family,
|
|
187
|
+
provider=provider,
|
|
188
|
+
changedSince=_date(changed_since),
|
|
189
|
+
page=page,
|
|
190
|
+
limit=limit,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _search_request(model: str) -> Request:
|
|
195
|
+
"""``where()``'s fallback: up to 20 models whose name matches."""
|
|
196
|
+
return "/models", _params(q=model.strip(), limit=20)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _changes_request(
|
|
200
|
+
*,
|
|
201
|
+
since: Optional[DateLike],
|
|
202
|
+
kind: Optional[Union[ChangeKind, Iterable[ChangeKind]]],
|
|
203
|
+
hub: Optional[ChangesHub],
|
|
204
|
+
page: Optional[int],
|
|
205
|
+
limit: Optional[int],
|
|
206
|
+
) -> Request:
|
|
207
|
+
return "/changes", _params(
|
|
208
|
+
since=_date(since, day_only=True), kind=_csv(kind), hub=hub, page=page, limit=limit
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _deadlines_request(
|
|
213
|
+
*,
|
|
214
|
+
hub: Optional[ChangesHub],
|
|
215
|
+
provider: Optional[str],
|
|
216
|
+
within_days: Optional[int],
|
|
217
|
+
page: Optional[int],
|
|
218
|
+
limit: Optional[int],
|
|
219
|
+
) -> Request:
|
|
220
|
+
return "/deadlines", _params(
|
|
221
|
+
hub=hub, provider=provider, withinDays=within_days, page=page, limit=limit
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _eligibility_request(
|
|
226
|
+
*,
|
|
227
|
+
student: bool,
|
|
228
|
+
startup: Optional[Startup],
|
|
229
|
+
country: Optional[str],
|
|
230
|
+
card: bool,
|
|
231
|
+
building: Optional[Building],
|
|
232
|
+
limit: Optional[int],
|
|
233
|
+
) -> Request:
|
|
234
|
+
return "/eligibility", _params(
|
|
235
|
+
student="1" if student else None,
|
|
236
|
+
startup=startup,
|
|
237
|
+
country=country.upper() if country else None,
|
|
238
|
+
card=None if card else "no",
|
|
239
|
+
building=building,
|
|
240
|
+
limit=limit,
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _headers(api_key: Optional[str], user_agent: Optional[str]) -> Dict[str, str]:
|
|
245
|
+
agent = f"aifree-python/{__version__}"
|
|
246
|
+
headers = {
|
|
247
|
+
"accept": "application/json",
|
|
248
|
+
"user-agent": f"{user_agent} {agent}" if user_agent else agent,
|
|
249
|
+
}
|
|
250
|
+
if api_key:
|
|
251
|
+
headers["x-api-key"] = api_key
|
|
252
|
+
return headers
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _settings(
|
|
256
|
+
api_key: Optional[str], base_url: Optional[str]
|
|
257
|
+
) -> Tuple[Optional[str], str]:
|
|
258
|
+
key = api_key if api_key is not None else os.environ.get("AIFREE_API_KEY") or None
|
|
259
|
+
base = base_url or os.environ.get("AIFREE_API_URL") or DEFAULT_BASE_URL
|
|
260
|
+
return key, base.rstrip("/")
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _json(response: httpx.Response) -> Any:
|
|
264
|
+
if not response.is_success:
|
|
265
|
+
raise _error(response)
|
|
266
|
+
return response.json()
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class Client:
|
|
270
|
+
"""Synchronous client for the aifree.dev API v1.
|
|
271
|
+
|
|
272
|
+
``api_key`` (default: ``AIFREE_API_KEY``) raises the rate limit from 600
|
|
273
|
+
to 6,000 requests per 15 minutes; ``base_url`` (default:
|
|
274
|
+
``AIFREE_API_URL``, else ``https://aifree.dev/api/v1``) points it at
|
|
275
|
+
another server. Use it as a context manager, or call ``close()``.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
def __init__(
|
|
279
|
+
self,
|
|
280
|
+
api_key: Optional[str] = None,
|
|
281
|
+
*,
|
|
282
|
+
base_url: Optional[str] = None,
|
|
283
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
284
|
+
user_agent: Optional[str] = None,
|
|
285
|
+
http_client: Optional[httpx.Client] = None,
|
|
286
|
+
) -> None:
|
|
287
|
+
key, self.base_url = _settings(api_key, base_url)
|
|
288
|
+
self._headers = _headers(key, user_agent)
|
|
289
|
+
self._own = http_client is None
|
|
290
|
+
self._http = http_client or httpx.Client(timeout=timeout, follow_redirects=True)
|
|
291
|
+
|
|
292
|
+
def __enter__(self) -> "Client":
|
|
293
|
+
return self
|
|
294
|
+
|
|
295
|
+
def __exit__(self, *exc: object) -> None:
|
|
296
|
+
self.close()
|
|
297
|
+
|
|
298
|
+
def close(self) -> None:
|
|
299
|
+
if self._own:
|
|
300
|
+
self._http.close()
|
|
301
|
+
|
|
302
|
+
def _get(self, path: str, params: Optional[Mapping[str, str]] = None) -> Any:
|
|
303
|
+
response = self._http.get(
|
|
304
|
+
f"{self.base_url}{path}", params=params, headers=self._headers
|
|
305
|
+
)
|
|
306
|
+
return _json(response)
|
|
307
|
+
|
|
308
|
+
def offers(
|
|
309
|
+
self,
|
|
310
|
+
q: Optional[str] = None,
|
|
311
|
+
*,
|
|
312
|
+
category: Optional[Union[Category, Iterable[Category]]] = None,
|
|
313
|
+
audience: Optional[Union[str, Iterable[str]]] = None,
|
|
314
|
+
free_type: Optional[Union[FreeType, Iterable[FreeType]]] = None,
|
|
315
|
+
card_required: Optional[bool] = None,
|
|
316
|
+
region: Optional[str] = None,
|
|
317
|
+
commercial_use: Optional[Union[str, Iterable[str]]] = None,
|
|
318
|
+
refill: Optional[Union[Refill, Iterable[Refill]]] = None,
|
|
319
|
+
status: Optional[Union[OfferStatus, Iterable[OfferStatus]]] = None,
|
|
320
|
+
changed_since: Optional[DateLike] = None,
|
|
321
|
+
fields: Optional[Iterable[str]] = None,
|
|
322
|
+
page: Optional[int] = None,
|
|
323
|
+
limit: Optional[int] = None,
|
|
324
|
+
) -> Page[Offer]:
|
|
325
|
+
"""``GET /offers``: the catalog, filtered; one page (``limit`` 1-200, default 50)."""
|
|
326
|
+
return cast(Page[Offer], self._get(*_offers_request(**_args(locals()))))
|
|
327
|
+
|
|
328
|
+
def offer(self, slug: str) -> Item[Offer]:
|
|
329
|
+
"""``GET /offers/{slug}``: one offer; ``AifreeError`` 404 when unknown."""
|
|
330
|
+
return cast(Item[Offer], self._get(f"/offers/{_quote(slug)}"))
|
|
331
|
+
|
|
332
|
+
def models(
|
|
333
|
+
self,
|
|
334
|
+
q: Optional[str] = None,
|
|
335
|
+
*,
|
|
336
|
+
family: Optional[str] = None,
|
|
337
|
+
provider: Optional[str] = None,
|
|
338
|
+
changed_since: Optional[DateLike] = None,
|
|
339
|
+
page: Optional[int] = None,
|
|
340
|
+
limit: Optional[int] = None,
|
|
341
|
+
) -> Page[ModelSummary]:
|
|
342
|
+
"""``GET /models``: every model served free somewhere, most sources first."""
|
|
343
|
+
return cast(Page[ModelSummary], self._get(*_models_request(**_args(locals()))))
|
|
344
|
+
|
|
345
|
+
def where(self, model: str) -> WhereResult:
|
|
346
|
+
"""Where a model is free: its sources with RPM/RPD/TPM and card rule.
|
|
347
|
+
|
|
348
|
+
An exact slug (or alias) is looked up directly; otherwise the name is
|
|
349
|
+
searched and a single match is looked up. Several matches come back in
|
|
350
|
+
``matches`` with ``model`` set to ``None``.
|
|
351
|
+
"""
|
|
352
|
+
slug = _slug(model)
|
|
353
|
+
if not slug:
|
|
354
|
+
raise ValueError("where: model name is empty")
|
|
355
|
+
try:
|
|
356
|
+
item = self._get(f"/models/{_quote(slug)}")
|
|
357
|
+
return {"model": item["data"], "matches": []}
|
|
358
|
+
except AifreeError as err:
|
|
359
|
+
if err.status != 404:
|
|
360
|
+
raise
|
|
361
|
+
page = self._get(*_search_request(model))
|
|
362
|
+
matches = page["data"]
|
|
363
|
+
if len(matches) != 1:
|
|
364
|
+
return {"model": None, "matches": matches}
|
|
365
|
+
item = self._get(f"/models/{_quote(matches[0]['slug'])}")
|
|
366
|
+
return {"model": item["data"], "matches": matches}
|
|
367
|
+
|
|
368
|
+
def eligibility(
|
|
369
|
+
self,
|
|
370
|
+
*,
|
|
371
|
+
student: bool = False,
|
|
372
|
+
startup: Optional[Startup] = None,
|
|
373
|
+
country: Optional[str] = None,
|
|
374
|
+
card: bool = True,
|
|
375
|
+
building: Optional[Building] = None,
|
|
376
|
+
limit: Optional[int] = None,
|
|
377
|
+
) -> Item[EligibilityResult]:
|
|
378
|
+
"""``GET /eligibility``: offers a profile can claim (``card=False``: no card)."""
|
|
379
|
+
return cast(
|
|
380
|
+
Item[EligibilityResult], self._get(*_eligibility_request(**_args(locals())))
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
def changes(
|
|
384
|
+
self,
|
|
385
|
+
*,
|
|
386
|
+
since: Optional[DateLike] = None,
|
|
387
|
+
kind: Optional[Union[ChangeKind, Iterable[ChangeKind]]] = None,
|
|
388
|
+
hub: Optional[ChangesHub] = None,
|
|
389
|
+
page: Optional[int] = None,
|
|
390
|
+
limit: Optional[int] = None,
|
|
391
|
+
) -> Page[Change]:
|
|
392
|
+
"""``GET /changes``: changelog events, newest first (``since`` is a day)."""
|
|
393
|
+
return cast(Page[Change], self._get(*_changes_request(**_args(locals()))))
|
|
394
|
+
|
|
395
|
+
def deadlines(
|
|
396
|
+
self,
|
|
397
|
+
*,
|
|
398
|
+
hub: Optional[ChangesHub] = None,
|
|
399
|
+
provider: Optional[str] = None,
|
|
400
|
+
within_days: Optional[int] = None,
|
|
401
|
+
page: Optional[int] = None,
|
|
402
|
+
limit: Optional[int] = None,
|
|
403
|
+
) -> DeadlinesPage:
|
|
404
|
+
"""``GET /deadlines``: offers ending within ``within_days`` (default 30), soonest first."""
|
|
405
|
+
return cast(DeadlinesPage, self._get(*_deadlines_request(**_args(locals()))))
|
|
406
|
+
|
|
407
|
+
def providers(self) -> Page[Provider]:
|
|
408
|
+
"""``GET /providers``: providers with their public offers."""
|
|
409
|
+
return cast(Page[Provider], self._get("/providers"))
|
|
410
|
+
|
|
411
|
+
def best_lists(self) -> Page[BestListSummary]:
|
|
412
|
+
"""``GET /best``: the curated "best free X" lists with the names of their picks."""
|
|
413
|
+
return cast(Page[BestListSummary], self._get("/best"))
|
|
414
|
+
|
|
415
|
+
def best_list(self, slug: str) -> Item[BestList]:
|
|
416
|
+
"""``GET /best/{slug}``: one list with links, FAQ, sources and body; ``AifreeError`` 404 when unknown."""
|
|
417
|
+
return cast(Item[BestList], self._get(f"/best/{_quote(slug)}"))
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
class AsyncClient:
|
|
421
|
+
"""Asynchronous twin of :class:`Client` (same methods, awaited)."""
|
|
422
|
+
|
|
423
|
+
def __init__(
|
|
424
|
+
self,
|
|
425
|
+
api_key: Optional[str] = None,
|
|
426
|
+
*,
|
|
427
|
+
base_url: Optional[str] = None,
|
|
428
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
429
|
+
user_agent: Optional[str] = None,
|
|
430
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
431
|
+
) -> None:
|
|
432
|
+
key, self.base_url = _settings(api_key, base_url)
|
|
433
|
+
self._headers = _headers(key, user_agent)
|
|
434
|
+
self._own = http_client is None
|
|
435
|
+
self._http = http_client or httpx.AsyncClient(timeout=timeout, follow_redirects=True)
|
|
436
|
+
|
|
437
|
+
async def __aenter__(self) -> "AsyncClient":
|
|
438
|
+
return self
|
|
439
|
+
|
|
440
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
441
|
+
await self.aclose()
|
|
442
|
+
|
|
443
|
+
async def aclose(self) -> None:
|
|
444
|
+
if self._own:
|
|
445
|
+
await self._http.aclose()
|
|
446
|
+
|
|
447
|
+
async def _get(self, path: str, params: Optional[Mapping[str, str]] = None) -> Any:
|
|
448
|
+
response = await self._http.get(
|
|
449
|
+
f"{self.base_url}{path}", params=params, headers=self._headers
|
|
450
|
+
)
|
|
451
|
+
return _json(response)
|
|
452
|
+
|
|
453
|
+
async def offers(
|
|
454
|
+
self,
|
|
455
|
+
q: Optional[str] = None,
|
|
456
|
+
*,
|
|
457
|
+
category: Optional[Union[Category, Iterable[Category]]] = None,
|
|
458
|
+
audience: Optional[Union[str, Iterable[str]]] = None,
|
|
459
|
+
free_type: Optional[Union[FreeType, Iterable[FreeType]]] = None,
|
|
460
|
+
card_required: Optional[bool] = None,
|
|
461
|
+
region: Optional[str] = None,
|
|
462
|
+
commercial_use: Optional[Union[str, Iterable[str]]] = None,
|
|
463
|
+
refill: Optional[Union[Refill, Iterable[Refill]]] = None,
|
|
464
|
+
status: Optional[Union[OfferStatus, Iterable[OfferStatus]]] = None,
|
|
465
|
+
changed_since: Optional[DateLike] = None,
|
|
466
|
+
fields: Optional[Iterable[str]] = None,
|
|
467
|
+
page: Optional[int] = None,
|
|
468
|
+
limit: Optional[int] = None,
|
|
469
|
+
) -> Page[Offer]:
|
|
470
|
+
"""``GET /offers``: see :meth:`Client.offers`."""
|
|
471
|
+
return cast(Page[Offer], await self._get(*_offers_request(**_args(locals()))))
|
|
472
|
+
|
|
473
|
+
async def offer(self, slug: str) -> Item[Offer]:
|
|
474
|
+
"""``GET /offers/{slug}``: see :meth:`Client.offer`."""
|
|
475
|
+
return cast(Item[Offer], await self._get(f"/offers/{_quote(slug)}"))
|
|
476
|
+
|
|
477
|
+
async def models(
|
|
478
|
+
self,
|
|
479
|
+
q: Optional[str] = None,
|
|
480
|
+
*,
|
|
481
|
+
family: Optional[str] = None,
|
|
482
|
+
provider: Optional[str] = None,
|
|
483
|
+
changed_since: Optional[DateLike] = None,
|
|
484
|
+
page: Optional[int] = None,
|
|
485
|
+
limit: Optional[int] = None,
|
|
486
|
+
) -> Page[ModelSummary]:
|
|
487
|
+
"""``GET /models``: see :meth:`Client.models`."""
|
|
488
|
+
return cast(
|
|
489
|
+
Page[ModelSummary], await self._get(*_models_request(**_args(locals())))
|
|
490
|
+
)
|
|
491
|
+
|
|
492
|
+
async def where(self, model: str) -> WhereResult:
|
|
493
|
+
"""See :meth:`Client.where`."""
|
|
494
|
+
slug = _slug(model)
|
|
495
|
+
if not slug:
|
|
496
|
+
raise ValueError("where: model name is empty")
|
|
497
|
+
try:
|
|
498
|
+
item = await self._get(f"/models/{_quote(slug)}")
|
|
499
|
+
return {"model": item["data"], "matches": []}
|
|
500
|
+
except AifreeError as err:
|
|
501
|
+
if err.status != 404:
|
|
502
|
+
raise
|
|
503
|
+
page = await self._get(*_search_request(model))
|
|
504
|
+
matches = page["data"]
|
|
505
|
+
if len(matches) != 1:
|
|
506
|
+
return {"model": None, "matches": matches}
|
|
507
|
+
item = await self._get(f"/models/{_quote(matches[0]['slug'])}")
|
|
508
|
+
return {"model": item["data"], "matches": matches}
|
|
509
|
+
|
|
510
|
+
async def eligibility(
|
|
511
|
+
self,
|
|
512
|
+
*,
|
|
513
|
+
student: bool = False,
|
|
514
|
+
startup: Optional[Startup] = None,
|
|
515
|
+
country: Optional[str] = None,
|
|
516
|
+
card: bool = True,
|
|
517
|
+
building: Optional[Building] = None,
|
|
518
|
+
limit: Optional[int] = None,
|
|
519
|
+
) -> Item[EligibilityResult]:
|
|
520
|
+
"""``GET /eligibility``: see :meth:`Client.eligibility`."""
|
|
521
|
+
return cast(
|
|
522
|
+
Item[EligibilityResult],
|
|
523
|
+
await self._get(*_eligibility_request(**_args(locals()))),
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
async def changes(
|
|
527
|
+
self,
|
|
528
|
+
*,
|
|
529
|
+
since: Optional[DateLike] = None,
|
|
530
|
+
kind: Optional[Union[ChangeKind, Iterable[ChangeKind]]] = None,
|
|
531
|
+
hub: Optional[ChangesHub] = None,
|
|
532
|
+
page: Optional[int] = None,
|
|
533
|
+
limit: Optional[int] = None,
|
|
534
|
+
) -> Page[Change]:
|
|
535
|
+
"""``GET /changes``: see :meth:`Client.changes`."""
|
|
536
|
+
return cast(Page[Change], await self._get(*_changes_request(**_args(locals()))))
|
|
537
|
+
|
|
538
|
+
async def deadlines(
|
|
539
|
+
self,
|
|
540
|
+
*,
|
|
541
|
+
hub: Optional[ChangesHub] = None,
|
|
542
|
+
provider: Optional[str] = None,
|
|
543
|
+
within_days: Optional[int] = None,
|
|
544
|
+
page: Optional[int] = None,
|
|
545
|
+
limit: Optional[int] = None,
|
|
546
|
+
) -> DeadlinesPage:
|
|
547
|
+
"""``GET /deadlines``: see :meth:`Client.deadlines`."""
|
|
548
|
+
return cast(DeadlinesPage, await self._get(*_deadlines_request(**_args(locals()))))
|
|
549
|
+
|
|
550
|
+
async def providers(self) -> Page[Provider]:
|
|
551
|
+
"""``GET /providers``: see :meth:`Client.providers`."""
|
|
552
|
+
return cast(Page[Provider], await self._get("/providers"))
|
|
553
|
+
|
|
554
|
+
async def best_lists(self) -> Page[BestListSummary]:
|
|
555
|
+
"""``GET /best``: see :meth:`Client.best_lists`."""
|
|
556
|
+
return cast(Page[BestListSummary], await self._get("/best"))
|
|
557
|
+
|
|
558
|
+
async def best_list(self, slug: str) -> Item[BestList]:
|
|
559
|
+
"""``GET /best/{slug}``: see :meth:`Client.best_list`."""
|
|
560
|
+
return cast(Item[BestList], await self._get(f"/best/{_quote(slug)}"))
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _args(scope: Dict[str, Any]) -> Dict[str, Any]:
|
|
564
|
+
"""A method's keyword arguments (``locals()`` without ``self``)."""
|
|
565
|
+
return {k: v for k, v in scope.items() if k != "self"}
|
aifree/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.3.0"
|
aifree/py.typed
ADDED
|
File without changes
|
aifree/types.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
"""Response shapes of the aifree.dev API v1, as TypedDicts.
|
|
2
|
+
|
|
3
|
+
The API returns plain JSON; these types only describe it for editors and
|
|
4
|
+
type checkers (the client never validates or converts records). Field names
|
|
5
|
+
are the API's own (camelCase). The OpenAPI document at
|
|
6
|
+
``https://aifree.dev/api/v1/openapi.json`` is the reference.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import sys
|
|
12
|
+
from typing import Any, Dict, Generic, List, Literal, Optional, TypeVar
|
|
13
|
+
|
|
14
|
+
if sys.version_info >= (3, 11):
|
|
15
|
+
from typing import TypedDict
|
|
16
|
+
else: # Generic TypedDict needs typing_extensions before 3.11
|
|
17
|
+
from typing_extensions import TypedDict
|
|
18
|
+
|
|
19
|
+
Category = Literal["coding", "image", "audio", "video", "api-credits", "assistant", "other"]
|
|
20
|
+
Audience = Literal[
|
|
21
|
+
"developers",
|
|
22
|
+
"students",
|
|
23
|
+
"startups",
|
|
24
|
+
"creators",
|
|
25
|
+
"researchers",
|
|
26
|
+
"nonprofits",
|
|
27
|
+
"educators",
|
|
28
|
+
"everyone",
|
|
29
|
+
]
|
|
30
|
+
FreeType = Literal[
|
|
31
|
+
"free-tier",
|
|
32
|
+
"free-credits",
|
|
33
|
+
"free-trial",
|
|
34
|
+
"student-program",
|
|
35
|
+
"startup-program",
|
|
36
|
+
"nonprofit-program",
|
|
37
|
+
"fully-free",
|
|
38
|
+
]
|
|
39
|
+
Refill = Literal["once", "hourly", "daily", "weekly", "monthly", "unknown"]
|
|
40
|
+
OfferStatus = Literal["verified", "listed", "changed", "expired"]
|
|
41
|
+
ChangeKind = Literal[
|
|
42
|
+
"listed",
|
|
43
|
+
"verified",
|
|
44
|
+
"changed",
|
|
45
|
+
"terms_updated",
|
|
46
|
+
"expired",
|
|
47
|
+
"relisted",
|
|
48
|
+
"incident",
|
|
49
|
+
"incident_resolved",
|
|
50
|
+
]
|
|
51
|
+
ChangesHub = Literal[
|
|
52
|
+
"free-ai-coding-tools",
|
|
53
|
+
"free-api-credits",
|
|
54
|
+
"student-ai-deals",
|
|
55
|
+
"startup-ai-credits",
|
|
56
|
+
"free-ai-image-tools",
|
|
57
|
+
"free-ai-audio-tools",
|
|
58
|
+
"free-ai-video-tools",
|
|
59
|
+
]
|
|
60
|
+
Startup = Literal["none", "idea", "early", "funded"]
|
|
61
|
+
Building = Literal["any", "coding", "api-credits", "image", "audio", "video", "assistant"]
|
|
62
|
+
|
|
63
|
+
T = TypeVar("T")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Meta(TypedDict, total=False):
|
|
67
|
+
"""``meta`` of every response. List endpoints add the paging keys."""
|
|
68
|
+
|
|
69
|
+
version: str
|
|
70
|
+
license: str
|
|
71
|
+
attribution: str
|
|
72
|
+
total: int
|
|
73
|
+
page: int
|
|
74
|
+
limit: int
|
|
75
|
+
pages: int
|
|
76
|
+
approximate: bool
|
|
77
|
+
suggestions: List[Dict[str, Any]]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Page(TypedDict, Generic[T]):
|
|
81
|
+
"""A list response: ``data`` plus ``meta`` (``total``, ``page``, ``pages``…)."""
|
|
82
|
+
|
|
83
|
+
data: List[T]
|
|
84
|
+
meta: Meta
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class Item(TypedDict, Generic[T]):
|
|
88
|
+
"""A single-record response."""
|
|
89
|
+
|
|
90
|
+
data: T
|
|
91
|
+
meta: Meta
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class Amount(TypedDict):
|
|
95
|
+
unit: str
|
|
96
|
+
value: Optional[float]
|
|
97
|
+
recurring: bool
|
|
98
|
+
durationMonths: Optional[int]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Eligibility(TypedDict, total=False):
|
|
102
|
+
regions: List[str]
|
|
103
|
+
summary: str
|
|
104
|
+
requirements: List[str]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _ResetsBase(TypedDict):
|
|
108
|
+
period: Literal["hourly", "daily", "weekly", "monthly"]
|
|
109
|
+
at: Optional[str]
|
|
110
|
+
tz: Optional[str]
|
|
111
|
+
anchor: Optional[int]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class Resets(_ResetsBase, total=False):
|
|
115
|
+
"""``everyHours`` (1-23 or ``None``) is present on an ``hourly`` period only."""
|
|
116
|
+
|
|
117
|
+
everyHours: Optional[int]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class RateLimit(TypedDict, total=False):
|
|
121
|
+
"""Published caps; ``None`` (or a missing ``tpd`` / ``rpmo``) = not published."""
|
|
122
|
+
|
|
123
|
+
rpm: Optional[int]
|
|
124
|
+
rpd: Optional[int]
|
|
125
|
+
tpm: Optional[int]
|
|
126
|
+
tpd: Optional[int]
|
|
127
|
+
rpmo: Optional[int]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class OfferModel(TypedDict, total=False):
|
|
131
|
+
name: str
|
|
132
|
+
rateLimit: RateLimit
|
|
133
|
+
apiId: str
|
|
134
|
+
structuredOutput: bool
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class Offer(TypedDict, total=False):
|
|
138
|
+
"""A catalog record. With ``fields=`` only those keys (plus ``slug``) are present."""
|
|
139
|
+
|
|
140
|
+
slug: str
|
|
141
|
+
url: str
|
|
142
|
+
name: str
|
|
143
|
+
provider: str
|
|
144
|
+
vendorUrl: str
|
|
145
|
+
headline: str
|
|
146
|
+
whatYouGet: str
|
|
147
|
+
theCatch: Optional[str]
|
|
148
|
+
category: Category
|
|
149
|
+
secondaryCategories: List[Category]
|
|
150
|
+
audiences: List[Audience]
|
|
151
|
+
freeType: FreeType
|
|
152
|
+
openSource: bool
|
|
153
|
+
amount: Optional[Amount]
|
|
154
|
+
cardRequired: Optional[bool]
|
|
155
|
+
signupRequired: Optional[bool]
|
|
156
|
+
eligibility: Optional[Eligibility]
|
|
157
|
+
limits: List[str]
|
|
158
|
+
expiryDate: Optional[str]
|
|
159
|
+
listedAt: str
|
|
160
|
+
verifiedAt: Optional[str]
|
|
161
|
+
status: OfferStatus
|
|
162
|
+
riskStatus: str
|
|
163
|
+
relatedSlugs: List[str]
|
|
164
|
+
resets: Optional[Resets]
|
|
165
|
+
refill: Refill
|
|
166
|
+
models: Optional[List[OfferModel]]
|
|
167
|
+
selfHostAlternative: Optional[Dict[str, Any]]
|
|
168
|
+
requirements: Optional[List[Dict[str, Any]]]
|
|
169
|
+
apiBaseUrl: Optional[str]
|
|
170
|
+
apiCompat: Optional[Literal["openai", "anthropic", "google", "custom"]]
|
|
171
|
+
successorSlug: Optional[str]
|
|
172
|
+
commercialUse: Optional[Literal["yes", "no", "unknown"]]
|
|
173
|
+
updatedAt: str
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class Change(TypedDict):
|
|
177
|
+
id: str
|
|
178
|
+
slug: str
|
|
179
|
+
url: str
|
|
180
|
+
kind: ChangeKind
|
|
181
|
+
at: str
|
|
182
|
+
source: Literal["human", "monitor", "community", "probe", "ai"]
|
|
183
|
+
note: Optional[str]
|
|
184
|
+
offerStatus: OfferStatus
|
|
185
|
+
alternativesUrl: Optional[str]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class Deadline(TypedDict):
|
|
189
|
+
"""One offer ending soon (``GET /deadlines``). ``daysLeft`` 0 = ends today;
|
|
190
|
+
``status`` "listed" = not yet verified by a person."""
|
|
191
|
+
|
|
192
|
+
slug: str
|
|
193
|
+
name: str
|
|
194
|
+
provider: str
|
|
195
|
+
url: str
|
|
196
|
+
kind: str
|
|
197
|
+
expiryDate: str
|
|
198
|
+
endsAt: str
|
|
199
|
+
daysLeft: int
|
|
200
|
+
status: Literal["verified", "listed"]
|
|
201
|
+
freeType: FreeType
|
|
202
|
+
category: Category
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class DeadlinesMeta(Meta, total=False):
|
|
206
|
+
withinDays: int
|
|
207
|
+
hub: Optional[ChangesHub]
|
|
208
|
+
provider: Optional[str]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class DeadlinesPage(TypedDict):
|
|
212
|
+
"""``GET /deadlines``: ``data`` plus ``meta`` with the window and filters."""
|
|
213
|
+
|
|
214
|
+
data: List[Deadline]
|
|
215
|
+
meta: DeadlinesMeta
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class ProviderOffer(TypedDict):
|
|
219
|
+
slug: str
|
|
220
|
+
name: str
|
|
221
|
+
url: str
|
|
222
|
+
status: OfferStatus
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class Provider(TypedDict):
|
|
226
|
+
slug: str
|
|
227
|
+
name: str
|
|
228
|
+
offerCount: int
|
|
229
|
+
categories: List[Category]
|
|
230
|
+
freeTypes: List[FreeType]
|
|
231
|
+
offers: List[ProviderOffer]
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class BestListSummary(TypedDict):
|
|
235
|
+
"""One list of ``GET /best``: the curated "best free X" lists."""
|
|
236
|
+
|
|
237
|
+
slug: str
|
|
238
|
+
title: str
|
|
239
|
+
description: str
|
|
240
|
+
published: str
|
|
241
|
+
checked: str
|
|
242
|
+
image: Optional[str]
|
|
243
|
+
url: str
|
|
244
|
+
markdownUrl: str
|
|
245
|
+
picks: List[str]
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class BestPick(TypedDict):
|
|
249
|
+
name: str
|
|
250
|
+
url: str
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class BestFaq(TypedDict):
|
|
254
|
+
question: str
|
|
255
|
+
answer: str
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
class BestList(BestListSummary):
|
|
259
|
+
"""``GET /best/{slug}``: the summary plus picks with links, FAQ, sources and Markdown body."""
|
|
260
|
+
|
|
261
|
+
items: List[BestPick]
|
|
262
|
+
faqs: List[BestFaq]
|
|
263
|
+
sources: List[str]
|
|
264
|
+
body: str
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class EligibilityAnswers(TypedDict):
|
|
268
|
+
student: bool
|
|
269
|
+
startup: Startup
|
|
270
|
+
country: str
|
|
271
|
+
noCard: bool
|
|
272
|
+
building: Building
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class EligibleOffer(TypedDict):
|
|
276
|
+
slug: str
|
|
277
|
+
url: str
|
|
278
|
+
name: str
|
|
279
|
+
provider: str
|
|
280
|
+
headline: str
|
|
281
|
+
category: Category
|
|
282
|
+
freeType: FreeType
|
|
283
|
+
status: OfferStatus
|
|
284
|
+
cardRequired: Optional[bool]
|
|
285
|
+
usdValue: float
|
|
286
|
+
verifiedAt: Optional[str]
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
class EligibilityResult(TypedDict):
|
|
290
|
+
answers: EligibilityAnswers
|
|
291
|
+
profile: List[str]
|
|
292
|
+
total: int
|
|
293
|
+
verifiedCount: int
|
|
294
|
+
listedCount: int
|
|
295
|
+
totalUsd: float
|
|
296
|
+
unrecordedRegionCount: int
|
|
297
|
+
note: str
|
|
298
|
+
unlockUrl: str
|
|
299
|
+
offers: List[EligibleOffer]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class ModelSummary(TypedDict):
|
|
303
|
+
slug: str
|
|
304
|
+
url: str
|
|
305
|
+
name: str
|
|
306
|
+
family: Optional[str]
|
|
307
|
+
vendor: Optional[str]
|
|
308
|
+
openWeights: Optional[bool]
|
|
309
|
+
contextK: Optional[int]
|
|
310
|
+
toolCalling: Optional[bool]
|
|
311
|
+
vision: Optional[bool]
|
|
312
|
+
structuredOutput: Optional[bool]
|
|
313
|
+
sourceCount: int
|
|
314
|
+
verifiedSourceCount: int
|
|
315
|
+
indexable: bool
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
class ModelSource(TypedDict):
|
|
319
|
+
offerSlug: str
|
|
320
|
+
offerUrl: str
|
|
321
|
+
offerName: str
|
|
322
|
+
provider: str
|
|
323
|
+
servedAs: str
|
|
324
|
+
verified: bool
|
|
325
|
+
cardRequired: Optional[bool]
|
|
326
|
+
contextK: Optional[int]
|
|
327
|
+
structuredOutput: Optional[bool]
|
|
328
|
+
rateLimit: RateLimit
|
|
329
|
+
resets: Optional[Resets]
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
class ModelDetail(ModelSummary):
|
|
333
|
+
benchmarkUrl: Optional[str]
|
|
334
|
+
sources: List[ModelSource]
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
class WhereResult(TypedDict):
|
|
338
|
+
"""``where()``: ``model`` when one model matched, else ``None`` and the
|
|
339
|
+
candidates in ``matches`` (empty when nothing matched)."""
|
|
340
|
+
|
|
341
|
+
model: Optional[ModelDetail]
|
|
342
|
+
matches: List[ModelSummary]
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: aifree
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Python client for the aifree.dev API: verified free AI offers, free LLM API tiers and where each model is free.
|
|
5
|
+
Project-URL: Homepage, https://aifree.dev/developers
|
|
6
|
+
Project-URL: Documentation, https://aifree.dev/developers
|
|
7
|
+
Project-URL: Source, https://github.com/aifree4dev/aifree.dev
|
|
8
|
+
Project-URL: Issues, https://github.com/aifree4dev/aifree.dev/issues
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
Keywords: ai credits,aifree,free ai,free tier,llm api
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Requires-Dist: httpx<1,>=0.25
|
|
17
|
+
Requires-Dist: typing-extensions>=4.7; python_version < '3.11'
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# aifree (Python)
|
|
23
|
+
|
|
24
|
+
Python client for the [aifree.dev](https://aifree.dev) API v1: verified free
|
|
25
|
+
AI offers, free LLM API tiers and credits, and where each model is free with
|
|
26
|
+
its rate limits. Sync and async, typed, built on [httpx](https://www.python-httpx.org).
|
|
27
|
+
Data is CC BY 4.0: link to `https://aifree.dev` when you reuse it (every
|
|
28
|
+
record carries its `url`).
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
pip install aifree
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Python 3.9+.
|
|
35
|
+
|
|
36
|
+
## Usage
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from aifree import Client
|
|
40
|
+
|
|
41
|
+
with Client() as aifree:
|
|
42
|
+
page = aifree.offers(category="api-credits", card_required=False, limit=5)
|
|
43
|
+
print(page["meta"]["total"], "offers")
|
|
44
|
+
for offer in page["data"]:
|
|
45
|
+
print(offer["name"], "-", offer["url"])
|
|
46
|
+
|
|
47
|
+
# Where can I call gpt-oss-120b for free, and at what RPM?
|
|
48
|
+
found = aifree.where("gpt-oss-120b")
|
|
49
|
+
if found["model"]:
|
|
50
|
+
for source in found["model"]["sources"]:
|
|
51
|
+
print(source["provider"], source["rateLimit"]["rpm"], "RPM")
|
|
52
|
+
|
|
53
|
+
# Which free offers end in the next two weeks?
|
|
54
|
+
for deadline in aifree.deadlines(within_days=14)["data"]:
|
|
55
|
+
print(deadline["expiryDate"], deadline["name"], deadline["url"])
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Async, same methods:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
import asyncio
|
|
62
|
+
from aifree import AsyncClient
|
|
63
|
+
|
|
64
|
+
async def main() -> None:
|
|
65
|
+
async with AsyncClient() as aifree:
|
|
66
|
+
result = await aifree.eligibility(student=True, country="VN", card=False)
|
|
67
|
+
print(result["data"]["total"], "offers,", result["data"]["totalUsd"], "USD")
|
|
68
|
+
|
|
69
|
+
asyncio.run(main())
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
| Method | Endpoint |
|
|
73
|
+
| ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
|
|
74
|
+
| `offers(q, category, audience, free_type, card_required, region, commercial_use, refill, status, changed_since, fields, page, limit)` | `GET /offers`: the catalog, filtered, one page |
|
|
75
|
+
| `offer(slug)` | `GET /offers/{slug}` |
|
|
76
|
+
| `models(q, family, provider, changed_since, page, limit)` | `GET /models`: every model served free somewhere |
|
|
77
|
+
| `where(model)` | `GET /models/{model}` by slug or alias, else a name search |
|
|
78
|
+
| `eligibility(student, startup, country, card, building, limit)` | `GET /eligibility`: what a profile can claim (the `/unlock` quiz) |
|
|
79
|
+
| `changes(since, kind, hub, page, limit)` | `GET /changes`: changelog events, newest first |
|
|
80
|
+
| `deadlines(hub, provider, within_days, page, limit)` | `GET /deadlines`: offers ending soon, soonest first |
|
|
81
|
+
| `providers()` | `GET /providers` |
|
|
82
|
+
| `best_lists()`, `best_list(slug)` | `GET /best`, `GET /best/{slug}`: the curated "best free X" lists |
|
|
83
|
+
|
|
84
|
+
Responses are the API's JSON as plain dicts (`{"data": ..., "meta": ...}`),
|
|
85
|
+
typed with the `TypedDict`s in `aifree.types`, so field names are the API's
|
|
86
|
+
own (`cardRequired`, `rateLimit`). List parameters take a string or a list
|
|
87
|
+
(`category=["audio", "image"]`); dates take a `date`, a time-zone-aware
|
|
88
|
+
`datetime` or a string. `where()` returns `{"model": ..., "matches": [...]}`:
|
|
89
|
+
`model` is set when one model matched, otherwise `matches` lists the
|
|
90
|
+
candidates. Parameters and fields: [API v1 docs](https://aifree.dev/developers)
|
|
91
|
+
and the OpenAPI document at `https://aifree.dev/api/v1/openapi.json`.
|
|
92
|
+
|
|
93
|
+
## Keys, limits and errors
|
|
94
|
+
|
|
95
|
+
Without a key: 600 requests per 15 minutes per IP. A free key from
|
|
96
|
+
[aifree.dev/developers](https://aifree.dev/developers) raises that to 6,000:
|
|
97
|
+
`Client("afk_...")` or the `AIFREE_API_KEY` environment variable.
|
|
98
|
+
`AIFREE_API_URL` (or `base_url=`) points the client at another server.
|
|
99
|
+
|
|
100
|
+
A non-2xx answer raises `aifree.AifreeError` with `status`, the API's stable
|
|
101
|
+
`code` (`not_found`, `rate_limited`, `invalid_request`...), `details` (the
|
|
102
|
+
problems of a 400) and `retry_after` (seconds to wait on a 429 or 5xx). The
|
|
103
|
+
client does not retry by itself:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
import time
|
|
107
|
+
from aifree import AifreeError, Client
|
|
108
|
+
|
|
109
|
+
with Client() as aifree:
|
|
110
|
+
try:
|
|
111
|
+
changes = aifree.changes(since="2026-10-01", kind="expired")
|
|
112
|
+
except AifreeError as err:
|
|
113
|
+
if err.retry_after:
|
|
114
|
+
time.sleep(err.retry_after)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Pass `user_agent="my-app/1.0"` to name your app in the `User-Agent`, or
|
|
118
|
+
`http_client=` to reuse your own `httpx.Client` / `httpx.AsyncClient`
|
|
119
|
+
(proxies, transports, timeouts).
|
|
120
|
+
|
|
121
|
+
## Development
|
|
122
|
+
|
|
123
|
+
```sh
|
|
124
|
+
cd packages/python
|
|
125
|
+
python3 -m venv .venv && .venv/bin/pip install -e '.[test]'
|
|
126
|
+
.venv/bin/python -m pytest
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
The tests start a local HTTP server that answers with the API's recorded
|
|
130
|
+
responses (`app/lib/openapi-examples.json`), so they run from the
|
|
131
|
+
repository. From the repository root, `bun test tests/python-client.test.ts`
|
|
132
|
+
also runs the client against the real query parsers of the API (it uses
|
|
133
|
+
`packages/python/.venv` when present and skips without httpx).
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
|
|
137
|
+
MIT. The data is CC BY 4.0 (aifree.dev).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
aifree/__init__.py,sha256=Did0kwZQAJY2d0CblO4eIk8GS9JIXYXbfcy_tsCtYFA,329
|
|
2
|
+
aifree/_client.py,sha256=fNzaXj4RbI6I7JzprecSEL-NSAQy33t3s3Rt04ys4xM,18847
|
|
3
|
+
aifree/_version.py,sha256=VrXpHDu3erkzwl_WXrqINBm9xWkcyUy53IQOj042dOs,22
|
|
4
|
+
aifree/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
aifree/types.py,sha256=a_YAFXkg0T4_snerh1myTmNfs403lNrvgcHeatm8-9c,7766
|
|
6
|
+
aifree-0.3.0.dist-info/METADATA,sha256=XxV1hpWAlxz28WdaXu_5L_1RWRoNw4D3iuddGyu17qs,6752
|
|
7
|
+
aifree-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
aifree-0.3.0.dist-info/RECORD,,
|