syncso 0.1.0__tar.gz

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.
@@ -0,0 +1,8 @@
1
+ node_modules/
2
+ dist/
3
+ .venv/
4
+ __pycache__/
5
+ *.egg-info/
6
+ .pytest_cache/
7
+ .env
8
+ pending-patches/
syncso-0.1.0/LICENSE ADDED
@@ -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.
syncso-0.1.0/PKG-INFO ADDED
@@ -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)
syncso-0.1.0/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # SyncSo Python SDK
2
+
3
+ Live events and things to do — searched, curated, and recommended — from the
4
+ [SyncSo API](https://syncso.com/partner-api).
5
+
6
+ ```bash
7
+ pip install syncso
8
+ ```
9
+
10
+ ```bash
11
+ export SYNCSO_API_KEY=rtdb_live_... # create one at https://syncso.com/console
12
+ ```
13
+
14
+ ```python
15
+ from syncso import SyncSo
16
+
17
+ syncso = SyncSo()
18
+
19
+ r = syncso.search(
20
+ query="live jazz",
21
+ location={"city": "New York"},
22
+ time_windows=[{"start": "2026-11-25T19:00", "end": "2026-11-25T23:59"}],
23
+ )
24
+ for e in r["experiences"]:
25
+ print(e["title"], e["time"]["next_start"], e["booking"]["primary_link"])
26
+ ```
27
+
28
+ Python 3.9+. One dependency, `httpx`.
29
+
30
+ ## The three endpoints
31
+
32
+ **Search** — a query, a place, a time; ranked. 1 credit per 50 results.
33
+ Leave `query` out to browse by place and time alone.
34
+
35
+ ```python
36
+ syncso.search(
37
+ query="stand-up comedy",
38
+ location={"point": {"lat": 40.7233, "lng": -74.003, "radius_km": 5}},
39
+ requirements=["seating:seated", "price_max:40"],
40
+ )
41
+ ```
42
+
43
+ **Featured** — our curated picks for a place and time, no query. Starter plan
44
+ and above; 1 credit per 20 results.
45
+
46
+ ```python
47
+ syncso.featured(location={"city": "New York"}, sort="time", limit=20)
48
+ ```
49
+
50
+ **Local Life Intelligence** — what someone wants, in their own words,
51
+ answered ranked with a sentence on why each result fits.
52
+
53
+ ```python
54
+ answer = syncso.intelligence(
55
+ "Six friends, a birthday this weekend. Two are vegan, one uses a "
56
+ "wheelchair. Somewhere we can sit and talk. Under $60 a head.",
57
+ place="Lower East Side",
58
+ )
59
+ print(answer["understood"]) # show this first
60
+ for row in answer["results"]: # in this order
61
+ print(row["title"], "—", row["reason"])
62
+ ```
63
+
64
+ Put everything you know in the message — an allergy, a wheelchair, a dislike.
65
+ Send `reasons=False` when you will not show the sentences: same results,
66
+ sooner, fewer credits.
67
+
68
+ Stream it to show each result as it is decided:
69
+
70
+ ```python
71
+ for ev in syncso.intelligence_stream("Comedy tonight in the East Village"):
72
+ if ev["event"] == "understood":
73
+ print(ev["data"]["text"])
74
+ elif ev["event"] == "result":
75
+ print(ev["data"]["item"]["title"])
76
+ ```
77
+
78
+ ## Also
79
+
80
+ ```python
81
+ syncso.experience(id) # one experience, every field (free)
82
+ syncso.experiences([id1, id2]) # up to 20 (free)
83
+ syncso.meta() # cities, and the requirement tags Search takes
84
+ syncso.catalog() # how many experiences each city holds
85
+ syncso.usage() # this month's requests and credits
86
+ ```
87
+
88
+ Every result's cost is in `meta.credits_charged`. Page with the previous
89
+ answer's `meta.next_cursor` (`next_cursor` on Intelligence) and everything
90
+ else unchanged.
91
+
92
+ ## Async
93
+
94
+ ```python
95
+ from syncso import AsyncSyncSo
96
+
97
+ async with AsyncSyncSo() as syncso:
98
+ r = await syncso.search(query="pottery class", location={"city": "New York"})
99
+ async for ev in syncso.intelligence_stream("Something to do after 10pm"):
100
+ ...
101
+ ```
102
+
103
+ ## Errors and retries
104
+
105
+ ```python
106
+ from syncso import SyncSoError
107
+
108
+ try:
109
+ syncso.featured(location={"city": "New York"})
110
+ except SyncSoError as e:
111
+ e.status # 403
112
+ e.code # "forbidden_tier"
113
+ e.request_id # quote this to support
114
+ ```
115
+
116
+ Rate limits (`429 rate_limited`), a busy catalogue (`503`), server errors and
117
+ dropped connections are retried twice, waiting as long as the API asks.
118
+ Quota, credit and validation errors are not. Set `max_retries=` and
119
+ `timeout=` on the client to change that. A request that never gets an
120
+ answer raises `SyncSoConnectionError`.
121
+
122
+ ## Three things that trip people up
123
+
124
+ - **Times are local to the city, with no offset.** `"2026-11-25T19:00"`, never
125
+ `datetime.utcnow().isoformat()` — a `Z` is rejected. Response times are
126
+ wall-clock at the venue too.
127
+ - **A blank `query` is a `422`.** To browse, leave `query` out.
128
+ - **Unknown fields are rejected**, so a misspelt keyword fails instead of
129
+ silently widening the search.
130
+
131
+ [Every field, in the API docs →](https://syncso.com/partner-api)
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.21"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "syncso"
7
+ version = "0.1.0"
8
+ description = "Official Python client for the SyncSo API: live events and things to do, searched and recommended."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ dependencies = ["httpx>=0.25,<1"]
13
+ keywords = ["syncso", "events", "things to do", "local", "search", "api", "sdk", "agents"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Typing :: Typed",
17
+ "Intended Audience :: Developers",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://syncso.com/partner-api"
22
+ Documentation = "https://syncso.com/partner-api"
23
+ Source = "https://github.com/SyncSo-Inc/syncso-sdk"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/syncso"]
@@ -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__"]
@@ -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")
@@ -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."""
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,100 @@
1
+ import json
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ from syncso import AsyncSyncSo, SyncSo, SyncSoConnectionError, SyncSoError
7
+
8
+
9
+ def client(handler, **kw):
10
+ return SyncSo(api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(handler)), **kw)
11
+
12
+
13
+ def test_sends_key_body_and_drops_none():
14
+ seen = {}
15
+
16
+ def handler(req):
17
+ seen["url"] = str(req.url)
18
+ seen["auth"] = req.headers["authorization"]
19
+ seen["body"] = json.loads(req.content)
20
+ return httpx.Response(200, json={"experiences": [], "meta": {"credits_charged": 1}})
21
+
22
+ client(handler).search(location={"city": "New York"}, limit=5)
23
+ assert seen["url"] == "https://api.syncso.com/v1/search"
24
+ assert seen["auth"] == "Bearer k"
25
+ assert seen["body"] == {"location": {"city": "New York"}, "limit": 5} # query=None left out
26
+
27
+
28
+ def test_retries_after_rate_limit():
29
+ calls = []
30
+
31
+ def handler(req):
32
+ calls.append(1)
33
+ if len(calls) == 1:
34
+ return httpx.Response(429, json={"error": {"code": "rate_limited", "message": "slow"}, "retry_after_s": 0.01})
35
+ return httpx.Response(200, json={"ok": True})
36
+
37
+ assert client(handler).usage() == {"ok": True}
38
+ assert len(calls) == 2
39
+
40
+
41
+ @pytest.mark.parametrize("status,code", [(429, "quota_exceeded"), (422, "invalid_request"), (402, "insufficient_credits")])
42
+ def test_never_retries_final_errors(status, code):
43
+ calls = []
44
+
45
+ def handler(req):
46
+ calls.append(1)
47
+ return httpx.Response(status, json={"error": {"code": code, "message": "no", "request_id": "req_1"}})
48
+
49
+ with pytest.raises(SyncSoError) as e:
50
+ client(handler).usage()
51
+ assert (e.value.status, e.value.code, e.value.request_id) == (status, code, "req_1")
52
+ assert len(calls) == 1
53
+
54
+
55
+ def test_connection_error_after_retries():
56
+ calls = []
57
+
58
+ def handler(req):
59
+ calls.append(1)
60
+ raise httpx.ConnectError("down")
61
+
62
+ with pytest.raises(SyncSoConnectionError):
63
+ client(handler, max_retries=1).usage()
64
+ assert len(calls) == 2
65
+
66
+
67
+ STREAM = (
68
+ 'event: meta\ndata: {"request_id":"r"}\n\n'
69
+ 'event: understood\ndata: {"text":"about 900 things on"}\n\n'
70
+ 'event: result\ndata: {"rank":1,"item":{"id":"a","title":"A"}}\n\n'
71
+ 'event: done\ndata: {"request_id":"r","meta":{"credits_charged":2}}\n\n'
72
+ )
73
+
74
+
75
+ def test_stream_events():
76
+ events = list(client(lambda req: httpx.Response(200, text=STREAM)).intelligence_stream("x"))
77
+ assert [e["event"] for e in events] == ["meta", "understood", "result", "done"]
78
+ assert events[2]["data"]["item"]["title"] == "A"
79
+
80
+
81
+ def test_stream_error_event_raises():
82
+ body = 'event: meta\ndata: {"request_id":"r"}\n\nevent: error\ndata: {"error":{"code":"internal","message":"boom"}}\n\n'
83
+ with pytest.raises(SyncSoError, match="boom"):
84
+ list(client(lambda req: httpx.Response(200, text=body)).intelligence_stream("x"))
85
+
86
+
87
+ def test_async_stream():
88
+ import asyncio
89
+
90
+ async def run():
91
+ s = AsyncSyncSo(api_key="k", http_client=httpx.AsyncClient(transport=httpx.MockTransport(lambda r: httpx.Response(200, text=STREAM))))
92
+ return [e["event"] async for e in s.intelligence_stream("x")]
93
+
94
+ assert asyncio.run(run()) == ["meta", "understood", "result", "done"]
95
+
96
+
97
+ def test_no_key(monkeypatch):
98
+ monkeypatch.delenv("SYNCSO_API_KEY", raising=False)
99
+ with pytest.raises(ValueError, match="SYNCSO_API_KEY"):
100
+ SyncSo()