avalkit 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.
- avalkit-0.1.0/LICENSE +21 -0
- avalkit-0.1.0/MANIFEST.in +2 -0
- avalkit-0.1.0/PKG-INFO +113 -0
- avalkit-0.1.0/README.md +90 -0
- avalkit-0.1.0/avalkit/__init__.py +28 -0
- avalkit-0.1.0/avalkit/client.py +208 -0
- avalkit-0.1.0/avalkit/errors.py +73 -0
- avalkit-0.1.0/avalkit/resources.py +269 -0
- avalkit-0.1.0/avalkit.egg-info/PKG-INFO +113 -0
- avalkit-0.1.0/avalkit.egg-info/SOURCES.txt +13 -0
- avalkit-0.1.0/avalkit.egg-info/dependency_links.txt +1 -0
- avalkit-0.1.0/avalkit.egg-info/requires.txt +1 -0
- avalkit-0.1.0/avalkit.egg-info/top_level.txt +1 -0
- avalkit-0.1.0/pyproject.toml +37 -0
- avalkit-0.1.0/setup.cfg +4 -0
avalkit-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 avalkit
|
|
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.
|
avalkit-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: avalkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The control layer for AI agents. Set what they're allowed to do, and prove everything they did.
|
|
5
|
+
Author: Erik Bustos
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://avalkit.com
|
|
8
|
+
Keywords: ai,agents,ai-agents,governance,audit,audit-log,spend-controls,compliance
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
17
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
18
|
+
Requires-Python: >=3.9
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: requests>=2.28.0
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# Avalkit Python SDK
|
|
25
|
+
|
|
26
|
+
**The control layer for AI agents. Set what they're allowed to do, and prove everything they did.**
|
|
27
|
+
|
|
28
|
+
Avalkit is for teams building AI agents that spend money. Before an agent acts, it declares an intent. Avalkit checks it against your rules, approves or denies it with a reason, and writes every decision to a hash-chained, tamper-evident audit log.
|
|
29
|
+
|
|
30
|
+
Avalkit decides and records. Your existing payment rails move the money.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
> `pip install avalkit` will be available once the package is published to PyPI.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install avalkit
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Python 3.9 or newer.
|
|
41
|
+
|
|
42
|
+
## Get an API key
|
|
43
|
+
|
|
44
|
+
Request a sign-up link (replace the email with yours):
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
curl -X POST https://mcp.avalkit.com/v1/signup \
|
|
48
|
+
-H "Content-Type: application/json" \
|
|
49
|
+
-d '{"email": "you@example.com"}'
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Open the link in the email. Your API key is shown once, so save it somewhere safe.
|
|
53
|
+
|
|
54
|
+
## Quick start
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from avalkit import Avalkit, AvalkitError
|
|
58
|
+
|
|
59
|
+
av = Avalkit(api_key="ak_...")
|
|
60
|
+
|
|
61
|
+
# 1. In the dashboard (app.avalkit.com), give "travel-agent" rules:
|
|
62
|
+
# for example $500 per purchase, $1,000 per day, category "travel".
|
|
63
|
+
|
|
64
|
+
# 2. Before the agent spends, it declares an intent
|
|
65
|
+
try:
|
|
66
|
+
intent = av.intents.create(
|
|
67
|
+
amount=4700,
|
|
68
|
+
currency="usd",
|
|
69
|
+
purpose="Flight ATL to LAX for the Q3 offsite",
|
|
70
|
+
category="travel",
|
|
71
|
+
user_id="travel-agent",
|
|
72
|
+
vendor="Delta", # optional: who would be paid, shown in the audit log
|
|
73
|
+
)
|
|
74
|
+
except AvalkitError as e:
|
|
75
|
+
# No decision is a no: don't make the purchase.
|
|
76
|
+
print(f"Not approved (Avalkit error): {e}")
|
|
77
|
+
else:
|
|
78
|
+
if intent.approved:
|
|
79
|
+
print("Approved. Pay with your existing payment system.")
|
|
80
|
+
else:
|
|
81
|
+
print(f"Denied ({intent.denial_reason}): {intent.denial_message}")
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Only `intent.approved` means yes. Treat everything else as no: a denial, an exception, a rate limit, a timeout.
|
|
85
|
+
|
|
86
|
+
Every decision, approved or denied, is written to the audit log.
|
|
87
|
+
|
|
88
|
+
Rules are set by a person in the dashboard, not from code: an API key can read rules but not change them, so an agent can't raise its own limits. Without rules for a `user_id`, its intents are denied. A `user_id` can't contain `/`.
|
|
89
|
+
|
|
90
|
+
## Reference
|
|
91
|
+
|
|
92
|
+
| Call | What it does |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `av.intents.create(amount, currency, purpose, category, user_id, vendor=None, metadata=None)` | Check a planned spend against the rules. Returns an `Intent` with `.approved`, `.denial_reason`, `.denial_message`, `.vendor`, `.metadata`. |
|
|
95
|
+
| `av.rules.list()` | List all rules on your account (read-only; change rules in the dashboard). |
|
|
96
|
+
|
|
97
|
+
Amounts are in minor units (cents for USD). `purpose` must be at least 10 characters. `vendor` is optional (up to 100 characters); no rule uses it.
|
|
98
|
+
|
|
99
|
+
`metadata` is optional: your own fields, e.g. `{"ticket": "OPS-12"}` (up to 50 keys, keys up to 100 characters, 4 KB as JSON). It is recorded in the intent's audit entry, covered by its hash, and shown in History and the CSV export; no rule uses it. Text, `True`/`False`, `None` and whole numbers up to 2^53-1 are stored as they are; anything else (decimals, larger numbers, lists, nested objects) is stored as its JSON text, e.g. `0.5` becomes `"0.5"`, so every value reads back exactly as it was hashed. `.metadata` shows what was stored.
|
|
100
|
+
|
|
101
|
+
Errors all inherit from `AvalkitError`: `AvalkitAuthError` (bad or missing key), `AvalkitAPIError` (the API returned an error), `AvalkitRateLimitError` (HTTP 429: too many requests, or the month's decisions are used up; a subclass of `AvalkitAPIError`, with `.retry_after` in seconds, or `None` when the limit resets on the 1st), `AvalkitConnectionError` (network problem), `AvalkitValidationError` (bad input, caught before the request is sent).
|
|
102
|
+
|
|
103
|
+
## Status
|
|
104
|
+
|
|
105
|
+
Beta. The API may change before v1.0.
|
|
106
|
+
|
|
107
|
+
## Pricing
|
|
108
|
+
|
|
109
|
+
Free: 1,000 decisions a month and 7 days of audit history. Starter: $49/month for 25,000 decisions and a year of history, upgrade from the [dashboard](https://app.avalkit.com). Compliance: from $999/month, email founders@avalkit.com. Details at [avalkit.com](https://avalkit.com).
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT
|
avalkit-0.1.0/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Avalkit Python SDK
|
|
2
|
+
|
|
3
|
+
**The control layer for AI agents. Set what they're allowed to do, and prove everything they did.**
|
|
4
|
+
|
|
5
|
+
Avalkit is for teams building AI agents that spend money. Before an agent acts, it declares an intent. Avalkit checks it against your rules, approves or denies it with a reason, and writes every decision to a hash-chained, tamper-evident audit log.
|
|
6
|
+
|
|
7
|
+
Avalkit decides and records. Your existing payment rails move the money.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
> `pip install avalkit` will be available once the package is published to PyPI.
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install avalkit
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Python 3.9 or newer.
|
|
18
|
+
|
|
19
|
+
## Get an API key
|
|
20
|
+
|
|
21
|
+
Request a sign-up link (replace the email with yours):
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
curl -X POST https://mcp.avalkit.com/v1/signup \
|
|
25
|
+
-H "Content-Type: application/json" \
|
|
26
|
+
-d '{"email": "you@example.com"}'
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Open the link in the email. Your API key is shown once, so save it somewhere safe.
|
|
30
|
+
|
|
31
|
+
## Quick start
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from avalkit import Avalkit, AvalkitError
|
|
35
|
+
|
|
36
|
+
av = Avalkit(api_key="ak_...")
|
|
37
|
+
|
|
38
|
+
# 1. In the dashboard (app.avalkit.com), give "travel-agent" rules:
|
|
39
|
+
# for example $500 per purchase, $1,000 per day, category "travel".
|
|
40
|
+
|
|
41
|
+
# 2. Before the agent spends, it declares an intent
|
|
42
|
+
try:
|
|
43
|
+
intent = av.intents.create(
|
|
44
|
+
amount=4700,
|
|
45
|
+
currency="usd",
|
|
46
|
+
purpose="Flight ATL to LAX for the Q3 offsite",
|
|
47
|
+
category="travel",
|
|
48
|
+
user_id="travel-agent",
|
|
49
|
+
vendor="Delta", # optional: who would be paid, shown in the audit log
|
|
50
|
+
)
|
|
51
|
+
except AvalkitError as e:
|
|
52
|
+
# No decision is a no: don't make the purchase.
|
|
53
|
+
print(f"Not approved (Avalkit error): {e}")
|
|
54
|
+
else:
|
|
55
|
+
if intent.approved:
|
|
56
|
+
print("Approved. Pay with your existing payment system.")
|
|
57
|
+
else:
|
|
58
|
+
print(f"Denied ({intent.denial_reason}): {intent.denial_message}")
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Only `intent.approved` means yes. Treat everything else as no: a denial, an exception, a rate limit, a timeout.
|
|
62
|
+
|
|
63
|
+
Every decision, approved or denied, is written to the audit log.
|
|
64
|
+
|
|
65
|
+
Rules are set by a person in the dashboard, not from code: an API key can read rules but not change them, so an agent can't raise its own limits. Without rules for a `user_id`, its intents are denied. A `user_id` can't contain `/`.
|
|
66
|
+
|
|
67
|
+
## Reference
|
|
68
|
+
|
|
69
|
+
| Call | What it does |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `av.intents.create(amount, currency, purpose, category, user_id, vendor=None, metadata=None)` | Check a planned spend against the rules. Returns an `Intent` with `.approved`, `.denial_reason`, `.denial_message`, `.vendor`, `.metadata`. |
|
|
72
|
+
| `av.rules.list()` | List all rules on your account (read-only; change rules in the dashboard). |
|
|
73
|
+
|
|
74
|
+
Amounts are in minor units (cents for USD). `purpose` must be at least 10 characters. `vendor` is optional (up to 100 characters); no rule uses it.
|
|
75
|
+
|
|
76
|
+
`metadata` is optional: your own fields, e.g. `{"ticket": "OPS-12"}` (up to 50 keys, keys up to 100 characters, 4 KB as JSON). It is recorded in the intent's audit entry, covered by its hash, and shown in History and the CSV export; no rule uses it. Text, `True`/`False`, `None` and whole numbers up to 2^53-1 are stored as they are; anything else (decimals, larger numbers, lists, nested objects) is stored as its JSON text, e.g. `0.5` becomes `"0.5"`, so every value reads back exactly as it was hashed. `.metadata` shows what was stored.
|
|
77
|
+
|
|
78
|
+
Errors all inherit from `AvalkitError`: `AvalkitAuthError` (bad or missing key), `AvalkitAPIError` (the API returned an error), `AvalkitRateLimitError` (HTTP 429: too many requests, or the month's decisions are used up; a subclass of `AvalkitAPIError`, with `.retry_after` in seconds, or `None` when the limit resets on the 1st), `AvalkitConnectionError` (network problem), `AvalkitValidationError` (bad input, caught before the request is sent).
|
|
79
|
+
|
|
80
|
+
## Status
|
|
81
|
+
|
|
82
|
+
Beta. The API may change before v1.0.
|
|
83
|
+
|
|
84
|
+
## Pricing
|
|
85
|
+
|
|
86
|
+
Free: 1,000 decisions a month and 7 days of audit history. Starter: $49/month for 25,000 decisions and a year of history, upgrade from the [dashboard](https://app.avalkit.com). Compliance: from $999/month, email founders@avalkit.com. Details at [avalkit.com](https://avalkit.com).
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
MIT
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Avalkit SDK: the control layer for AI agents."""
|
|
2
|
+
|
|
3
|
+
from .client import Avalkit
|
|
4
|
+
from .errors import (
|
|
5
|
+
AvalkitAPIError,
|
|
6
|
+
AvalkitAuthError,
|
|
7
|
+
AvalkitConnectionError,
|
|
8
|
+
AvalkitError,
|
|
9
|
+
AvalkitRateLimitError,
|
|
10
|
+
AvalkitValidationError,
|
|
11
|
+
)
|
|
12
|
+
from .resources import Intent, Receipt, Rules
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"Avalkit",
|
|
18
|
+
"AvalkitError",
|
|
19
|
+
"AvalkitAuthError",
|
|
20
|
+
"AvalkitAPIError",
|
|
21
|
+
"AvalkitConnectionError",
|
|
22
|
+
"AvalkitRateLimitError",
|
|
23
|
+
"AvalkitValidationError",
|
|
24
|
+
"Intent",
|
|
25
|
+
"Receipt",
|
|
26
|
+
"Rules",
|
|
27
|
+
"__version__",
|
|
28
|
+
]
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Main Avalkit SDK client."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
|
|
7
|
+
from .errors import (
|
|
8
|
+
AvalkitAPIError,
|
|
9
|
+
AvalkitAuthError,
|
|
10
|
+
AvalkitConnectionError,
|
|
11
|
+
AvalkitRateLimitError,
|
|
12
|
+
AvalkitValidationError,
|
|
13
|
+
)
|
|
14
|
+
from .resources import Intent, Receipt, Rules
|
|
15
|
+
|
|
16
|
+
DEFAULT_BASE_URL = "https://mcp.avalkit.com"
|
|
17
|
+
DEFAULT_TIMEOUT_SECONDS = 30
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _parse_error(response) -> "tuple[str, Optional[str]]":
|
|
21
|
+
"""Turn an error response into (plain message, error code or None).
|
|
22
|
+
|
|
23
|
+
Handles the shapes the Avalkit API returns:
|
|
24
|
+
{"detail": "Invalid API key"}
|
|
25
|
+
{"detail": {"error": "monthly_limit_exceeded", "message": "..."}}
|
|
26
|
+
{"detail": [{"loc": [...], "msg": "...", ...}]} (request validation)
|
|
27
|
+
{"error": {"code": "...", "message": "..."}}
|
|
28
|
+
and falls back to the response text for anything else.
|
|
29
|
+
"""
|
|
30
|
+
fallback = f"HTTP {response.status_code}"
|
|
31
|
+
try:
|
|
32
|
+
payload = response.json()
|
|
33
|
+
except ValueError:
|
|
34
|
+
return (response.text or "").strip() or fallback, None
|
|
35
|
+
|
|
36
|
+
if isinstance(payload, dict):
|
|
37
|
+
detail = payload.get("detail")
|
|
38
|
+
if isinstance(detail, str) and detail:
|
|
39
|
+
return detail, None
|
|
40
|
+
if isinstance(detail, dict):
|
|
41
|
+
message = detail.get("message") or detail.get("error") or fallback
|
|
42
|
+
return str(message), detail.get("error")
|
|
43
|
+
if isinstance(detail, list) and detail:
|
|
44
|
+
parts = []
|
|
45
|
+
for item in detail:
|
|
46
|
+
if isinstance(item, dict):
|
|
47
|
+
loc = ".".join(str(x) for x in item.get("loc", []) if x != "body")
|
|
48
|
+
msg = item.get("msg", "")
|
|
49
|
+
parts.append(f"{loc}: {msg}" if loc else msg)
|
|
50
|
+
else:
|
|
51
|
+
parts.append(str(item))
|
|
52
|
+
return "; ".join(p for p in parts if p) or fallback, None
|
|
53
|
+
error = payload.get("error")
|
|
54
|
+
if isinstance(error, dict):
|
|
55
|
+
return str(error.get("message") or fallback), error.get("code")
|
|
56
|
+
if isinstance(error, str) and error:
|
|
57
|
+
return error, None
|
|
58
|
+
|
|
59
|
+
return fallback, None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _retry_after(response) -> Optional[int]:
|
|
63
|
+
"""Seconds from a Retry-After header, or None if missing or not a number."""
|
|
64
|
+
value = (response.headers or {}).get("Retry-After") or (response.headers or {}).get("retry-after")
|
|
65
|
+
try:
|
|
66
|
+
return max(0, int(str(value).strip()))
|
|
67
|
+
except (TypeError, ValueError):
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Avalkit:
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
api_key: str,
|
|
75
|
+
*,
|
|
76
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
77
|
+
timeout: int = DEFAULT_TIMEOUT_SECONDS,
|
|
78
|
+
):
|
|
79
|
+
if not api_key or not isinstance(api_key, str):
|
|
80
|
+
raise AvalkitValidationError("api_key is required and must be a string")
|
|
81
|
+
|
|
82
|
+
self.api_key = api_key
|
|
83
|
+
self.base_url = base_url.rstrip("/")
|
|
84
|
+
self.timeout = timeout
|
|
85
|
+
self.intents = _IntentsResource(self)
|
|
86
|
+
self.rules = _RulesResource(self)
|
|
87
|
+
|
|
88
|
+
def _headers(self) -> dict:
|
|
89
|
+
return {
|
|
90
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
91
|
+
"Content-Type": "application/json",
|
|
92
|
+
"User-Agent": "avalkit-python/0.1.0",
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
def _request(self, method, path, *, json=None, params=None):
|
|
96
|
+
url = f"{self.base_url}{path}"
|
|
97
|
+
try:
|
|
98
|
+
response = requests.request(
|
|
99
|
+
method=method,
|
|
100
|
+
url=url,
|
|
101
|
+
headers=self._headers(),
|
|
102
|
+
json=json,
|
|
103
|
+
params=params,
|
|
104
|
+
timeout=self.timeout,
|
|
105
|
+
)
|
|
106
|
+
except requests.Timeout:
|
|
107
|
+
raise AvalkitConnectionError(f"Request to {url} timed out")
|
|
108
|
+
except requests.ConnectionError as e:
|
|
109
|
+
raise AvalkitConnectionError(f"Could not connect to {url}: {e}")
|
|
110
|
+
except requests.RequestException as e:
|
|
111
|
+
raise AvalkitConnectionError(f"Request failed: {e}")
|
|
112
|
+
|
|
113
|
+
request_id = response.headers.get("x-request-id")
|
|
114
|
+
|
|
115
|
+
if response.status_code >= 400:
|
|
116
|
+
message, error_code = _parse_error(response)
|
|
117
|
+
if response.status_code == 429:
|
|
118
|
+
raise AvalkitRateLimitError(
|
|
119
|
+
message,
|
|
120
|
+
status_code=429,
|
|
121
|
+
error_code=error_code,
|
|
122
|
+
request_id=request_id,
|
|
123
|
+
retry_after=_retry_after(response),
|
|
124
|
+
)
|
|
125
|
+
if response.status_code in (401, 403):
|
|
126
|
+
raise AvalkitAuthError(
|
|
127
|
+
message,
|
|
128
|
+
status_code=response.status_code,
|
|
129
|
+
request_id=request_id,
|
|
130
|
+
)
|
|
131
|
+
raise AvalkitAPIError(
|
|
132
|
+
message,
|
|
133
|
+
status_code=response.status_code,
|
|
134
|
+
error_code=error_code,
|
|
135
|
+
request_id=request_id,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
try:
|
|
139
|
+
return response.json()
|
|
140
|
+
except ValueError:
|
|
141
|
+
raise AvalkitAPIError(
|
|
142
|
+
"API returned invalid JSON", status_code=response.status_code
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class _IntentsResource:
|
|
147
|
+
def __init__(self, client):
|
|
148
|
+
self._client = client
|
|
149
|
+
|
|
150
|
+
def create(
|
|
151
|
+
self,
|
|
152
|
+
*,
|
|
153
|
+
amount: int,
|
|
154
|
+
currency: str,
|
|
155
|
+
purpose: str,
|
|
156
|
+
category: str,
|
|
157
|
+
user_id: str,
|
|
158
|
+
vendor: Optional[str] = None,
|
|
159
|
+
metadata: Optional[dict] = None,
|
|
160
|
+
) -> Intent:
|
|
161
|
+
if amount <= 0:
|
|
162
|
+
raise AvalkitValidationError("amount must be positive")
|
|
163
|
+
if not currency or len(currency) != 3:
|
|
164
|
+
raise AvalkitValidationError("currency must be a 3-letter ISO code")
|
|
165
|
+
if not purpose or len(purpose) < 10:
|
|
166
|
+
raise AvalkitValidationError("purpose must be at least 10 characters")
|
|
167
|
+
|
|
168
|
+
payload = {
|
|
169
|
+
"amount": amount,
|
|
170
|
+
"currency": currency.lower(),
|
|
171
|
+
"purpose": purpose,
|
|
172
|
+
"category": category,
|
|
173
|
+
"user_id": user_id,
|
|
174
|
+
}
|
|
175
|
+
if vendor is not None:
|
|
176
|
+
payload["vendor"] = vendor
|
|
177
|
+
if metadata is not None:
|
|
178
|
+
payload["metadata"] = metadata
|
|
179
|
+
|
|
180
|
+
data = self._client._request("POST", "/v1/intents", json=payload)
|
|
181
|
+
return Intent.from_dict(data, client=self._client)
|
|
182
|
+
|
|
183
|
+
def execute(self, intent_id, *, payment_method, idempotency_key: Optional[str] = None):
|
|
184
|
+
"""Demo payment path (Stripe test mode). Each approved intent can be
|
|
185
|
+
charged once: the API makes retries safe on its own, so
|
|
186
|
+
idempotency_key is optional and kept only for older callers."""
|
|
187
|
+
payload = {"payment_method": payment_method}
|
|
188
|
+
if idempotency_key is not None:
|
|
189
|
+
payload["idempotency_key"] = idempotency_key
|
|
190
|
+
data = self._client._request(
|
|
191
|
+
"POST", f"/v1/intents/{intent_id}/execute", json=payload
|
|
192
|
+
)
|
|
193
|
+
return Receipt.from_dict(data)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class _RulesResource:
|
|
197
|
+
"""Read the account's rules: av.rules.list().
|
|
198
|
+
|
|
199
|
+
Rules are changed by a person in the dashboard (app.avalkit.com), never
|
|
200
|
+
with an API key, so an agent can't raise its own limits."""
|
|
201
|
+
|
|
202
|
+
def __init__(self, client):
|
|
203
|
+
self._client = client
|
|
204
|
+
|
|
205
|
+
def list(self) -> list:
|
|
206
|
+
"""List all rules on your account."""
|
|
207
|
+
data = self._client._request("GET", "/v1/rules")
|
|
208
|
+
return [Rules.from_dict(item) for item in data.get("data", [])]
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Custom exceptions for the Avalkit SDK."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AvalkitError(Exception):
|
|
7
|
+
"""Base exception for all Avalkit SDK errors.
|
|
8
|
+
|
|
9
|
+
Catch this if you want to handle any Avalkit-related failure generically.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, message: str, *, request_id: Optional[str] = None):
|
|
13
|
+
super().__init__(message)
|
|
14
|
+
self.request_id = request_id
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AvalkitAuthError(AvalkitError):
|
|
18
|
+
"""Raised when the API key is missing, invalid, or has been revoked.
|
|
19
|
+
|
|
20
|
+
status_code is 401 (missing or invalid key) or 403 (revoked key).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, message: str, *, status_code: Optional[int] = None, request_id: Optional[str] = None):
|
|
24
|
+
super().__init__(message, request_id=request_id)
|
|
25
|
+
self.status_code = status_code
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class AvalkitAPIError(AvalkitError):
|
|
29
|
+
"""Raised when the API returns an error response (4xx or 5xx).
|
|
30
|
+
|
|
31
|
+
Includes the HTTP status code and the error code from the response.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
message: str,
|
|
37
|
+
*,
|
|
38
|
+
status_code: Optional[int] = None,
|
|
39
|
+
error_code: Optional[str] = None,
|
|
40
|
+
request_id: Optional[str] = None,
|
|
41
|
+
):
|
|
42
|
+
super().__init__(message, request_id=request_id)
|
|
43
|
+
self.status_code = status_code
|
|
44
|
+
self.error_code = error_code
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class AvalkitRateLimitError(AvalkitAPIError):
|
|
48
|
+
"""Raised on HTTP 429: too many requests, or the plan's monthly decisions
|
|
49
|
+
are used up. Treat it as "not approved": don't make the purchase.
|
|
50
|
+
|
|
51
|
+
retry_after is the number of seconds to wait (from the Retry-After
|
|
52
|
+
header), or None when there is nothing to wait for (the monthly limit
|
|
53
|
+
resets on the 1st; the message says when).
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(self, message: str, *, retry_after: Optional[int] = None, **kwargs):
|
|
57
|
+
super().__init__(message, **kwargs)
|
|
58
|
+
self.retry_after = retry_after
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class AvalkitConnectionError(AvalkitError):
|
|
62
|
+
"""Raised when the SDK cannot reach the Avalkit API.
|
|
63
|
+
|
|
64
|
+
Network failure, timeout, or DNS issue. Usually transient — safe to retry.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class AvalkitValidationError(AvalkitError):
|
|
69
|
+
"""Raised when the request fails client-side validation before being sent.
|
|
70
|
+
|
|
71
|
+
Catches obvious problems (missing required fields, invalid amounts) before
|
|
72
|
+
burning a network round-trip.
|
|
73
|
+
"""
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""Intent and Receipt resource classes."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Any, Optional, TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .client import Avalkit
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _parse_datetime(value: Optional[str]) -> Optional[datetime]:
|
|
11
|
+
"""Parse an ISO 8601 datetime string from the API."""
|
|
12
|
+
if not value:
|
|
13
|
+
return None
|
|
14
|
+
# Handle 'Z' suffix (Python <3.11 doesn't parse it directly)
|
|
15
|
+
if value.endswith("Z"):
|
|
16
|
+
value = value[:-1] + "+00:00"
|
|
17
|
+
try:
|
|
18
|
+
return datetime.fromisoformat(value)
|
|
19
|
+
except (ValueError, TypeError):
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Intent:
|
|
24
|
+
"""A spend intent — the result of submitting a request for approval.
|
|
25
|
+
|
|
26
|
+
Attributes:
|
|
27
|
+
id: Unique identifier (e.g. 'int_abc123...')
|
|
28
|
+
status: 'approved' or 'denied'
|
|
29
|
+
approved: Boolean shortcut — True if status == 'approved'
|
|
30
|
+
amount: Amount in minor units (e.g. cents)
|
|
31
|
+
currency: ISO 4217 code
|
|
32
|
+
purpose: Human-readable description
|
|
33
|
+
category: Category string
|
|
34
|
+
user_id: Your end-user identifier
|
|
35
|
+
vendor: Who would be paid, if given
|
|
36
|
+
metadata: Your own fields, as the audit log stored them (or None)
|
|
37
|
+
rules_evaluated: List of rule check results
|
|
38
|
+
denial_reason: Short code if denied (e.g. 'amount_exceeds_limit')
|
|
39
|
+
denial_message: Human-readable explanation if denied
|
|
40
|
+
expires_at: When this intent can no longer be executed (if approved)
|
|
41
|
+
created_at: When the intent was created
|
|
42
|
+
|
|
43
|
+
Methods:
|
|
44
|
+
execute(payment_method, idempotency_key): Charge the card if approved.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
*,
|
|
50
|
+
id: str,
|
|
51
|
+
status: str,
|
|
52
|
+
amount: int,
|
|
53
|
+
currency: str,
|
|
54
|
+
purpose: str,
|
|
55
|
+
category: str,
|
|
56
|
+
user_id: str,
|
|
57
|
+
rules_evaluated: list,
|
|
58
|
+
vendor: Optional[str] = None,
|
|
59
|
+
metadata: Optional[dict] = None,
|
|
60
|
+
denial_reason: Optional[str],
|
|
61
|
+
denial_message: Optional[str],
|
|
62
|
+
expires_at: Optional[datetime],
|
|
63
|
+
created_at: datetime,
|
|
64
|
+
_client: Optional["Avalkit"] = None,
|
|
65
|
+
):
|
|
66
|
+
self.id = id
|
|
67
|
+
self.status = status
|
|
68
|
+
self.amount = amount
|
|
69
|
+
self.currency = currency
|
|
70
|
+
self.purpose = purpose
|
|
71
|
+
self.category = category
|
|
72
|
+
self.user_id = user_id
|
|
73
|
+
self.vendor = vendor
|
|
74
|
+
self.metadata = metadata
|
|
75
|
+
self.rules_evaluated = rules_evaluated
|
|
76
|
+
self.denial_reason = denial_reason
|
|
77
|
+
self.denial_message = denial_message
|
|
78
|
+
self.expires_at = expires_at
|
|
79
|
+
self.created_at = created_at
|
|
80
|
+
self._client = _client
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def approved(self) -> bool:
|
|
84
|
+
"""True only if this intent was approved. Treat anything else as no."""
|
|
85
|
+
return self.status == "approved"
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def denied(self) -> bool:
|
|
89
|
+
"""True if this intent was denied by the rules engine."""
|
|
90
|
+
return self.status == "denied"
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def from_dict(cls, data: dict, *, client: Optional["Avalkit"] = None) -> "Intent":
|
|
94
|
+
"""Build an Intent from an API response dict."""
|
|
95
|
+
return cls(
|
|
96
|
+
id=data["id"],
|
|
97
|
+
status=data["status"],
|
|
98
|
+
amount=data["amount"],
|
|
99
|
+
currency=data["currency"],
|
|
100
|
+
purpose=data["purpose"],
|
|
101
|
+
category=data["category"],
|
|
102
|
+
user_id=data["user_id"],
|
|
103
|
+
vendor=data.get("vendor"),
|
|
104
|
+
metadata=data.get("metadata"),
|
|
105
|
+
rules_evaluated=data.get("rules_evaluated", []),
|
|
106
|
+
denial_reason=data.get("denial_reason"),
|
|
107
|
+
denial_message=data.get("denial_message"),
|
|
108
|
+
expires_at=_parse_datetime(data.get("expires_at")),
|
|
109
|
+
created_at=_parse_datetime(data["created_at"]),
|
|
110
|
+
_client=client,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def execute(
|
|
114
|
+
self,
|
|
115
|
+
*,
|
|
116
|
+
payment_method: str,
|
|
117
|
+
idempotency_key: Optional[str] = None,
|
|
118
|
+
) -> "Receipt":
|
|
119
|
+
"""Execute this intent by charging via Stripe.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
payment_method: Stripe payment method ID (e.g. 'pm_card_visa' for testing)
|
|
123
|
+
idempotency_key: Optional; not needed. Each intent is charged at most
|
|
124
|
+
once, so retries are safe without it.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
A Receipt object describing the charge result.
|
|
128
|
+
|
|
129
|
+
Raises:
|
|
130
|
+
RuntimeError: If this Intent was not created via an SDK client.
|
|
131
|
+
AvalkitAPIError: If the intent is not approved or has expired.
|
|
132
|
+
"""
|
|
133
|
+
if self._client is None:
|
|
134
|
+
raise RuntimeError(
|
|
135
|
+
"This Intent has no SDK client attached and cannot be executed. "
|
|
136
|
+
"Use Avalkit(...).intents.execute(intent_id, ...) instead."
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
if not self.approved:
|
|
140
|
+
raise RuntimeError(
|
|
141
|
+
f"Cannot execute intent with status '{self.status}'. "
|
|
142
|
+
f"Only approved intents can be executed."
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
return self._client.intents.execute(
|
|
146
|
+
self.id,
|
|
147
|
+
payment_method=payment_method,
|
|
148
|
+
idempotency_key=idempotency_key,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
def __repr__(self) -> str:
|
|
152
|
+
return (
|
|
153
|
+
f"<Intent id={self.id!r} status={self.status!r} "
|
|
154
|
+
f"amount={self.amount} currency={self.currency!r}>"
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class Receipt:
|
|
159
|
+
"""The result of executing an intent — a real or attempted charge.
|
|
160
|
+
|
|
161
|
+
Attributes:
|
|
162
|
+
id: Unique identifier (e.g. 'rcp_abc123...')
|
|
163
|
+
intent_id: The intent this receipt corresponds to
|
|
164
|
+
status: 'succeeded' or 'failed'
|
|
165
|
+
succeeded: Boolean shortcut — True if status == 'succeeded'
|
|
166
|
+
amount: Amount in minor units
|
|
167
|
+
currency: ISO 4217 code
|
|
168
|
+
stripe_charge_id: The underlying Stripe PaymentIntent ID, if successful
|
|
169
|
+
audit_hash: The hash of this entry in the audit log chain
|
|
170
|
+
failure_reason: Short code if failed (e.g. 'card_declined')
|
|
171
|
+
failure_message: Human-readable explanation if failed
|
|
172
|
+
executed_at: When the charge was attempted
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
def __init__(
|
|
176
|
+
self,
|
|
177
|
+
*,
|
|
178
|
+
id: str,
|
|
179
|
+
intent_id: str,
|
|
180
|
+
status: str,
|
|
181
|
+
amount: int,
|
|
182
|
+
currency: str,
|
|
183
|
+
stripe_charge_id: Optional[str],
|
|
184
|
+
audit_hash: Optional[str],
|
|
185
|
+
failure_reason: Optional[str],
|
|
186
|
+
failure_message: Optional[str],
|
|
187
|
+
executed_at: datetime,
|
|
188
|
+
):
|
|
189
|
+
self.id = id
|
|
190
|
+
self.intent_id = intent_id
|
|
191
|
+
self.status = status
|
|
192
|
+
self.amount = amount
|
|
193
|
+
self.currency = currency
|
|
194
|
+
self.stripe_charge_id = stripe_charge_id
|
|
195
|
+
self.audit_hash = audit_hash
|
|
196
|
+
self.failure_reason = failure_reason
|
|
197
|
+
self.failure_message = failure_message
|
|
198
|
+
self.executed_at = executed_at
|
|
199
|
+
|
|
200
|
+
@property
|
|
201
|
+
def succeeded(self) -> bool:
|
|
202
|
+
"""True if the charge succeeded."""
|
|
203
|
+
return self.status == "succeeded"
|
|
204
|
+
|
|
205
|
+
@property
|
|
206
|
+
def failed(self) -> bool:
|
|
207
|
+
"""True if the charge failed."""
|
|
208
|
+
return self.status == "failed"
|
|
209
|
+
|
|
210
|
+
@classmethod
|
|
211
|
+
def from_dict(cls, data: dict) -> "Receipt":
|
|
212
|
+
"""Build a Receipt from an API response dict."""
|
|
213
|
+
return cls(
|
|
214
|
+
id=data["id"],
|
|
215
|
+
intent_id=data["intent_id"],
|
|
216
|
+
status=data["status"],
|
|
217
|
+
amount=data["amount"],
|
|
218
|
+
currency=data["currency"],
|
|
219
|
+
stripe_charge_id=data.get("stripe_charge_id"),
|
|
220
|
+
audit_hash=data.get("audit_hash"),
|
|
221
|
+
failure_reason=data.get("failure_reason"),
|
|
222
|
+
failure_message=data.get("failure_message"),
|
|
223
|
+
executed_at=_parse_datetime(data["executed_at"]),
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
def __repr__(self) -> str:
|
|
227
|
+
return (
|
|
228
|
+
f"<Receipt id={self.id!r} status={self.status!r} "
|
|
229
|
+
f"intent_id={self.intent_id!r}>"
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class Rules:
|
|
234
|
+
"""A rule set for a specific user_id under your API key."""
|
|
235
|
+
|
|
236
|
+
def __init__(
|
|
237
|
+
self,
|
|
238
|
+
*,
|
|
239
|
+
user_id: str,
|
|
240
|
+
max_amount_per_intent: Optional[int],
|
|
241
|
+
daily_limit: Optional[int],
|
|
242
|
+
allowed_categories: Optional[list],
|
|
243
|
+
created_at: datetime,
|
|
244
|
+
updated_at: datetime,
|
|
245
|
+
):
|
|
246
|
+
self.user_id = user_id
|
|
247
|
+
self.max_amount_per_intent = max_amount_per_intent
|
|
248
|
+
self.daily_limit = daily_limit
|
|
249
|
+
self.allowed_categories = allowed_categories
|
|
250
|
+
self.created_at = created_at
|
|
251
|
+
self.updated_at = updated_at
|
|
252
|
+
|
|
253
|
+
@classmethod
|
|
254
|
+
def from_dict(cls, data: dict) -> "Rules":
|
|
255
|
+
return cls(
|
|
256
|
+
user_id=data["user_id"],
|
|
257
|
+
max_amount_per_intent=data.get("max_amount_per_intent"),
|
|
258
|
+
daily_limit=data.get("daily_limit"),
|
|
259
|
+
allowed_categories=data.get("allowed_categories"),
|
|
260
|
+
created_at=_parse_datetime(data["created_at"]),
|
|
261
|
+
updated_at=_parse_datetime(data["updated_at"]),
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
def __repr__(self) -> str:
|
|
265
|
+
return (
|
|
266
|
+
f"<Rules user_id={self.user_id!r} "
|
|
267
|
+
f"max_per_intent={self.max_amount_per_intent} "
|
|
268
|
+
f"daily_limit={self.daily_limit}>"
|
|
269
|
+
)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: avalkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The control layer for AI agents. Set what they're allowed to do, and prove everything they did.
|
|
5
|
+
Author: Erik Bustos
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://avalkit.com
|
|
8
|
+
Keywords: ai,agents,ai-agents,governance,audit,audit-log,spend-controls,compliance
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
17
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
18
|
+
Requires-Python: >=3.9
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: requests>=2.28.0
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# Avalkit Python SDK
|
|
25
|
+
|
|
26
|
+
**The control layer for AI agents. Set what they're allowed to do, and prove everything they did.**
|
|
27
|
+
|
|
28
|
+
Avalkit is for teams building AI agents that spend money. Before an agent acts, it declares an intent. Avalkit checks it against your rules, approves or denies it with a reason, and writes every decision to a hash-chained, tamper-evident audit log.
|
|
29
|
+
|
|
30
|
+
Avalkit decides and records. Your existing payment rails move the money.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
> `pip install avalkit` will be available once the package is published to PyPI.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install avalkit
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Python 3.9 or newer.
|
|
41
|
+
|
|
42
|
+
## Get an API key
|
|
43
|
+
|
|
44
|
+
Request a sign-up link (replace the email with yours):
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
curl -X POST https://mcp.avalkit.com/v1/signup \
|
|
48
|
+
-H "Content-Type: application/json" \
|
|
49
|
+
-d '{"email": "you@example.com"}'
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Open the link in the email. Your API key is shown once, so save it somewhere safe.
|
|
53
|
+
|
|
54
|
+
## Quick start
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from avalkit import Avalkit, AvalkitError
|
|
58
|
+
|
|
59
|
+
av = Avalkit(api_key="ak_...")
|
|
60
|
+
|
|
61
|
+
# 1. In the dashboard (app.avalkit.com), give "travel-agent" rules:
|
|
62
|
+
# for example $500 per purchase, $1,000 per day, category "travel".
|
|
63
|
+
|
|
64
|
+
# 2. Before the agent spends, it declares an intent
|
|
65
|
+
try:
|
|
66
|
+
intent = av.intents.create(
|
|
67
|
+
amount=4700,
|
|
68
|
+
currency="usd",
|
|
69
|
+
purpose="Flight ATL to LAX for the Q3 offsite",
|
|
70
|
+
category="travel",
|
|
71
|
+
user_id="travel-agent",
|
|
72
|
+
vendor="Delta", # optional: who would be paid, shown in the audit log
|
|
73
|
+
)
|
|
74
|
+
except AvalkitError as e:
|
|
75
|
+
# No decision is a no: don't make the purchase.
|
|
76
|
+
print(f"Not approved (Avalkit error): {e}")
|
|
77
|
+
else:
|
|
78
|
+
if intent.approved:
|
|
79
|
+
print("Approved. Pay with your existing payment system.")
|
|
80
|
+
else:
|
|
81
|
+
print(f"Denied ({intent.denial_reason}): {intent.denial_message}")
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Only `intent.approved` means yes. Treat everything else as no: a denial, an exception, a rate limit, a timeout.
|
|
85
|
+
|
|
86
|
+
Every decision, approved or denied, is written to the audit log.
|
|
87
|
+
|
|
88
|
+
Rules are set by a person in the dashboard, not from code: an API key can read rules but not change them, so an agent can't raise its own limits. Without rules for a `user_id`, its intents are denied. A `user_id` can't contain `/`.
|
|
89
|
+
|
|
90
|
+
## Reference
|
|
91
|
+
|
|
92
|
+
| Call | What it does |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `av.intents.create(amount, currency, purpose, category, user_id, vendor=None, metadata=None)` | Check a planned spend against the rules. Returns an `Intent` with `.approved`, `.denial_reason`, `.denial_message`, `.vendor`, `.metadata`. |
|
|
95
|
+
| `av.rules.list()` | List all rules on your account (read-only; change rules in the dashboard). |
|
|
96
|
+
|
|
97
|
+
Amounts are in minor units (cents for USD). `purpose` must be at least 10 characters. `vendor` is optional (up to 100 characters); no rule uses it.
|
|
98
|
+
|
|
99
|
+
`metadata` is optional: your own fields, e.g. `{"ticket": "OPS-12"}` (up to 50 keys, keys up to 100 characters, 4 KB as JSON). It is recorded in the intent's audit entry, covered by its hash, and shown in History and the CSV export; no rule uses it. Text, `True`/`False`, `None` and whole numbers up to 2^53-1 are stored as they are; anything else (decimals, larger numbers, lists, nested objects) is stored as its JSON text, e.g. `0.5` becomes `"0.5"`, so every value reads back exactly as it was hashed. `.metadata` shows what was stored.
|
|
100
|
+
|
|
101
|
+
Errors all inherit from `AvalkitError`: `AvalkitAuthError` (bad or missing key), `AvalkitAPIError` (the API returned an error), `AvalkitRateLimitError` (HTTP 429: too many requests, or the month's decisions are used up; a subclass of `AvalkitAPIError`, with `.retry_after` in seconds, or `None` when the limit resets on the 1st), `AvalkitConnectionError` (network problem), `AvalkitValidationError` (bad input, caught before the request is sent).
|
|
102
|
+
|
|
103
|
+
## Status
|
|
104
|
+
|
|
105
|
+
Beta. The API may change before v1.0.
|
|
106
|
+
|
|
107
|
+
## Pricing
|
|
108
|
+
|
|
109
|
+
Free: 1,000 decisions a month and 7 days of audit history. Starter: $49/month for 25,000 decisions and a year of history, upgrade from the [dashboard](https://app.avalkit.com). Compliance: from $999/month, email founders@avalkit.com. Details at [avalkit.com](https://avalkit.com).
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
avalkit/__init__.py
|
|
6
|
+
avalkit/client.py
|
|
7
|
+
avalkit/errors.py
|
|
8
|
+
avalkit/resources.py
|
|
9
|
+
avalkit.egg-info/PKG-INFO
|
|
10
|
+
avalkit.egg-info/SOURCES.txt
|
|
11
|
+
avalkit.egg-info/dependency_links.txt
|
|
12
|
+
avalkit.egg-info/requires.txt
|
|
13
|
+
avalkit.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
requests>=2.28.0
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
avalkit
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "avalkit"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "The control layer for AI agents. Set what they're allowed to do, and prove everything they did."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Erik Bustos" }
|
|
15
|
+
]
|
|
16
|
+
keywords = ["ai", "agents", "ai-agents", "governance", "audit", "audit-log", "spend-controls", "compliance"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 3 - Alpha",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.9",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
26
|
+
"Topic :: Office/Business :: Financial",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"requests>=2.28.0",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://avalkit.com"
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.packages.find]
|
|
36
|
+
where = ["."]
|
|
37
|
+
include = ["avalkit*"]
|
avalkit-0.1.0/setup.cfg
ADDED