usagemax 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.
- usagemax-0.1.0/.gitignore +3 -0
- usagemax-0.1.0/LICENSE +21 -0
- usagemax-0.1.0/PKG-INFO +101 -0
- usagemax-0.1.0/README.md +82 -0
- usagemax-0.1.0/pyproject.toml +32 -0
- usagemax-0.1.0/src/usagemax/__init__.py +5 -0
- usagemax-0.1.0/src/usagemax/client.py +226 -0
- usagemax-0.1.0/src/usagemax/py.typed +0 -0
- usagemax-0.1.0/tests/test_client.py +144 -0
usagemax-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 UsageMax
|
|
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.
|
usagemax-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: usagemax
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for UsageMax telemetry, gateway receipts, and usage reports
|
|
5
|
+
Project-URL: Homepage, https://usagemax.com
|
|
6
|
+
Project-URL: Documentation, https://docs.usagemax.com
|
|
7
|
+
Project-URL: API Reference, https://usagemax.com/openapi.json
|
|
8
|
+
Project-URL: Source, https://github.com/SYMBaiEX/usagemax/tree/main/packages/python
|
|
9
|
+
Project-URL: Issues, https://github.com/SYMBaiEX/usagemax/issues
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# UsageMax for Python
|
|
21
|
+
|
|
22
|
+
Use UsageMax from a Python service, script, or notebook. The client supports Python 3.10 and later and has zero runtime dependencies.
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install usagemax
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Read public usage
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from usagemax import UsageMax
|
|
32
|
+
|
|
33
|
+
usage = UsageMax()
|
|
34
|
+
print(usage.health()["ok"])
|
|
35
|
+
print(usage.stats()["stats"])
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Use `profile(handle)` or `daily_usage(handle, days=30, group_by="model")` for opt-in public profiles. For a large result, use `daily_detail()` with an inclusive UTC date range and pass `continueCursor` back as `cursor` until `isDone` is true. Sum additive rows across all pages for full-range totals.
|
|
39
|
+
|
|
40
|
+
## Read private gateway reports
|
|
41
|
+
|
|
42
|
+
Create a report key in [your gateway workspace](https://usagemax.com/workspace/gateway). Store it in your server's secret manager and pass it to the client.
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import os
|
|
46
|
+
from datetime import datetime, timedelta, timezone
|
|
47
|
+
|
|
48
|
+
from usagemax import GatewayClient
|
|
49
|
+
|
|
50
|
+
gateway = GatewayClient(os.environ["USAGEMAX_GATEWAY_REPORT_TOKEN"])
|
|
51
|
+
today = datetime.now(timezone.utc).date()
|
|
52
|
+
report = gateway.operations(start=today - timedelta(days=6), through=today)
|
|
53
|
+
print(report["overall"]["requests"], report["truncated"])
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Use `receipts()` for a bounded list and `receipt(request_id)` for one receipt. Use a separate ingest key for `write_receipts()`. Check the status of every receipt returned by the batch write and reuse the original request ID, revision, and fields on a retry.
|
|
57
|
+
|
|
58
|
+
## Send content-free telemetry
|
|
59
|
+
|
|
60
|
+
Create a custom collector under [your account](https://usagemax.com/account?setup=telemetry#custom-telemetry). Generate and persist a stable installation UUID when provisioning the collector. Keep using that UUID for all requests from that installation.
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import os
|
|
64
|
+
|
|
65
|
+
from usagemax import CollectorClient
|
|
66
|
+
|
|
67
|
+
collector = CollectorClient(
|
|
68
|
+
os.environ["USAGEMAX_COLLECTOR_TOKEN"],
|
|
69
|
+
device_id=os.environ["USAGEMAX_DEVICE_ID"],
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def record_request(request_id, model, occurred_at, input_tokens, output_tokens):
|
|
73
|
+
return collector.send_events(
|
|
74
|
+
[{
|
|
75
|
+
"eventKey": request_id,
|
|
76
|
+
"model": model,
|
|
77
|
+
"occurredAt": occurred_at,
|
|
78
|
+
"inputTokens": input_tokens,
|
|
79
|
+
"outputTokens": output_tokens,
|
|
80
|
+
}],
|
|
81
|
+
idempotency_key=request_id,
|
|
82
|
+
)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Use the actual event time in ISO 8601 or Unix milliseconds. Reuse the original payload and idempotency key when retrying. Use `send_traces()` for OTLP/HTTP JSON. Filter prompts, responses, and other sensitive attributes at the source before sending an event or trace.
|
|
86
|
+
|
|
87
|
+
## Handle errors
|
|
88
|
+
|
|
89
|
+
`APIError` provides `status_code`, `code` when the API supplies one, and `retry_after` when present. `TransportError` covers network failures and unreadable responses. Requests are synchronous and use a configurable timeout. Handle retries in your application or durable outbox.
|
|
90
|
+
|
|
91
|
+
The [OpenAPI contract](https://usagemax.com/openapi.json) documents request and response fields. For scanning local coding-agent usage, see the [UsageMax CLI](https://docs.usagemax.com/cli).
|
|
92
|
+
|
|
93
|
+
## Maintainer release
|
|
94
|
+
|
|
95
|
+
Bump the version in `pyproject.toml`, merge the tested change into `main`, and dispatch the workflow with that exact version.
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
gh workflow run publish-python.yml --ref main -f version=0.1.0
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
The workflow uses the dedicated `pypi` environment and PyPI Trusted Publishing. It builds and tests the distributions before the publishing job receives OIDC permissions.
|
usagemax-0.1.0/README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# UsageMax for Python
|
|
2
|
+
|
|
3
|
+
Use UsageMax from a Python service, script, or notebook. The client supports Python 3.10 and later and has zero runtime dependencies.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install usagemax
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Read public usage
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from usagemax import UsageMax
|
|
13
|
+
|
|
14
|
+
usage = UsageMax()
|
|
15
|
+
print(usage.health()["ok"])
|
|
16
|
+
print(usage.stats()["stats"])
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Use `profile(handle)` or `daily_usage(handle, days=30, group_by="model")` for opt-in public profiles. For a large result, use `daily_detail()` with an inclusive UTC date range and pass `continueCursor` back as `cursor` until `isDone` is true. Sum additive rows across all pages for full-range totals.
|
|
20
|
+
|
|
21
|
+
## Read private gateway reports
|
|
22
|
+
|
|
23
|
+
Create a report key in [your gateway workspace](https://usagemax.com/workspace/gateway). Store it in your server's secret manager and pass it to the client.
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import os
|
|
27
|
+
from datetime import datetime, timedelta, timezone
|
|
28
|
+
|
|
29
|
+
from usagemax import GatewayClient
|
|
30
|
+
|
|
31
|
+
gateway = GatewayClient(os.environ["USAGEMAX_GATEWAY_REPORT_TOKEN"])
|
|
32
|
+
today = datetime.now(timezone.utc).date()
|
|
33
|
+
report = gateway.operations(start=today - timedelta(days=6), through=today)
|
|
34
|
+
print(report["overall"]["requests"], report["truncated"])
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Use `receipts()` for a bounded list and `receipt(request_id)` for one receipt. Use a separate ingest key for `write_receipts()`. Check the status of every receipt returned by the batch write and reuse the original request ID, revision, and fields on a retry.
|
|
38
|
+
|
|
39
|
+
## Send content-free telemetry
|
|
40
|
+
|
|
41
|
+
Create a custom collector under [your account](https://usagemax.com/account?setup=telemetry#custom-telemetry). Generate and persist a stable installation UUID when provisioning the collector. Keep using that UUID for all requests from that installation.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import os
|
|
45
|
+
|
|
46
|
+
from usagemax import CollectorClient
|
|
47
|
+
|
|
48
|
+
collector = CollectorClient(
|
|
49
|
+
os.environ["USAGEMAX_COLLECTOR_TOKEN"],
|
|
50
|
+
device_id=os.environ["USAGEMAX_DEVICE_ID"],
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def record_request(request_id, model, occurred_at, input_tokens, output_tokens):
|
|
54
|
+
return collector.send_events(
|
|
55
|
+
[{
|
|
56
|
+
"eventKey": request_id,
|
|
57
|
+
"model": model,
|
|
58
|
+
"occurredAt": occurred_at,
|
|
59
|
+
"inputTokens": input_tokens,
|
|
60
|
+
"outputTokens": output_tokens,
|
|
61
|
+
}],
|
|
62
|
+
idempotency_key=request_id,
|
|
63
|
+
)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Use the actual event time in ISO 8601 or Unix milliseconds. Reuse the original payload and idempotency key when retrying. Use `send_traces()` for OTLP/HTTP JSON. Filter prompts, responses, and other sensitive attributes at the source before sending an event or trace.
|
|
67
|
+
|
|
68
|
+
## Handle errors
|
|
69
|
+
|
|
70
|
+
`APIError` provides `status_code`, `code` when the API supplies one, and `retry_after` when present. `TransportError` covers network failures and unreadable responses. Requests are synchronous and use a configurable timeout. Handle retries in your application or durable outbox.
|
|
71
|
+
|
|
72
|
+
The [OpenAPI contract](https://usagemax.com/openapi.json) documents request and response fields. For scanning local coding-agent usage, see the [UsageMax CLI](https://docs.usagemax.com/cli).
|
|
73
|
+
|
|
74
|
+
## Maintainer release
|
|
75
|
+
|
|
76
|
+
Bump the version in `pyproject.toml`, merge the tested change into `main`, and dispatch the workflow with that exact version.
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
gh workflow run publish-python.yml --ref main -f version=0.1.0
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The workflow uses the dedicated `pypi` environment and PyPI Trusted Publishing. It builds and tests the distributions before the publishing job receives OIDC permissions.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27,<2"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "usagemax"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python client for UsageMax telemetry, gateway receipts, and usage reports"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 4 - Beta",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Software Development :: Libraries",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://usagemax.com"
|
|
23
|
+
Documentation = "https://docs.usagemax.com"
|
|
24
|
+
"API Reference" = "https://usagemax.com/openapi.json"
|
|
25
|
+
Source = "https://github.com/SYMBaiEX/usagemax/tree/main/packages/python"
|
|
26
|
+
Issues = "https://github.com/SYMBaiEX/usagemax/issues"
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/usagemax"]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.sdist]
|
|
32
|
+
include = ["/src", "/tests", "/README.md", "/LICENSE", "/pyproject.toml"]
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Synchronous clients for the UsageMax HTTP API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
from datetime import date
|
|
9
|
+
from typing import Any, Literal, Mapping, Sequence
|
|
10
|
+
from urllib.error import HTTPError, URLError
|
|
11
|
+
from urllib.parse import quote, urlencode, urlsplit
|
|
12
|
+
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
13
|
+
from uuid import UUID
|
|
14
|
+
|
|
15
|
+
JsonObject = dict[str, Any]
|
|
16
|
+
GroupBy = Literal["model", "source", "device"]
|
|
17
|
+
DEFAULT_URL = "https://usagemax.com"
|
|
18
|
+
|
|
19
|
+
_PROFILE_HANDLE = re.compile(r"[A-Za-z0-9_-]{1,80}")
|
|
20
|
+
_REQUEST_ID = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9_.:-]{0,119}")
|
|
21
|
+
_HEADER_VALUE = re.compile(r"[!-~]+")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class APIError(Exception):
|
|
25
|
+
"""The API rejected a request. The exception omits the request and response bodies."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, status_code: int, code: str | None, retry_after: str | None) -> None:
|
|
28
|
+
self.status_code = status_code
|
|
29
|
+
self.code = code
|
|
30
|
+
self.retry_after = retry_after
|
|
31
|
+
super().__init__(f"UsageMax returned HTTP {status_code}" + (f" ({code})" if code else ""))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class TransportError(Exception):
|
|
35
|
+
"""The connection failed or UsageMax returned an unreadable response."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _NoRedirect(HTTPRedirectHandler):
|
|
39
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
40
|
+
# urllib normally forwards ordinary request headers during redirects.
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _header_value(value: str, label: str, maximum: int | None = None) -> str:
|
|
45
|
+
if not _HEADER_VALUE.fullmatch(value) or (maximum is not None and len(value) > maximum):
|
|
46
|
+
raise ValueError(f"{label} must be a nonempty printable ASCII value without spaces")
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _segment(value: str, pattern: re.Pattern[str], label: str) -> str:
|
|
51
|
+
if not pattern.fullmatch(value):
|
|
52
|
+
raise ValueError(f"Invalid {label}")
|
|
53
|
+
return quote(value, safe="")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _range(start: date | str, through: date | str) -> dict[str, str]:
|
|
57
|
+
def iso(value: date | str) -> str:
|
|
58
|
+
return date.fromisoformat(value if isinstance(value, str) else value.isoformat()).isoformat()
|
|
59
|
+
|
|
60
|
+
first, last = iso(start), iso(through)
|
|
61
|
+
if first > last:
|
|
62
|
+
raise ValueError("start must be on or before through")
|
|
63
|
+
return {"from": first, "through": last}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class _HTTP:
|
|
67
|
+
def __init__(self, base_url: str, timeout: float, token: str | None = None) -> None:
|
|
68
|
+
url = urlsplit(base_url)
|
|
69
|
+
if (url.scheme != "https" or not url.hostname or url.username is not None
|
|
70
|
+
or url.password is not None or url.query or url.fragment
|
|
71
|
+
or url.path not in ("", "/")):
|
|
72
|
+
raise ValueError("base_url must be an HTTPS origin without credentials")
|
|
73
|
+
if not math.isfinite(timeout) or timeout <= 0:
|
|
74
|
+
raise ValueError("timeout must be positive and finite")
|
|
75
|
+
self._origin = f"https://{url.netloc}"
|
|
76
|
+
self._timeout = timeout
|
|
77
|
+
self._token = _header_value(token, "token") if token is not None else None
|
|
78
|
+
self._opener = build_opener(_NoRedirect())
|
|
79
|
+
|
|
80
|
+
def request(
|
|
81
|
+
self,
|
|
82
|
+
path: str,
|
|
83
|
+
*,
|
|
84
|
+
query: Mapping[str, str | int] | None = None,
|
|
85
|
+
body: Mapping[str, Any] | None = None,
|
|
86
|
+
headers: Mapping[str, str] | None = None,
|
|
87
|
+
max_bytes: int | None = None,
|
|
88
|
+
) -> JsonObject:
|
|
89
|
+
request_headers = {"Accept": "application/json", "User-Agent": "usagemax-python"}
|
|
90
|
+
request_headers.update(headers or {})
|
|
91
|
+
if self._token is not None:
|
|
92
|
+
request_headers["Authorization"] = f"Bearer {self._token}"
|
|
93
|
+
data = None
|
|
94
|
+
if body is not None:
|
|
95
|
+
data = json.dumps(body, allow_nan=False, separators=(",", ":"), sort_keys=True).encode()
|
|
96
|
+
if max_bytes is not None and len(data) > max_bytes:
|
|
97
|
+
raise ValueError(f"JSON request exceeds the {max_bytes}-byte limit")
|
|
98
|
+
request_headers["Content-Type"] = "application/json"
|
|
99
|
+
url = self._origin + path
|
|
100
|
+
if query:
|
|
101
|
+
url += f"?{urlencode(query)}"
|
|
102
|
+
request = Request(url, data=data, headers=request_headers)
|
|
103
|
+
try:
|
|
104
|
+
with self._opener.open(request, timeout=self._timeout) as response:
|
|
105
|
+
document = json.load(response)
|
|
106
|
+
except HTTPError as error:
|
|
107
|
+
with error:
|
|
108
|
+
try:
|
|
109
|
+
payload = json.loads(error.read(16_384))
|
|
110
|
+
except (ValueError, OSError):
|
|
111
|
+
payload = None
|
|
112
|
+
code = payload.get("error") if isinstance(payload, dict) else None
|
|
113
|
+
if not isinstance(code, str) or not re.fullmatch(r"[a-z][a-z0-9_]{0,79}", code):
|
|
114
|
+
code = None
|
|
115
|
+
if code and self._token and self._token in code:
|
|
116
|
+
code = None
|
|
117
|
+
raise APIError(error.code, code, error.headers.get("Retry-After")) from None
|
|
118
|
+
except (URLError, OSError) as error:
|
|
119
|
+
raise TransportError("Could not complete the UsageMax request") from error
|
|
120
|
+
except ValueError as error:
|
|
121
|
+
raise TransportError("UsageMax did not return valid JSON") from error
|
|
122
|
+
if not isinstance(document, dict):
|
|
123
|
+
raise TransportError("UsageMax did not return a JSON object")
|
|
124
|
+
return document
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class UsageMax:
|
|
128
|
+
"""Read UsageMax health, network statistics, and opt-in public profiles."""
|
|
129
|
+
|
|
130
|
+
def __init__(self, *, base_url: str = DEFAULT_URL, timeout: float = 15.0) -> None:
|
|
131
|
+
self._http = _HTTP(base_url, timeout)
|
|
132
|
+
|
|
133
|
+
def health(self) -> JsonObject:
|
|
134
|
+
return self._http.request("/api/health")
|
|
135
|
+
|
|
136
|
+
def stats(self) -> JsonObject:
|
|
137
|
+
return self._http.request("/api/stats")
|
|
138
|
+
|
|
139
|
+
def profile(self, handle: str) -> JsonObject:
|
|
140
|
+
profile = _segment(handle.removeprefix("@"), _PROFILE_HANDLE, "profile handle")
|
|
141
|
+
return self._http.request(f"/api/profiles/{profile}")
|
|
142
|
+
|
|
143
|
+
def daily_usage(
|
|
144
|
+
self, handle: str, *, days: int = 365, group_by: GroupBy | None = None,
|
|
145
|
+
) -> JsonObject:
|
|
146
|
+
profile = _segment(handle.removeprefix("@"), _PROFILE_HANDLE, "profile handle")
|
|
147
|
+
query: dict[str, str | int] = {"days": days}
|
|
148
|
+
if group_by is not None:
|
|
149
|
+
query["groupBy"] = group_by
|
|
150
|
+
return self._http.request(f"/api/profiles/{profile}/daily", query=query)
|
|
151
|
+
|
|
152
|
+
def daily_detail(
|
|
153
|
+
self, handle: str, *, start: date | str, through: date | str,
|
|
154
|
+
group_by: GroupBy = "model", limit: int = 100, cursor: str | None = None,
|
|
155
|
+
) -> JsonObject:
|
|
156
|
+
"""Return one page. Pass the returned continueCursor to fetch the next page."""
|
|
157
|
+
profile = _segment(handle.removeprefix("@"), _PROFILE_HANDLE, "profile handle")
|
|
158
|
+
query: dict[str, str | int] = {**_range(start, through), "groupBy": group_by, "limit": limit}
|
|
159
|
+
if cursor is not None:
|
|
160
|
+
query["cursor"] = cursor
|
|
161
|
+
return self._http.request(f"/api/profiles/{profile}/daily/detail", query=query)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class GatewayClient:
|
|
165
|
+
"""Use a project-scoped gateway key to write receipts or read private reports."""
|
|
166
|
+
|
|
167
|
+
def __init__(self, token: str, *, base_url: str = DEFAULT_URL, timeout: float = 15.0) -> None:
|
|
168
|
+
self._http = _HTTP(base_url, timeout, token)
|
|
169
|
+
|
|
170
|
+
def status(self) -> JsonObject:
|
|
171
|
+
return self._http.request("/api/v1/gateway/status")
|
|
172
|
+
|
|
173
|
+
def write_receipts(self, receipts: Sequence[Mapping[str, Any]]) -> JsonObject:
|
|
174
|
+
"""Send 1–50 settled receipts using an ingest key. Inspect every item result."""
|
|
175
|
+
if not 1 <= len(receipts) <= 50:
|
|
176
|
+
raise ValueError("A gateway batch must contain 1 to 50 receipts")
|
|
177
|
+
return self._http.request(
|
|
178
|
+
"/api/v1/gateway/receipts", body={"receipts": list(receipts)}, max_bytes=65_536,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def receipts(self, *, start: date | str, through: date | str, limit: int = 50) -> JsonObject:
|
|
182
|
+
return self._http.request(
|
|
183
|
+
"/api/v1/gateway/receipts", query={**_range(start, through), "limit": limit},
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def receipt(self, request_id: str) -> JsonObject:
|
|
187
|
+
request_id = _segment(request_id, _REQUEST_ID, "request ID")
|
|
188
|
+
return self._http.request(f"/api/v1/gateway/receipts/{request_id}")
|
|
189
|
+
|
|
190
|
+
def operations(self, *, start: date | str, through: date | str) -> JsonObject:
|
|
191
|
+
return self._http.request("/api/v1/gateway/operations", query=_range(start, through))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class CollectorClient:
|
|
195
|
+
"""Send content-free usage events with an installation-bound collector key."""
|
|
196
|
+
|
|
197
|
+
def __init__(
|
|
198
|
+
self, token: str, *, device_id: str | UUID | None = None,
|
|
199
|
+
base_url: str = DEFAULT_URL, timeout: float = 15.0,
|
|
200
|
+
) -> None:
|
|
201
|
+
self._http = _HTTP(base_url, timeout, token)
|
|
202
|
+
self._device_id = str(UUID(str(device_id))) if device_id is not None else None
|
|
203
|
+
|
|
204
|
+
def status(self) -> JsonObject:
|
|
205
|
+
headers = {"X-UsageMax-Device-ID": self._device_id} if self._device_id else None
|
|
206
|
+
return self._http.request("/api/v1/devices/status", headers=headers)
|
|
207
|
+
|
|
208
|
+
def _ingest(self, path: str, payload: Mapping[str, Any], idempotency_key: str) -> JsonObject:
|
|
209
|
+
if self._device_id is None:
|
|
210
|
+
raise ValueError("device_id is required for collector writes")
|
|
211
|
+
return self._http.request(path, body=payload, max_bytes=1_048_576, headers={
|
|
212
|
+
"X-UsageMax-Device-ID": self._device_id,
|
|
213
|
+
"Idempotency-Key": _header_value(idempotency_key, "idempotency_key", 180),
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
def send_events(
|
|
217
|
+
self, events: Sequence[Mapping[str, Any]], *, idempotency_key: str,
|
|
218
|
+
) -> JsonObject:
|
|
219
|
+
"""Send 1–100 native events. Keep the same key and payload when retrying."""
|
|
220
|
+
if not 1 <= len(events) <= 100:
|
|
221
|
+
raise ValueError("A telemetry batch must contain 1 to 100 events")
|
|
222
|
+
return self._ingest("/api/v1/telemetry/llm", {"events": list(events)}, idempotency_key)
|
|
223
|
+
|
|
224
|
+
def send_traces(self, envelope: Mapping[str, Any], *, idempotency_key: str) -> JsonObject:
|
|
225
|
+
"""Send an OpenTelemetry resourceSpans envelope using OTLP/HTTP JSON."""
|
|
226
|
+
return self._ingest("/api/v1/traces", envelope, idempotency_key)
|
|
File without changes
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import unittest
|
|
4
|
+
from datetime import date
|
|
5
|
+
from email.message import Message
|
|
6
|
+
from unittest.mock import patch
|
|
7
|
+
from urllib.error import HTTPError, URLError
|
|
8
|
+
from urllib.parse import parse_qs, urlsplit
|
|
9
|
+
|
|
10
|
+
from usagemax import APIError, CollectorClient, GatewayClient, TransportError, UsageMax
|
|
11
|
+
|
|
12
|
+
DEVICE_ID = "b14aaf91-f7e5-4aad-af61-d0aefbd150c1"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ClientTests(unittest.TestCase):
|
|
16
|
+
def setUp(self):
|
|
17
|
+
opener = patch("usagemax.client.build_opener")
|
|
18
|
+
self.build_opener = opener.start()
|
|
19
|
+
self.addCleanup(opener.stop)
|
|
20
|
+
self.open = self.build_opener.return_value.open
|
|
21
|
+
self.open.side_effect = lambda *_args, **_kwargs: io.BytesIO(b'{"ok":true}')
|
|
22
|
+
|
|
23
|
+
def request(self):
|
|
24
|
+
return self.open.call_args.args[0]
|
|
25
|
+
|
|
26
|
+
def test_public_health_without_credentials(self):
|
|
27
|
+
self.assertEqual(UsageMax(timeout=2).health(), {"ok": True})
|
|
28
|
+
request = self.request()
|
|
29
|
+
self.assertEqual(request.full_url, "https://usagemax.com/api/health")
|
|
30
|
+
self.assertNotIn("Authorization", request.headers)
|
|
31
|
+
self.assertEqual(self.open.call_args.kwargs["timeout"], 2)
|
|
32
|
+
|
|
33
|
+
def test_daily_detail_passes_opaque_cursor_and_inclusive_dates(self):
|
|
34
|
+
UsageMax().daily_detail(
|
|
35
|
+
"@example", start=date(2026, 11, 1), through="2026-11-22",
|
|
36
|
+
group_by="source", cursor="page+2&x",
|
|
37
|
+
)
|
|
38
|
+
url = urlsplit(self.request().full_url)
|
|
39
|
+
self.assertEqual(url.path, "/api/profiles/example/daily/detail")
|
|
40
|
+
self.assertEqual(parse_qs(url.query), {
|
|
41
|
+
"from": ["2026-11-01"], "through": ["2026-11-22"],
|
|
42
|
+
"groupBy": ["source"], "limit": ["100"], "cursor": ["page+2&x"],
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
def test_gateway_read_and_write(self):
|
|
46
|
+
gateway = GatewayClient("example-key")
|
|
47
|
+
gateway.receipt("gateway:request.1")
|
|
48
|
+
self.assertEqual(self.request().full_url, "https://usagemax.com/api/v1/gateway/receipts/gateway%3Arequest.1")
|
|
49
|
+
self.assertEqual(self.request().get_header("Authorization"), "Bearer example-key")
|
|
50
|
+
|
|
51
|
+
receipts = [{"requestId": "gateway:request.1", "revision": 1}]
|
|
52
|
+
gateway.write_receipts(receipts)
|
|
53
|
+
self.assertEqual(self.request().get_method(), "POST")
|
|
54
|
+
self.assertEqual(self.request().get_header("Content-type"), "application/json")
|
|
55
|
+
self.assertEqual(json.loads(self.request().data), {"receipts": receipts})
|
|
56
|
+
self.assertIsNone(self.request().get_header("X-usagemax-device-id"))
|
|
57
|
+
|
|
58
|
+
gateway.operations(start="2026-11-22", through="2026-11-22")
|
|
59
|
+
self.assertEqual(urlsplit(self.request().full_url).path, "/api/v1/gateway/operations")
|
|
60
|
+
|
|
61
|
+
def test_collector_writes_device_and_idempotency_headers(self):
|
|
62
|
+
collector = CollectorClient("collector-key", device_id=DEVICE_ID)
|
|
63
|
+
first = {"eventKey": "test", "model": "example", "inputTokens": 1}
|
|
64
|
+
collector.send_events([first], idempotency_key="my-batch:1")
|
|
65
|
+
request = self.request()
|
|
66
|
+
self.assertEqual(urlsplit(request.full_url).path, "/api/v1/telemetry/llm")
|
|
67
|
+
self.assertEqual(request.get_header("X-usagemax-device-id"), DEVICE_ID)
|
|
68
|
+
self.assertEqual(request.get_header("Idempotency-key"), "my-batch:1")
|
|
69
|
+
self.assertEqual(request.get_header("Authorization"), "Bearer collector-key")
|
|
70
|
+
collector.send_events([dict(reversed(list(first.items())))], idempotency_key="my-batch:1")
|
|
71
|
+
self.assertEqual(request.data, self.request().data)
|
|
72
|
+
|
|
73
|
+
collector.send_traces({"resourceSpans": []}, idempotency_key="trace:1")
|
|
74
|
+
self.assertEqual(urlsplit(self.request().full_url).path, "/api/v1/traces")
|
|
75
|
+
self.assertEqual(json.loads(self.request().data), {"resourceSpans": []})
|
|
76
|
+
|
|
77
|
+
def test_status_allows_unbound_read_but_writes_require_device(self):
|
|
78
|
+
collector = CollectorClient("collector-key")
|
|
79
|
+
collector.status()
|
|
80
|
+
self.assertEqual(urlsplit(self.request().full_url).path, "/api/v1/devices/status")
|
|
81
|
+
self.assertIsNone(self.request().get_header("X-usagemax-device-id"))
|
|
82
|
+
with self.assertRaisesRegex(ValueError, "device_id is required"):
|
|
83
|
+
collector.send_events([{"eventKey": "event"}], idempotency_key="batch")
|
|
84
|
+
self.assertEqual(self.open.call_count, 1)
|
|
85
|
+
|
|
86
|
+
def test_rejects_invalid_paths_origins_headers_dates_and_batches(self):
|
|
87
|
+
with self.assertRaisesRegex(ValueError, "profile handle"):
|
|
88
|
+
UsageMax().profile("../account")
|
|
89
|
+
with self.assertRaisesRegex(ValueError, "request ID"):
|
|
90
|
+
GatewayClient("key").receipt("..")
|
|
91
|
+
with self.assertRaisesRegex(ValueError, "HTTPS origin"):
|
|
92
|
+
CollectorClient("key", base_url="http://usagemax.com")
|
|
93
|
+
with self.assertRaisesRegex(ValueError, "HTTPS origin"):
|
|
94
|
+
GatewayClient("key", base_url="https://key@usagemax.com")
|
|
95
|
+
with self.assertRaisesRegex(ValueError, "timeout"):
|
|
96
|
+
UsageMax(timeout=float("inf"))
|
|
97
|
+
with self.assertRaisesRegex(ValueError, "token"):
|
|
98
|
+
GatewayClient("key\r\nX-Garbage: header")
|
|
99
|
+
with self.assertRaisesRegex(ValueError, "on or before"):
|
|
100
|
+
GatewayClient("key").receipts(start="2026-11-22", through="2026-11-21")
|
|
101
|
+
with self.assertRaisesRegex(ValueError, "1 to 50"):
|
|
102
|
+
GatewayClient("key").write_receipts([])
|
|
103
|
+
with self.assertRaisesRegex(ValueError, "65536-byte"):
|
|
104
|
+
GatewayClient("key").write_receipts([{"model": "x" * 65_536}])
|
|
105
|
+
with self.assertRaisesRegex(ValueError, "idempotency_key"):
|
|
106
|
+
CollectorClient("key", device_id=DEVICE_ID).send_events([{}], idempotency_key=" ")
|
|
107
|
+
self.open.assert_not_called()
|
|
108
|
+
|
|
109
|
+
def test_redirect_handler_never_follows_redirects(self):
|
|
110
|
+
client = GatewayClient("key")
|
|
111
|
+
redirect = self.build_opener.call_args.args[0]
|
|
112
|
+
self.assertIsNone(redirect.redirect_request(None, None, 302, "", {}, "https://other.example"))
|
|
113
|
+
self.open.side_effect = HTTPError(
|
|
114
|
+
"https://usagemax.com/api/v1/gateway/status", 302, "", Message(), io.BytesIO(b""),
|
|
115
|
+
)
|
|
116
|
+
with self.assertRaises(APIError) as received:
|
|
117
|
+
client.status()
|
|
118
|
+
self.assertEqual(received.exception.status_code, 302)
|
|
119
|
+
self.assertEqual(self.open.call_count, 1)
|
|
120
|
+
|
|
121
|
+
def test_non_success_preserves_structured_error_and_retry_after(self):
|
|
122
|
+
headers = Message()
|
|
123
|
+
headers["Retry-After"] = "30"
|
|
124
|
+
self.open.side_effect = HTTPError(
|
|
125
|
+
"https://usagemax.com", 429, "Too Many Requests", headers,
|
|
126
|
+
io.BytesIO(b'{"error":"rate_limited","hint":"internal details"}'),
|
|
127
|
+
)
|
|
128
|
+
with self.assertRaises(APIError) as raised:
|
|
129
|
+
GatewayClient("example-token").status()
|
|
130
|
+
self.assertEqual(raised.exception.status_code, 429)
|
|
131
|
+
self.assertEqual(raised.exception.code, "rate_limited")
|
|
132
|
+
self.assertEqual(raised.exception.retry_after, "30")
|
|
133
|
+
self.assertNotIn("internal details", str(raised.exception))
|
|
134
|
+
self.assertNotIn("example-token", str(raised.exception))
|
|
135
|
+
|
|
136
|
+
def test_transport_and_response_errors(self):
|
|
137
|
+
for response in (b"garbage", b"[]"):
|
|
138
|
+
with self.subTest(response=response):
|
|
139
|
+
self.open.side_effect = lambda *_args, **_kwargs: io.BytesIO(response)
|
|
140
|
+
with self.assertRaises(TransportError):
|
|
141
|
+
UsageMax().health()
|
|
142
|
+
self.open.side_effect = URLError("timed out")
|
|
143
|
+
with self.assertRaises(TransportError):
|
|
144
|
+
UsageMax().health()
|