syncso 0.1.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.
- syncso/__init__.py +7 -0
- syncso/_client.py +364 -0
- syncso/_errors.py +27 -0
- syncso/_version.py +1 -0
- syncso/py.typed +0 -0
- syncso-0.1.0.dist-info/METADATA +148 -0
- syncso-0.1.0.dist-info/RECORD +9 -0
- syncso-0.1.0.dist-info/WHEEL +4 -0
- syncso-0.1.0.dist-info/licenses/LICENSE +21 -0
syncso/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Official Python client for the SyncSo API: live events and things to do."""
|
|
2
|
+
|
|
3
|
+
from ._client import AsyncSyncSo, SyncSo
|
|
4
|
+
from ._errors import SyncSoConnectionError, SyncSoError
|
|
5
|
+
from ._version import __version__
|
|
6
|
+
|
|
7
|
+
__all__ = ["SyncSo", "AsyncSyncSo", "SyncSoError", "SyncSoConnectionError", "__version__"]
|
syncso/_client.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""The SyncSo API client, sync and async.
|
|
2
|
+
|
|
3
|
+
from syncso import SyncSo
|
|
4
|
+
syncso = SyncSo() # reads SYNCSO_API_KEY
|
|
5
|
+
r = syncso.search(query="live jazz", location={"city": "New York"})
|
|
6
|
+
|
|
7
|
+
Keyword arguments are the API's own field names, sent as they are: the API
|
|
8
|
+
rejects a field it does not know, so a typo fails loudly instead of quietly
|
|
9
|
+
widening a search.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import random
|
|
18
|
+
import time
|
|
19
|
+
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Sequence
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from ._errors import SyncSoConnectionError, SyncSoError
|
|
24
|
+
from ._version import __version__
|
|
25
|
+
|
|
26
|
+
DEFAULT_BASE_URL = "https://api.syncso.com/v1"
|
|
27
|
+
# Local Life Intelligence reads the whole catalogue: 3-15 s, sometimes more.
|
|
28
|
+
SLOW_TIMEOUT = 120.0
|
|
29
|
+
DEFAULT_TIMEOUT = 60.0
|
|
30
|
+
|
|
31
|
+
_NO_RETRY_CODES = {"quota_exceeded", "insufficient_credits"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _body(fields: Dict[str, Any]) -> Dict[str, Any]:
|
|
35
|
+
return {k: v for k, v in fields.items() if v is not None}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _backoff(attempt: int) -> float:
|
|
39
|
+
return min(8.0, 0.5 * 2**attempt) * (0.75 + random.random() * 0.5)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _error(res: httpx.Response) -> SyncSoError:
|
|
43
|
+
request_id = res.headers.get("x-request-id")
|
|
44
|
+
retry_after: Optional[float] = None
|
|
45
|
+
try:
|
|
46
|
+
header = float(res.headers.get("retry-after", ""))
|
|
47
|
+
retry_after = header if header > 0 else None
|
|
48
|
+
except ValueError:
|
|
49
|
+
pass
|
|
50
|
+
code, message = "unknown", f"The API answered {res.status_code}."
|
|
51
|
+
try:
|
|
52
|
+
payload = res.json()
|
|
53
|
+
err = payload.get("error") or {}
|
|
54
|
+
code = err.get("code") or code
|
|
55
|
+
message = err.get("message") or message
|
|
56
|
+
request_id = err.get("request_id") or request_id
|
|
57
|
+
if isinstance(payload.get("retry_after_s"), (int, float)):
|
|
58
|
+
retry_after = float(payload["retry_after_s"])
|
|
59
|
+
except (ValueError, AttributeError):
|
|
60
|
+
# Not JSON: a proxy or transport error. Keep the status.
|
|
61
|
+
if res.status_code >= 500:
|
|
62
|
+
code = "transport"
|
|
63
|
+
return SyncSoError(res.status_code, code, message, request_id, retry_after)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _retryable(err: SyncSoError) -> bool:
|
|
67
|
+
if err.retry_after is not None: # rate_limited, catalogue_busy
|
|
68
|
+
return True
|
|
69
|
+
if err.code in _NO_RETRY_CODES:
|
|
70
|
+
return False
|
|
71
|
+
return err.status >= 500
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _sse(lines: Iterator[str]) -> Iterator[Dict[str, Any]]:
|
|
75
|
+
"""Server-sent events, as {"event", "data"}; an `error` event is raised."""
|
|
76
|
+
event, data = "message", []
|
|
77
|
+
for line in lines:
|
|
78
|
+
if line == "":
|
|
79
|
+
if data:
|
|
80
|
+
yield _event(event, data)
|
|
81
|
+
event, data = "message", []
|
|
82
|
+
continue
|
|
83
|
+
if line.startswith(":"):
|
|
84
|
+
continue
|
|
85
|
+
field, _, value = line.partition(":")
|
|
86
|
+
value = value[1:] if value.startswith(" ") else value
|
|
87
|
+
if field == "event":
|
|
88
|
+
event = value
|
|
89
|
+
elif field == "data":
|
|
90
|
+
data.append(value)
|
|
91
|
+
if data:
|
|
92
|
+
yield _event(event, data)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _event(event: str, data: List[str]) -> Dict[str, Any]:
|
|
96
|
+
raw = "\n".join(data)
|
|
97
|
+
try:
|
|
98
|
+
parsed: Any = json.loads(raw)
|
|
99
|
+
except ValueError:
|
|
100
|
+
parsed = raw
|
|
101
|
+
if event == "error":
|
|
102
|
+
err = (parsed.get("error") if isinstance(parsed, dict) else None) or {}
|
|
103
|
+
raise SyncSoError(200, err.get("code", "unknown"), err.get("message", "The stream failed."), err.get("request_id"), None)
|
|
104
|
+
return {"event": event, "data": parsed}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _Base:
|
|
108
|
+
def __init__(self, api_key: Optional[str], base_url: Optional[str], timeout: Optional[float], max_retries: int) -> None:
|
|
109
|
+
key = api_key or os.environ.get("SYNCSO_API_KEY")
|
|
110
|
+
if not key:
|
|
111
|
+
raise ValueError(
|
|
112
|
+
"No SyncSo API key. Pass api_key=... or set SYNCSO_API_KEY. "
|
|
113
|
+
"Create one at https://syncso.com/console"
|
|
114
|
+
)
|
|
115
|
+
self.base_url = (base_url or os.environ.get("SYNCSO_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
116
|
+
self._timeout = timeout
|
|
117
|
+
self.max_retries = max_retries
|
|
118
|
+
self._headers = {
|
|
119
|
+
"Authorization": f"Bearer {key}",
|
|
120
|
+
"User-Agent": f"syncso-python/{__version__}",
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
def _t(self, slow: bool) -> float:
|
|
124
|
+
return self._timeout if self._timeout is not None else (SLOW_TIMEOUT if slow else DEFAULT_TIMEOUT)
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def _lookup_params(images: Optional[int], include_ai: Optional[bool]) -> Dict[str, Any]:
|
|
128
|
+
params: Dict[str, Any] = {}
|
|
129
|
+
if images is not None:
|
|
130
|
+
params["images"] = images
|
|
131
|
+
if include_ai is not None:
|
|
132
|
+
params["include_ai"] = "true" if include_ai else "false"
|
|
133
|
+
return params
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class SyncSo(_Base):
|
|
137
|
+
"""Synchronous client. Use it as a context manager, or call `close()`."""
|
|
138
|
+
|
|
139
|
+
def __init__(
|
|
140
|
+
self,
|
|
141
|
+
api_key: Optional[str] = None,
|
|
142
|
+
*,
|
|
143
|
+
base_url: Optional[str] = None,
|
|
144
|
+
timeout: Optional[float] = None,
|
|
145
|
+
max_retries: int = 2,
|
|
146
|
+
http_client: Optional[httpx.Client] = None,
|
|
147
|
+
) -> None:
|
|
148
|
+
super().__init__(api_key, base_url, timeout, max_retries)
|
|
149
|
+
self._http = http_client or httpx.Client()
|
|
150
|
+
|
|
151
|
+
def __enter__(self) -> "SyncSo":
|
|
152
|
+
return self
|
|
153
|
+
|
|
154
|
+
def __exit__(self, *exc: object) -> None:
|
|
155
|
+
self.close()
|
|
156
|
+
|
|
157
|
+
def close(self) -> None:
|
|
158
|
+
self._http.close()
|
|
159
|
+
|
|
160
|
+
# ── endpoints ──
|
|
161
|
+
|
|
162
|
+
def search(self, *, location: Dict[str, Any], query: Optional[str] = None, **fields: Any) -> Dict[str, Any]:
|
|
163
|
+
"""Events and things to do for a query, place and time, ranked. 1 credit per 50 results.
|
|
164
|
+
|
|
165
|
+
Leave `query` out to browse by place and time alone. Other fields:
|
|
166
|
+
time_windows, limit, cursor, ranking, media, requirements, include.
|
|
167
|
+
"""
|
|
168
|
+
return self._request("POST", "/search", _body({"query": query, "location": location, **fields}))
|
|
169
|
+
|
|
170
|
+
def featured(self, *, location: Dict[str, Any], **fields: Any) -> Dict[str, Any]:
|
|
171
|
+
"""Curated picks for a place and time, no query. Starter plan and above."""
|
|
172
|
+
return self._request("POST", "/featured", _body({"location": location, **fields}))
|
|
173
|
+
|
|
174
|
+
def intelligence(self, message: str, **fields: Any) -> Dict[str, Any]:
|
|
175
|
+
"""Local Life Intelligence: the whole ask as one sentence, answered ranked, a reason for each.
|
|
176
|
+
|
|
177
|
+
Show `understood` first and the results in the order they come back.
|
|
178
|
+
Other fields: place, lat, lng, radius_mi, when, context, limit, reasons, include, cursor.
|
|
179
|
+
"""
|
|
180
|
+
return self._request("POST", "/intelligence", _body({"message": message, **fields}), slow=True)
|
|
181
|
+
|
|
182
|
+
def intelligence_stream(self, message: str, **fields: Any) -> Iterator[Dict[str, Any]]:
|
|
183
|
+
"""The same answer, as it is decided. Yields {"event", "data"}:
|
|
184
|
+
meta, stage, understood, result (data.item), result_patch, done.
|
|
185
|
+
"""
|
|
186
|
+
body = _body({"message": message, **fields})
|
|
187
|
+
for attempt in range(self.max_retries + 1):
|
|
188
|
+
try:
|
|
189
|
+
with self._http.stream(
|
|
190
|
+
"POST",
|
|
191
|
+
f"{self.base_url}/intelligence/stream",
|
|
192
|
+
json=body,
|
|
193
|
+
headers={**self._headers, "Accept": "text/event-stream"},
|
|
194
|
+
timeout=self._t(True),
|
|
195
|
+
) as res:
|
|
196
|
+
if res.status_code >= 400:
|
|
197
|
+
res.read()
|
|
198
|
+
err = _error(res)
|
|
199
|
+
if attempt < self.max_retries and _retryable(err):
|
|
200
|
+
time.sleep(err.retry_after if err.retry_after is not None else _backoff(attempt))
|
|
201
|
+
continue
|
|
202
|
+
raise err
|
|
203
|
+
yield from _sse(res.iter_lines())
|
|
204
|
+
return
|
|
205
|
+
except httpx.TransportError as exc:
|
|
206
|
+
if attempt < self.max_retries:
|
|
207
|
+
time.sleep(_backoff(attempt))
|
|
208
|
+
continue
|
|
209
|
+
raise SyncSoConnectionError(f"Could not reach the SyncSo API: {exc}") from exc
|
|
210
|
+
|
|
211
|
+
def experience(self, id: str, *, images: Optional[int] = None, include_ai: Optional[bool] = None) -> Dict[str, Any]:
|
|
212
|
+
"""One experience by id, every field. Free."""
|
|
213
|
+
return self._request("GET", f"/experiences/{id}", params=self._lookup_params(images, include_ai))
|
|
214
|
+
|
|
215
|
+
def experiences(self, ids: Sequence[str], *, images: Optional[int] = None, include_ai: Optional[bool] = None) -> Dict[str, Any]:
|
|
216
|
+
"""Up to 20 experiences by id, in that order; unknown ids in `not_found`. Free."""
|
|
217
|
+
params = {"ids": ",".join(ids), **self._lookup_params(images, include_ai)}
|
|
218
|
+
return self._request("GET", "/experiences", params=params)
|
|
219
|
+
|
|
220
|
+
def meta(self) -> Dict[str, Any]:
|
|
221
|
+
"""Supported cities and vocabularies, including the requirement tags."""
|
|
222
|
+
return self._request("GET", "/meta")
|
|
223
|
+
|
|
224
|
+
def catalog(self) -> Dict[str, Any]:
|
|
225
|
+
"""How many experiences each city holds right now."""
|
|
226
|
+
return self._request("GET", "/catalog")
|
|
227
|
+
|
|
228
|
+
def usage(self) -> Dict[str, Any]:
|
|
229
|
+
"""Month-to-date requests and credits, and the limits on this key."""
|
|
230
|
+
return self._request("GET", "/usage")
|
|
231
|
+
|
|
232
|
+
# ── transport ──
|
|
233
|
+
|
|
234
|
+
def _request(self, method: str, path: str, body: Any = None, *, params: Any = None, slow: bool = False) -> Dict[str, Any]:
|
|
235
|
+
for attempt in range(self.max_retries + 1):
|
|
236
|
+
try:
|
|
237
|
+
res = self._http.request(
|
|
238
|
+
method, f"{self.base_url}{path}", json=body, params=params,
|
|
239
|
+
headers=self._headers, timeout=self._t(slow),
|
|
240
|
+
)
|
|
241
|
+
except httpx.TransportError as exc:
|
|
242
|
+
if attempt < self.max_retries:
|
|
243
|
+
time.sleep(_backoff(attempt))
|
|
244
|
+
continue
|
|
245
|
+
raise SyncSoConnectionError(f"Could not reach the SyncSo API: {exc}") from exc
|
|
246
|
+
if res.is_success:
|
|
247
|
+
try:
|
|
248
|
+
return res.json()
|
|
249
|
+
except ValueError as exc:
|
|
250
|
+
raise SyncSoConnectionError(f"The API answered {res.status_code} with a body that is not JSON.") from exc
|
|
251
|
+
err = _error(res)
|
|
252
|
+
if attempt < self.max_retries and _retryable(err):
|
|
253
|
+
time.sleep(err.retry_after if err.retry_after is not None else _backoff(attempt))
|
|
254
|
+
continue
|
|
255
|
+
raise err
|
|
256
|
+
raise AssertionError("unreachable")
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class AsyncSyncSo(_Base):
|
|
260
|
+
"""The same client for asyncio. `async with AsyncSyncSo() as syncso: ...`"""
|
|
261
|
+
|
|
262
|
+
def __init__(
|
|
263
|
+
self,
|
|
264
|
+
api_key: Optional[str] = None,
|
|
265
|
+
*,
|
|
266
|
+
base_url: Optional[str] = None,
|
|
267
|
+
timeout: Optional[float] = None,
|
|
268
|
+
max_retries: int = 2,
|
|
269
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
270
|
+
) -> None:
|
|
271
|
+
super().__init__(api_key, base_url, timeout, max_retries)
|
|
272
|
+
self._http = http_client or httpx.AsyncClient()
|
|
273
|
+
|
|
274
|
+
async def __aenter__(self) -> "AsyncSyncSo":
|
|
275
|
+
return self
|
|
276
|
+
|
|
277
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
278
|
+
await self.close()
|
|
279
|
+
|
|
280
|
+
async def close(self) -> None:
|
|
281
|
+
await self._http.aclose()
|
|
282
|
+
|
|
283
|
+
async def search(self, *, location: Dict[str, Any], query: Optional[str] = None, **fields: Any) -> Dict[str, Any]:
|
|
284
|
+
return await self._request("POST", "/search", _body({"query": query, "location": location, **fields}))
|
|
285
|
+
|
|
286
|
+
async def featured(self, *, location: Dict[str, Any], **fields: Any) -> Dict[str, Any]:
|
|
287
|
+
return await self._request("POST", "/featured", _body({"location": location, **fields}))
|
|
288
|
+
|
|
289
|
+
async def intelligence(self, message: str, **fields: Any) -> Dict[str, Any]:
|
|
290
|
+
return await self._request("POST", "/intelligence", _body({"message": message, **fields}), slow=True)
|
|
291
|
+
|
|
292
|
+
async def intelligence_stream(self, message: str, **fields: Any) -> AsyncIterator[Dict[str, Any]]:
|
|
293
|
+
body = _body({"message": message, **fields})
|
|
294
|
+
for attempt in range(self.max_retries + 1):
|
|
295
|
+
try:
|
|
296
|
+
async with self._http.stream(
|
|
297
|
+
"POST",
|
|
298
|
+
f"{self.base_url}/intelligence/stream",
|
|
299
|
+
json=body,
|
|
300
|
+
headers={**self._headers, "Accept": "text/event-stream"},
|
|
301
|
+
timeout=self._t(True),
|
|
302
|
+
) as res:
|
|
303
|
+
if res.status_code >= 400:
|
|
304
|
+
await res.aread()
|
|
305
|
+
err = _error(res)
|
|
306
|
+
if attempt < self.max_retries and _retryable(err):
|
|
307
|
+
await asyncio.sleep(err.retry_after if err.retry_after is not None else _backoff(attempt))
|
|
308
|
+
continue
|
|
309
|
+
raise err
|
|
310
|
+
buffer: List[str] = []
|
|
311
|
+
async for line in res.aiter_lines():
|
|
312
|
+
buffer.append(line)
|
|
313
|
+
if line == "":
|
|
314
|
+
for ev in _sse(iter(buffer)):
|
|
315
|
+
yield ev
|
|
316
|
+
buffer = []
|
|
317
|
+
for ev in _sse(iter(buffer)):
|
|
318
|
+
yield ev
|
|
319
|
+
return
|
|
320
|
+
except httpx.TransportError as exc:
|
|
321
|
+
if attempt < self.max_retries:
|
|
322
|
+
await asyncio.sleep(_backoff(attempt))
|
|
323
|
+
continue
|
|
324
|
+
raise SyncSoConnectionError(f"Could not reach the SyncSo API: {exc}") from exc
|
|
325
|
+
|
|
326
|
+
async def experience(self, id: str, *, images: Optional[int] = None, include_ai: Optional[bool] = None) -> Dict[str, Any]:
|
|
327
|
+
return await self._request("GET", f"/experiences/{id}", params=self._lookup_params(images, include_ai))
|
|
328
|
+
|
|
329
|
+
async def experiences(self, ids: Sequence[str], *, images: Optional[int] = None, include_ai: Optional[bool] = None) -> Dict[str, Any]:
|
|
330
|
+
params = {"ids": ",".join(ids), **self._lookup_params(images, include_ai)}
|
|
331
|
+
return await self._request("GET", "/experiences", params=params)
|
|
332
|
+
|
|
333
|
+
async def meta(self) -> Dict[str, Any]:
|
|
334
|
+
return await self._request("GET", "/meta")
|
|
335
|
+
|
|
336
|
+
async def catalog(self) -> Dict[str, Any]:
|
|
337
|
+
return await self._request("GET", "/catalog")
|
|
338
|
+
|
|
339
|
+
async def usage(self) -> Dict[str, Any]:
|
|
340
|
+
return await self._request("GET", "/usage")
|
|
341
|
+
|
|
342
|
+
async def _request(self, method: str, path: str, body: Any = None, *, params: Any = None, slow: bool = False) -> Dict[str, Any]:
|
|
343
|
+
for attempt in range(self.max_retries + 1):
|
|
344
|
+
try:
|
|
345
|
+
res = await self._http.request(
|
|
346
|
+
method, f"{self.base_url}{path}", json=body, params=params,
|
|
347
|
+
headers=self._headers, timeout=self._t(slow),
|
|
348
|
+
)
|
|
349
|
+
except httpx.TransportError as exc:
|
|
350
|
+
if attempt < self.max_retries:
|
|
351
|
+
await asyncio.sleep(_backoff(attempt))
|
|
352
|
+
continue
|
|
353
|
+
raise SyncSoConnectionError(f"Could not reach the SyncSo API: {exc}") from exc
|
|
354
|
+
if res.is_success:
|
|
355
|
+
try:
|
|
356
|
+
return res.json()
|
|
357
|
+
except ValueError as exc:
|
|
358
|
+
raise SyncSoConnectionError(f"The API answered {res.status_code} with a body that is not JSON.") from exc
|
|
359
|
+
err = _error(res)
|
|
360
|
+
if attempt < self.max_retries and _retryable(err):
|
|
361
|
+
await asyncio.sleep(err.retry_after if err.retry_after is not None else _backoff(attempt))
|
|
362
|
+
continue
|
|
363
|
+
raise err
|
|
364
|
+
raise AssertionError("unreachable")
|
syncso/_errors.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SyncSoError(Exception):
|
|
7
|
+
"""Every non-2xx answer, with the fields from the API's error envelope.
|
|
8
|
+
|
|
9
|
+
`code` is the API's error code ("rate_limited", "forbidden_tier",
|
|
10
|
+
"invalid_request" ...). Quote `request_id` to support about a call.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, status: int, code: str, message: str, request_id: Optional[str], retry_after: Optional[float]) -> None:
|
|
14
|
+
super().__init__(message)
|
|
15
|
+
self.status = status
|
|
16
|
+
self.code = code
|
|
17
|
+
self.message = message
|
|
18
|
+
self.request_id = request_id
|
|
19
|
+
self.retry_after = retry_after
|
|
20
|
+
|
|
21
|
+
def __str__(self) -> str:
|
|
22
|
+
rid = f" ({self.request_id})" if self.request_id else ""
|
|
23
|
+
return f"{self.status} {self.code}: {self.message}{rid}"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SyncSoConnectionError(Exception):
|
|
27
|
+
"""The request never got an answer: network down, DNS, or the timeout."""
|
syncso/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
syncso/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: syncso
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python client for the SyncSo API: live events and things to do, searched and recommended.
|
|
5
|
+
Project-URL: Homepage, https://syncso.com/partner-api
|
|
6
|
+
Project-URL: Documentation, https://syncso.com/partner-api
|
|
7
|
+
Project-URL: Source, https://github.com/SyncSo-Inc/syncso-sdk
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,api,events,local,sdk,search,syncso,things to do
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Requires-Dist: httpx<1,>=0.25
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# SyncSo Python SDK
|
|
19
|
+
|
|
20
|
+
Live events and things to do — searched, curated, and recommended — from the
|
|
21
|
+
[SyncSo API](https://syncso.com/partner-api).
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install syncso
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
export SYNCSO_API_KEY=rtdb_live_... # create one at https://syncso.com/console
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from syncso import SyncSo
|
|
33
|
+
|
|
34
|
+
syncso = SyncSo()
|
|
35
|
+
|
|
36
|
+
r = syncso.search(
|
|
37
|
+
query="live jazz",
|
|
38
|
+
location={"city": "New York"},
|
|
39
|
+
time_windows=[{"start": "2026-11-25T19:00", "end": "2026-11-25T23:59"}],
|
|
40
|
+
)
|
|
41
|
+
for e in r["experiences"]:
|
|
42
|
+
print(e["title"], e["time"]["next_start"], e["booking"]["primary_link"])
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Python 3.9+. One dependency, `httpx`.
|
|
46
|
+
|
|
47
|
+
## The three endpoints
|
|
48
|
+
|
|
49
|
+
**Search** — a query, a place, a time; ranked. 1 credit per 50 results.
|
|
50
|
+
Leave `query` out to browse by place and time alone.
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
syncso.search(
|
|
54
|
+
query="stand-up comedy",
|
|
55
|
+
location={"point": {"lat": 40.7233, "lng": -74.003, "radius_km": 5}},
|
|
56
|
+
requirements=["seating:seated", "price_max:40"],
|
|
57
|
+
)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
**Featured** — our curated picks for a place and time, no query. Starter plan
|
|
61
|
+
and above; 1 credit per 20 results.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
syncso.featured(location={"city": "New York"}, sort="time", limit=20)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
**Local Life Intelligence** — what someone wants, in their own words,
|
|
68
|
+
answered ranked with a sentence on why each result fits.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
answer = syncso.intelligence(
|
|
72
|
+
"Six friends, a birthday this weekend. Two are vegan, one uses a "
|
|
73
|
+
"wheelchair. Somewhere we can sit and talk. Under $60 a head.",
|
|
74
|
+
place="Lower East Side",
|
|
75
|
+
)
|
|
76
|
+
print(answer["understood"]) # show this first
|
|
77
|
+
for row in answer["results"]: # in this order
|
|
78
|
+
print(row["title"], "—", row["reason"])
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Put everything you know in the message — an allergy, a wheelchair, a dislike.
|
|
82
|
+
Send `reasons=False` when you will not show the sentences: same results,
|
|
83
|
+
sooner, fewer credits.
|
|
84
|
+
|
|
85
|
+
Stream it to show each result as it is decided:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
for ev in syncso.intelligence_stream("Comedy tonight in the East Village"):
|
|
89
|
+
if ev["event"] == "understood":
|
|
90
|
+
print(ev["data"]["text"])
|
|
91
|
+
elif ev["event"] == "result":
|
|
92
|
+
print(ev["data"]["item"]["title"])
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Also
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
syncso.experience(id) # one experience, every field (free)
|
|
99
|
+
syncso.experiences([id1, id2]) # up to 20 (free)
|
|
100
|
+
syncso.meta() # cities, and the requirement tags Search takes
|
|
101
|
+
syncso.catalog() # how many experiences each city holds
|
|
102
|
+
syncso.usage() # this month's requests and credits
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Every result's cost is in `meta.credits_charged`. Page with the previous
|
|
106
|
+
answer's `meta.next_cursor` (`next_cursor` on Intelligence) and everything
|
|
107
|
+
else unchanged.
|
|
108
|
+
|
|
109
|
+
## Async
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from syncso import AsyncSyncSo
|
|
113
|
+
|
|
114
|
+
async with AsyncSyncSo() as syncso:
|
|
115
|
+
r = await syncso.search(query="pottery class", location={"city": "New York"})
|
|
116
|
+
async for ev in syncso.intelligence_stream("Something to do after 10pm"):
|
|
117
|
+
...
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Errors and retries
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from syncso import SyncSoError
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
syncso.featured(location={"city": "New York"})
|
|
127
|
+
except SyncSoError as e:
|
|
128
|
+
e.status # 403
|
|
129
|
+
e.code # "forbidden_tier"
|
|
130
|
+
e.request_id # quote this to support
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Rate limits (`429 rate_limited`), a busy catalogue (`503`), server errors and
|
|
134
|
+
dropped connections are retried twice, waiting as long as the API asks.
|
|
135
|
+
Quota, credit and validation errors are not. Set `max_retries=` and
|
|
136
|
+
`timeout=` on the client to change that. A request that never gets an
|
|
137
|
+
answer raises `SyncSoConnectionError`.
|
|
138
|
+
|
|
139
|
+
## Three things that trip people up
|
|
140
|
+
|
|
141
|
+
- **Times are local to the city, with no offset.** `"2026-11-25T19:00"`, never
|
|
142
|
+
`datetime.utcnow().isoformat()` — a `Z` is rejected. Response times are
|
|
143
|
+
wall-clock at the venue too.
|
|
144
|
+
- **A blank `query` is a `422`.** To browse, leave `query` out.
|
|
145
|
+
- **Unknown fields are rejected**, so a misspelt keyword fails instead of
|
|
146
|
+
silently widening the search.
|
|
147
|
+
|
|
148
|
+
[Every field, in the API docs →](https://syncso.com/partner-api)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
syncso/__init__.py,sha256=urmc7AUrQ5t1_uFP8rjBWwuaUegt1WbKrtVokECfVoU,303
|
|
2
|
+
syncso/_client.py,sha256=XsL_pQl2pWjeH5uiau-ESJbe687zxb9P7lPeLrzSYKE,15389
|
|
3
|
+
syncso/_errors.py,sha256=2gDal-Afc3rxU4bPdL6dPejXBadO3MD8NT5EDK_46JE,927
|
|
4
|
+
syncso/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
5
|
+
syncso/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
syncso-0.1.0.dist-info/METADATA,sha256=wwpfZNKBezTwEeUy-ItdNT_Y8IM3maNw94dzHFnpSkQ,4651
|
|
7
|
+
syncso-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
syncso-0.1.0.dist-info/licenses/LICENSE,sha256=mKLnl5_EBs0-4u1yvub7xAYcfb_WDqnCkTj720qd-aY,1069
|
|
9
|
+
syncso-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SyncSo, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|