ami-router-client 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.
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ami-router-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client for the AMI Router's HTTP API
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/tbdsux/ami-sdk
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Dynamic: license-file
|
|
11
|
+
|
|
12
|
+
# ami-router-client
|
|
13
|
+
|
|
14
|
+
Python client for the [AMI Router](https://github.com/tbdsux/ami-sdk/tree/main/router#readme). The router puts one HTTP API in front of many web search, scrape and research providers: it tries them in the order you set, and falls back to the next one when a provider fails.
|
|
15
|
+
|
|
16
|
+
Standard library only. Python 3.9 or later.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install ami-router-client
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Or straight from GitHub:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install "git+https://github.com/tbdsux/ami-sdk#subdirectory=router-clients/python"
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Use
|
|
31
|
+
|
|
32
|
+
Create an API key in the router's dashboard, then:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from ami_router_client import Client, Pending, RouterError
|
|
36
|
+
|
|
37
|
+
router = Client("ami_...", base_url="http://127.0.0.1:8090")
|
|
38
|
+
|
|
39
|
+
res = router.search("go generics", limit=5)
|
|
40
|
+
for r in res.get("results", []):
|
|
41
|
+
print(r["title"], r["url"])
|
|
42
|
+
|
|
43
|
+
# Skip the routing order, and include the provider's original response.
|
|
44
|
+
res = router.search("go generics", provider="exa", raw=True)
|
|
45
|
+
|
|
46
|
+
for chunk in router.answer_stream("what is htmx?"):
|
|
47
|
+
print(chunk.get("text", ""), end="")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Replies are the router's JSON as dicts; the [router's README](https://github.com/tbdsux/ami-sdk/tree/main/router#responses) lists the fields. The router leaves out empty fields, so read them with `.get`.
|
|
51
|
+
|
|
52
|
+
| Method | Endpoint | Reply |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| `search(query, limit=0)` | `POST /v1/search` | `results` |
|
|
55
|
+
| `scrape(url)` | `POST /v1/scrape` | `page` |
|
|
56
|
+
| `crawl(url="", limit=0, *, resume_id="")` | `POST /v1/crawl` | `pages`, `id` |
|
|
57
|
+
| `answer(query)` | `POST /v1/answer` | `content`, `citations` |
|
|
58
|
+
| `research(query="", *, resume_id="")` | `POST /v1/research` | `content`, `citations`, `id` |
|
|
59
|
+
| `answer_stream(query)` | `POST /v1/answer`, streamed | yields chunks: `text`, `citations` |
|
|
60
|
+
| `research_stream(query="", *, resume_id="")` | `POST /v1/research`, streamed | yields chunks: `text`, `citations`, `id` |
|
|
61
|
+
| `providers()` | `GET /v1/providers` | the routing order for each endpoint |
|
|
62
|
+
|
|
63
|
+
Every method but `providers` also takes the keyword arguments `provider=` and `raw=`. Every reply has `provider`, the one that served the call, and `attempts`, the ones that failed first.
|
|
64
|
+
|
|
65
|
+
`Client(..., timeout=30)` limits each socket read, in seconds. By default it waits as long as the router does, which for crawl and research is the router's long timeout (600 s unless changed).
|
|
66
|
+
|
|
67
|
+
## Errors
|
|
68
|
+
|
|
69
|
+
- **`RouterError`** means the router couldn't serve the request. `e.status` is the HTTP status, and `e.body` is the router's reply, with `error` and the failed `attempts`.
|
|
70
|
+
- **`Pending`**, a subclass, means a crawl or research job outlasted the router's long timeout. The job keeps running at the provider, so collect it later instead of paying for a new one:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
try:
|
|
74
|
+
report = router.research("state of WebAssembly")
|
|
75
|
+
except Pending as e:
|
|
76
|
+
report = router.research(resume_id=e.id, provider=e.provider)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
- **A stream that fails partway,** or is cut off before the router finishes it, raises `RouterError` with status 200, after the chunks that arrived.
|
|
80
|
+
|
|
81
|
+
## Develop
|
|
82
|
+
|
|
83
|
+
The project is managed with [uv](https://docs.astral.sh/uv/). The tests run against a fake router:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
uv run python -m unittest -v
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Change the version with `uv version`, which updates `uv.lock` too:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
uv version 0.2.0
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Build the wheel and sdist into `dist/`:
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
uv build
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## License
|
|
102
|
+
|
|
103
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
ami_router_client.py,sha256=mIxL3isrPTBQkmjEksT5uAaXESyIkcloY_sREfKJTKo,6570
|
|
2
|
+
ami_router_client-0.1.0.dist-info/licenses/LICENSE,sha256=-33lBm4GL2QIBUVifGe6ChIicHxFyjYU2EfBWPPsEMA,1070
|
|
3
|
+
ami_router_client-0.1.0.dist-info/METADATA,sha256=xrrLEB3hifXdUdq36ldAV2oPChjZRgHCr2XlsG85X3U,3668
|
|
4
|
+
ami_router_client-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
ami_router_client-0.1.0.dist-info/top_level.txt,sha256=XQH1czw3M_q8oIPetCd7f-sdi6FacnNel_7AOJy12hM,18
|
|
6
|
+
ami_router_client-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joshue Abance
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ami_router_client
|
ami_router_client.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Client for the AMI Router's HTTP API. Standard library only.
|
|
2
|
+
|
|
3
|
+
from ami_router_client import Client
|
|
4
|
+
|
|
5
|
+
router = Client("ami_...", base_url="http://127.0.0.1:8090")
|
|
6
|
+
res = router.search("go generics", limit=5)
|
|
7
|
+
for r in res.get("results", []):
|
|
8
|
+
print(r["title"], r["url"])
|
|
9
|
+
|
|
10
|
+
Every method returns the router's JSON reply as a dict: see the router's README
|
|
11
|
+
for its fields. Empty fields are left out, so read them with ``.get``. ``provider`` and ``raw`` work on every call except ``providers``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.request
|
|
17
|
+
|
|
18
|
+
__all__ = ["Client", "RouterError", "Pending"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RouterError(Exception):
|
|
22
|
+
"""A request the router could not serve.
|
|
23
|
+
|
|
24
|
+
``status`` is the HTTP status (200 for a stream that failed partway), and
|
|
25
|
+
``body`` the router's reply, with ``error`` and the failed ``attempts``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, status, body):
|
|
29
|
+
super().__init__(f"ami router: {body.get('error') or body}")
|
|
30
|
+
self.status = status
|
|
31
|
+
self.body = body
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Pending(RouterError):
|
|
35
|
+
"""A crawl or research job that outlasted the router's long timeout.
|
|
36
|
+
|
|
37
|
+
The job keeps running at the provider. Collect it later, without paying
|
|
38
|
+
for a new one: ``router.research(resume_id=e.id, provider=e.provider)``.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, body):
|
|
42
|
+
super().__init__(202, {"error": f"job {body.get('id')} still running at {body.get('provider')}", **body})
|
|
43
|
+
self.id = body.get("id")
|
|
44
|
+
self.provider = body.get("provider")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Client:
|
|
48
|
+
"""Calls one router with one API key from its dashboard.
|
|
49
|
+
|
|
50
|
+
``timeout`` is in seconds and applies to each socket read; None waits as
|
|
51
|
+
long as the router does (up to its long timeout for crawl and research).
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(self, api_key, base_url="http://127.0.0.1:8090", timeout=None):
|
|
55
|
+
self.api_key = api_key
|
|
56
|
+
self.base_url = base_url.rstrip("/")
|
|
57
|
+
self.timeout = timeout
|
|
58
|
+
|
|
59
|
+
def search(self, query, limit=0, *, provider="", raw=False):
|
|
60
|
+
"""POST /v1/search: ``results``."""
|
|
61
|
+
return self._post("search", query=query, limit=limit, provider=provider, raw=raw)
|
|
62
|
+
|
|
63
|
+
def scrape(self, url, *, provider="", raw=False):
|
|
64
|
+
"""POST /v1/scrape: ``page``."""
|
|
65
|
+
return self._post("scrape", url=url, provider=provider, raw=raw)
|
|
66
|
+
|
|
67
|
+
def crawl(self, url="", limit=0, *, resume_id="", provider="", raw=False):
|
|
68
|
+
"""POST /v1/crawl: ``pages`` and ``id``. Raises Pending for a long job."""
|
|
69
|
+
return self._post("crawl", url=url, limit=limit, resume_id=resume_id, provider=provider, raw=raw)
|
|
70
|
+
|
|
71
|
+
def answer(self, query, *, provider="", raw=False):
|
|
72
|
+
"""POST /v1/answer: ``content`` and ``citations``."""
|
|
73
|
+
return self._post("answer", query=query, provider=provider, raw=raw)
|
|
74
|
+
|
|
75
|
+
def research(self, query="", *, resume_id="", provider="", raw=False):
|
|
76
|
+
"""POST /v1/research: ``content``, ``citations`` and ``id``. Raises Pending for a long job."""
|
|
77
|
+
return self._post("research", query=query, resume_id=resume_id, provider=provider, raw=raw)
|
|
78
|
+
|
|
79
|
+
def answer_stream(self, query, *, provider="", raw=False):
|
|
80
|
+
"""Yields the chunks of a streamed answer: ``text``, ``citations``, ``provider``."""
|
|
81
|
+
return self._stream("answer", query=query, provider=provider, raw=raw)
|
|
82
|
+
|
|
83
|
+
def research_stream(self, query="", *, resume_id="", provider="", raw=False):
|
|
84
|
+
"""Yields the chunks of a streamed report: ``text``, ``citations``, ``id``, ``provider``."""
|
|
85
|
+
return self._stream("research", query=query, resume_id=resume_id, provider=provider, raw=raw)
|
|
86
|
+
|
|
87
|
+
def providers(self):
|
|
88
|
+
"""GET /v1/providers: the routing order for each endpoint."""
|
|
89
|
+
with self._open("GET", "/v1/providers") as resp:
|
|
90
|
+
return _check(_parse(resp.read()), resp.status)
|
|
91
|
+
|
|
92
|
+
def _open(self, method, path, body=None):
|
|
93
|
+
data = None if body is None else json.dumps(body).encode()
|
|
94
|
+
req = urllib.request.Request(self.base_url + path, data=data, method=method)
|
|
95
|
+
req.add_header("Authorization", f"Bearer {self.api_key}")
|
|
96
|
+
if data is not None:
|
|
97
|
+
req.add_header("Content-Type", "application/json")
|
|
98
|
+
try:
|
|
99
|
+
return urllib.request.urlopen(req, timeout=self.timeout)
|
|
100
|
+
except urllib.error.HTTPError as e:
|
|
101
|
+
with e: # closes the connection
|
|
102
|
+
raise RouterError(e.code, _parse(e.read())) from None
|
|
103
|
+
|
|
104
|
+
def _post(self, endpoint, **body):
|
|
105
|
+
with self._open("POST", f"/v1/{endpoint}", body) as resp:
|
|
106
|
+
return _check(_parse(resp.read()), resp.status)
|
|
107
|
+
|
|
108
|
+
def _stream(self, endpoint, **body):
|
|
109
|
+
with self._open("POST", f"/v1/{endpoint}", {**body, "stream": True}) as resp:
|
|
110
|
+
# A job still pending before the first chunk comes back as plain JSON.
|
|
111
|
+
if resp.headers.get_content_type() != "text/event-stream":
|
|
112
|
+
_check(_parse(resp.read()), resp.status)
|
|
113
|
+
return
|
|
114
|
+
|
|
115
|
+
for event, data in _events(resp):
|
|
116
|
+
if event == "done":
|
|
117
|
+
_check(json.loads(data), 200)
|
|
118
|
+
return
|
|
119
|
+
yield json.loads(data)
|
|
120
|
+
|
|
121
|
+
# The router ends every stream it finishes with the done event.
|
|
122
|
+
raise RouterError(resp.status, {"error": "stream ended before the done event"})
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _check(body, status=200):
|
|
126
|
+
"""Raises the failure a 2xx reply or stream event reports, else returns it."""
|
|
127
|
+
if body.get("pending"):
|
|
128
|
+
raise Pending(body)
|
|
129
|
+
if body.get("error"):
|
|
130
|
+
raise RouterError(status, body)
|
|
131
|
+
return body
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _parse(raw):
|
|
135
|
+
"""A reply as a dict, even when a proxy in front sent HTML or JSON that isn't an object."""
|
|
136
|
+
try:
|
|
137
|
+
body = json.loads(raw)
|
|
138
|
+
except ValueError:
|
|
139
|
+
body = None
|
|
140
|
+
if isinstance(body, dict):
|
|
141
|
+
return body
|
|
142
|
+
# An empty body is an error too: {"error": ""} would pass _check as a reply.
|
|
143
|
+
return {"error": raw.decode(errors="replace") or "empty reply"}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _events(resp):
|
|
147
|
+
"""Yields (event, data) for each server-sent event, data lines joined by newlines per the SSE spec."""
|
|
148
|
+
event, data = "", []
|
|
149
|
+
for line in resp:
|
|
150
|
+
line = line.decode().rstrip("\r\n")
|
|
151
|
+
if line.startswith("event:"):
|
|
152
|
+
event = line[6:].strip()
|
|
153
|
+
elif line.startswith("data:"):
|
|
154
|
+
data.append(line[5:].removeprefix(" "))
|
|
155
|
+
elif not line:
|
|
156
|
+
if data:
|
|
157
|
+
yield event, "\n".join(data)
|
|
158
|
+
event, data = "", []
|
|
159
|
+
# Like the Go SDK's reader, a last event without its blank line still counts.
|
|
160
|
+
if data:
|
|
161
|
+
yield event, "\n".join(data)
|