tenkyu 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.
Potentially problematic release.
This version of tenkyu might be problematic. Click here for more details.
- tenkyu-0.1.0/LICENSE +21 -0
- tenkyu-0.1.0/PKG-INFO +132 -0
- tenkyu-0.1.0/README.md +113 -0
- tenkyu-0.1.0/pyproject.toml +34 -0
- tenkyu-0.1.0/setup.cfg +4 -0
- tenkyu-0.1.0/tenkyu/__init__.py +8 -0
- tenkyu-0.1.0/tenkyu/client.py +113 -0
- tenkyu-0.1.0/tenkyu/dashboard.html +258 -0
- tenkyu-0.1.0/tenkyu/engine.py +213 -0
- tenkyu-0.1.0/tenkyu/py.typed +0 -0
- tenkyu-0.1.0/tenkyu/server.py +272 -0
- tenkyu-0.1.0/tenkyu/signals.py +104 -0
- tenkyu-0.1.0/tenkyu/store.py +73 -0
- tenkyu-0.1.0/tenkyu.egg-info/PKG-INFO +132 -0
- tenkyu-0.1.0/tenkyu.egg-info/SOURCES.txt +20 -0
- tenkyu-0.1.0/tenkyu.egg-info/dependency_links.txt +1 -0
- tenkyu-0.1.0/tenkyu.egg-info/entry_points.txt +2 -0
- tenkyu-0.1.0/tenkyu.egg-info/top_level.txt +1 -0
- tenkyu-0.1.0/tests/test_client.py +57 -0
- tenkyu-0.1.0/tests/test_engine.py +134 -0
- tenkyu-0.1.0/tests/test_server.py +161 -0
- tenkyu-0.1.0/tests/test_signals.py +44 -0
tenkyu-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tenkyu contributors
|
|
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.
|
tenkyu-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tenkyu
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Stop credit farming in AI apps: link fake accounts to one person and give them one free budget.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://tenkyu.dev
|
|
7
|
+
Project-URL: Source, https://github.com/oriazuti100-a11y/tenkyu
|
|
8
|
+
Project-URL: Changelog, https://github.com/oriazuti100-a11y/tenkyu/blob/main/CHANGELOG.md
|
|
9
|
+
Keywords: fraud,abuse,free tier,multi-accounting,ai,llm,security
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Topic :: Security
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# Tenkyu
|
|
21
|
+
|
|
22
|
+
**Stop credit farming in AI apps.** One person making forty free accounts gets one free budget, not forty.
|
|
23
|
+
|
|
24
|
+
Tenkyu scores every signup, links accounts that share an inbox or a device into one *cluster* (one person), gives each cluster a single free budget, and shows you the dollars it saved. Zero dependencies. Fails open, so it never breaks your signup.
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
pip install tenkyu # Python 3.10+
|
|
28
|
+
npm install tenkyu # Node 18+, Deno, Bun
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Quickstart (Python)
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from tenkyu import Tenkyu, BudgetExceeded
|
|
35
|
+
|
|
36
|
+
tk = Tenkyu() # local mode: open-source engine on tenkyu.db
|
|
37
|
+
# tk = Tenkyu(api_key="tk_live_...", base_url="https://your-tenkyu-server") # hosted mode
|
|
38
|
+
|
|
39
|
+
# 1. At signup
|
|
40
|
+
risk = tk.check_signup(user_id, email=email, ip=ip, device_id=device_id)
|
|
41
|
+
if risk.action == "block":
|
|
42
|
+
return deny(risk.reasons)
|
|
43
|
+
if risk.action == "challenge":
|
|
44
|
+
return ask_for_phone_check()
|
|
45
|
+
|
|
46
|
+
# 2. Around every model call on the free tier
|
|
47
|
+
try:
|
|
48
|
+
reply = tk.meter(user_id, client.chat.completions.create,
|
|
49
|
+
model=model, messages=messages,
|
|
50
|
+
estimate_usd=0.01, # checked before the call
|
|
51
|
+
cost_of=lambda r: r.usage.total_tokens * PRICE_PER_TOKEN) # recorded after
|
|
52
|
+
except BudgetExceeded:
|
|
53
|
+
return upgrade_prompt()
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`paid=True` on `meter()` or `guard()` skips the free budget for paying users. `tk.allow(user_id)` trusts a user after a false flag.
|
|
57
|
+
|
|
58
|
+
## Quickstart (JavaScript)
|
|
59
|
+
|
|
60
|
+
```js
|
|
61
|
+
import { Tenkyu, BudgetExceeded } from "tenkyu";
|
|
62
|
+
const tk = new Tenkyu({ apiKey: process.env.TENKYU_API_KEY, baseUrl: process.env.TENKYU_URL });
|
|
63
|
+
|
|
64
|
+
const risk = await tk.checkSignup({ userId, email, ip, deviceId });
|
|
65
|
+
const reply = await tk.meter(userId, () => client.chat.completions.create(req), { estimateUsd: 0.01 });
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The JS client talks to a Tenkyu server (hosted mode only).
|
|
69
|
+
|
|
70
|
+
## What it checks
|
|
71
|
+
|
|
72
|
+
| Signal | Score |
|
|
73
|
+
|---|---|
|
|
74
|
+
| Disposable inbox (seed list, extendable) | +45 |
|
|
75
|
+
| Datacenter, VPS or Tor IP (seed list, extendable) | +25 |
|
|
76
|
+
| Inbox alias trick (`+tag`, extra Gmail dots) | +10 |
|
|
77
|
+
| Signup burst: 5+ signups from one /24 within 10 minutes | +20 |
|
|
78
|
+
| Linked to 1 other account | +15 |
|
|
79
|
+
| Linked to 2+ other accounts | +30 |
|
|
80
|
+
|
|
81
|
+
Score 70+ → `block`. 40–69 → `challenge`. Below 40 → `allow`. Accounts link when their normalized inbox (Gmail dots and `+tags` removed, `googlemail.com` → `gmail.com`) or their device ID match. A new account that matches two clusters merges them.
|
|
82
|
+
|
|
83
|
+
Load bigger lists at startup:
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from tenkyu import signals
|
|
87
|
+
signals.add_disposable_domains(open("disposable_domains.txt").read().split())
|
|
88
|
+
signals.add_datacenter_ranges(["203.0.113.0/24"])
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Run the server and dashboard
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
python -m tenkyu.server --demo # http://localhost:8787, demo key: tk_demo_public
|
|
95
|
+
python -m tenkyu.server new-project "My app" # prints an API key
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Environment: `PORT` (8787), `TENKYU_DB` (tenkyu.db), `TENKYU_ADMIN_TOKEN` (enables `POST /v1/projects`), `TENKYU_OPEN_SIGNUP=1` (lets anyone create a project from the dashboard or website, 3 per IP per hour), `TENKYU_TRUST_PROXY=1` (behind Fly, Cloudflare or another proxy), `TENKYU_DEMO=1`.
|
|
99
|
+
|
|
100
|
+
| Endpoint | Body | Returns |
|
|
101
|
+
|---|---|---|
|
|
102
|
+
| `POST /v1/signups/check` | `user_id, email, ip, device_id?, user_agent?` | `score, action, reasons, cluster_id, cluster_size` |
|
|
103
|
+
| `POST /v1/usage/guard` | `user_id, estimate_usd, paid?` | `allowed` |
|
|
104
|
+
| `POST /v1/usage/record` | `user_id, cost_usd` | `ok` |
|
|
105
|
+
| `POST /v1/users/allow` | `user_id` | `ok` |
|
|
106
|
+
| `GET /v1/stats` | | accounts, clusters, flagged, spend, `saved_usd`, `free_credits_protected_usd` |
|
|
107
|
+
| `GET /v1/signups?limit=50` | | recent signups |
|
|
108
|
+
| `POST /v1/projects` | `name, free_budget_usd?` + `X-Admin-Token` | `api_key` (shown once) |
|
|
109
|
+
| `POST /v1/projects/self-serve` | `name, email` (no key; needs `TENKYU_OPEN_SIGNUP=1`) | `api_key` (shown once) |
|
|
110
|
+
|
|
111
|
+
All `/v1` calls need `Authorization: Bearer <api key>`. Keys are stored as SHA-256 hashes only.
|
|
112
|
+
|
|
113
|
+
**How "$ saved" is counted:** the estimated cost of every model call Tenkyu refused. You set the estimate, so you can check it against your OpenAI or Anthropic invoice. "Free credits protected" is the free budget not handed out to duplicate and blocked accounts.
|
|
114
|
+
|
|
115
|
+
## Deploy
|
|
116
|
+
|
|
117
|
+
`Dockerfile` and `fly.toml` included; step-by-step in **SETUP.md**. SQLite needs a persistent disk mounted at `/data`; without one, data resets on every redeploy.
|
|
118
|
+
|
|
119
|
+
## Releasing
|
|
120
|
+
|
|
121
|
+
Push a tag like `v0.1.1`. GitHub Actions runs the tests, then publishes to PyPI (trusted publishing) and npm.
|
|
122
|
+
|
|
123
|
+
## Tests
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
python -m unittest # 36 tests
|
|
127
|
+
node --test js/test.mjs # 3 tests, starts a local server
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## License
|
|
131
|
+
|
|
132
|
+
MIT
|
tenkyu-0.1.0/README.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# Tenkyu
|
|
2
|
+
|
|
3
|
+
**Stop credit farming in AI apps.** One person making forty free accounts gets one free budget, not forty.
|
|
4
|
+
|
|
5
|
+
Tenkyu scores every signup, links accounts that share an inbox or a device into one *cluster* (one person), gives each cluster a single free budget, and shows you the dollars it saved. Zero dependencies. Fails open, so it never breaks your signup.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
pip install tenkyu # Python 3.10+
|
|
9
|
+
npm install tenkyu # Node 18+, Deno, Bun
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Quickstart (Python)
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from tenkyu import Tenkyu, BudgetExceeded
|
|
16
|
+
|
|
17
|
+
tk = Tenkyu() # local mode: open-source engine on tenkyu.db
|
|
18
|
+
# tk = Tenkyu(api_key="tk_live_...", base_url="https://your-tenkyu-server") # hosted mode
|
|
19
|
+
|
|
20
|
+
# 1. At signup
|
|
21
|
+
risk = tk.check_signup(user_id, email=email, ip=ip, device_id=device_id)
|
|
22
|
+
if risk.action == "block":
|
|
23
|
+
return deny(risk.reasons)
|
|
24
|
+
if risk.action == "challenge":
|
|
25
|
+
return ask_for_phone_check()
|
|
26
|
+
|
|
27
|
+
# 2. Around every model call on the free tier
|
|
28
|
+
try:
|
|
29
|
+
reply = tk.meter(user_id, client.chat.completions.create,
|
|
30
|
+
model=model, messages=messages,
|
|
31
|
+
estimate_usd=0.01, # checked before the call
|
|
32
|
+
cost_of=lambda r: r.usage.total_tokens * PRICE_PER_TOKEN) # recorded after
|
|
33
|
+
except BudgetExceeded:
|
|
34
|
+
return upgrade_prompt()
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`paid=True` on `meter()` or `guard()` skips the free budget for paying users. `tk.allow(user_id)` trusts a user after a false flag.
|
|
38
|
+
|
|
39
|
+
## Quickstart (JavaScript)
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
import { Tenkyu, BudgetExceeded } from "tenkyu";
|
|
43
|
+
const tk = new Tenkyu({ apiKey: process.env.TENKYU_API_KEY, baseUrl: process.env.TENKYU_URL });
|
|
44
|
+
|
|
45
|
+
const risk = await tk.checkSignup({ userId, email, ip, deviceId });
|
|
46
|
+
const reply = await tk.meter(userId, () => client.chat.completions.create(req), { estimateUsd: 0.01 });
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The JS client talks to a Tenkyu server (hosted mode only).
|
|
50
|
+
|
|
51
|
+
## What it checks
|
|
52
|
+
|
|
53
|
+
| Signal | Score |
|
|
54
|
+
|---|---|
|
|
55
|
+
| Disposable inbox (seed list, extendable) | +45 |
|
|
56
|
+
| Datacenter, VPS or Tor IP (seed list, extendable) | +25 |
|
|
57
|
+
| Inbox alias trick (`+tag`, extra Gmail dots) | +10 |
|
|
58
|
+
| Signup burst: 5+ signups from one /24 within 10 minutes | +20 |
|
|
59
|
+
| Linked to 1 other account | +15 |
|
|
60
|
+
| Linked to 2+ other accounts | +30 |
|
|
61
|
+
|
|
62
|
+
Score 70+ → `block`. 40–69 → `challenge`. Below 40 → `allow`. Accounts link when their normalized inbox (Gmail dots and `+tags` removed, `googlemail.com` → `gmail.com`) or their device ID match. A new account that matches two clusters merges them.
|
|
63
|
+
|
|
64
|
+
Load bigger lists at startup:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from tenkyu import signals
|
|
68
|
+
signals.add_disposable_domains(open("disposable_domains.txt").read().split())
|
|
69
|
+
signals.add_datacenter_ranges(["203.0.113.0/24"])
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Run the server and dashboard
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
python -m tenkyu.server --demo # http://localhost:8787, demo key: tk_demo_public
|
|
76
|
+
python -m tenkyu.server new-project "My app" # prints an API key
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Environment: `PORT` (8787), `TENKYU_DB` (tenkyu.db), `TENKYU_ADMIN_TOKEN` (enables `POST /v1/projects`), `TENKYU_OPEN_SIGNUP=1` (lets anyone create a project from the dashboard or website, 3 per IP per hour), `TENKYU_TRUST_PROXY=1` (behind Fly, Cloudflare or another proxy), `TENKYU_DEMO=1`.
|
|
80
|
+
|
|
81
|
+
| Endpoint | Body | Returns |
|
|
82
|
+
|---|---|---|
|
|
83
|
+
| `POST /v1/signups/check` | `user_id, email, ip, device_id?, user_agent?` | `score, action, reasons, cluster_id, cluster_size` |
|
|
84
|
+
| `POST /v1/usage/guard` | `user_id, estimate_usd, paid?` | `allowed` |
|
|
85
|
+
| `POST /v1/usage/record` | `user_id, cost_usd` | `ok` |
|
|
86
|
+
| `POST /v1/users/allow` | `user_id` | `ok` |
|
|
87
|
+
| `GET /v1/stats` | | accounts, clusters, flagged, spend, `saved_usd`, `free_credits_protected_usd` |
|
|
88
|
+
| `GET /v1/signups?limit=50` | | recent signups |
|
|
89
|
+
| `POST /v1/projects` | `name, free_budget_usd?` + `X-Admin-Token` | `api_key` (shown once) |
|
|
90
|
+
| `POST /v1/projects/self-serve` | `name, email` (no key; needs `TENKYU_OPEN_SIGNUP=1`) | `api_key` (shown once) |
|
|
91
|
+
|
|
92
|
+
All `/v1` calls need `Authorization: Bearer <api key>`. Keys are stored as SHA-256 hashes only.
|
|
93
|
+
|
|
94
|
+
**How "$ saved" is counted:** the estimated cost of every model call Tenkyu refused. You set the estimate, so you can check it against your OpenAI or Anthropic invoice. "Free credits protected" is the free budget not handed out to duplicate and blocked accounts.
|
|
95
|
+
|
|
96
|
+
## Deploy
|
|
97
|
+
|
|
98
|
+
`Dockerfile` and `fly.toml` included; step-by-step in **SETUP.md**. SQLite needs a persistent disk mounted at `/data`; without one, data resets on every redeploy.
|
|
99
|
+
|
|
100
|
+
## Releasing
|
|
101
|
+
|
|
102
|
+
Push a tag like `v0.1.1`. GitHub Actions runs the tests, then publishes to PyPI (trusted publishing) and npm.
|
|
103
|
+
|
|
104
|
+
## Tests
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
python -m unittest # 36 tests
|
|
108
|
+
node --test js/test.mjs # 3 tests, starts a local server
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tenkyu"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Stop credit farming in AI apps: link fake accounts to one person and give them one free budget."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["fraud", "abuse", "free tier", "multi-accounting", "ai", "llm", "security"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Topic :: Security",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://tenkyu.dev"
|
|
24
|
+
Source = "https://github.com/oriazuti100-a11y/tenkyu"
|
|
25
|
+
Changelog = "https://github.com/oriazuti100-a11y/tenkyu/blob/main/CHANGELOG.md"
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
tenkyu-server = "tenkyu.server:main"
|
|
29
|
+
|
|
30
|
+
[tool.setuptools]
|
|
31
|
+
packages = ["tenkyu"]
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.package-data]
|
|
34
|
+
tenkyu = ["dashboard.html", "py.typed"]
|
tenkyu-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Tenkyu: stop credit farming in AI apps."""
|
|
2
|
+
from .client import BudgetExceeded, Tenkyu
|
|
3
|
+
from .engine import Engine, Risk
|
|
4
|
+
from .signals import normalize_email
|
|
5
|
+
from .store import SQLiteStore
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
__all__ = ["Tenkyu", "BudgetExceeded", "Engine", "Risk", "SQLiteStore", "normalize_email", "__version__"]
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""The SDK customers install.
|
|
2
|
+
|
|
3
|
+
Two modes, same methods:
|
|
4
|
+
* Local (no api_key): runs the open-source engine on a SQLite file. Free, self-hosted.
|
|
5
|
+
* Hosted (api_key): calls a Tenkyu server. Every call fails open: if the server is slow,
|
|
6
|
+
down or rejects the key, signups are allowed and model calls go through.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
|
|
16
|
+
from .engine import Engine, Risk
|
|
17
|
+
from .store import SQLiteStore
|
|
18
|
+
|
|
19
|
+
log = logging.getLogger("tenkyu")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BudgetExceeded(Exception):
|
|
23
|
+
"""Raised by `meter()` when this person has used up their free budget."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, user_id):
|
|
26
|
+
super().__init__(f"free budget used up for user {user_id}")
|
|
27
|
+
self.user_id = user_id
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Tenkyu:
|
|
31
|
+
def __init__(self, api_key: str | None = None, base_url: str | None = None,
|
|
32
|
+
timeout: float = 1.5, db_path: str = "tenkyu.db", free_budget_usd: float = 3.0):
|
|
33
|
+
self.api_key = api_key or os.environ.get("TENKYU_API_KEY")
|
|
34
|
+
self.base_url = (base_url or os.environ.get("TENKYU_URL") or "http://localhost:8787").rstrip("/")
|
|
35
|
+
self.timeout = timeout
|
|
36
|
+
self._engine = None
|
|
37
|
+
if not self.api_key:
|
|
38
|
+
self._engine = Engine(SQLiteStore(db_path), free_budget_usd=free_budget_usd)
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def hosted(self) -> bool:
|
|
42
|
+
return self._engine is None
|
|
43
|
+
|
|
44
|
+
# ---- transport -----------------------------------------------------
|
|
45
|
+
def _call(self, method: str, path: str, body: dict | None = None):
|
|
46
|
+
"""Return parsed JSON, or None when the server can't be reached (caller fails open)."""
|
|
47
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
48
|
+
req = urllib.request.Request(self.base_url + path, data=data, method=method, headers={
|
|
49
|
+
"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json",
|
|
50
|
+
"User-Agent": "tenkyu-python/0.1.0"})
|
|
51
|
+
try:
|
|
52
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
53
|
+
return json.loads(resp.read() or b"{}")
|
|
54
|
+
except urllib.error.HTTPError as e:
|
|
55
|
+
if e.code == 400:
|
|
56
|
+
try:
|
|
57
|
+
msg = json.loads(e.read()).get("error", "bad request")
|
|
58
|
+
except Exception:
|
|
59
|
+
msg = "bad request"
|
|
60
|
+
raise ValueError(msg) from None
|
|
61
|
+
log.warning("tenkyu: server answered %s for %s, failing open", e.code, path)
|
|
62
|
+
except Exception as e: # timeouts, DNS, refused connections, bad JSON
|
|
63
|
+
log.warning("tenkyu: %s unreachable (%s), failing open", path, e.__class__.__name__)
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
# ---- public API ----------------------------------------------------
|
|
67
|
+
def check_signup(self, user_id, email: str, ip: str = "", device_id: str | None = None,
|
|
68
|
+
user_agent: str | None = None) -> Risk:
|
|
69
|
+
if not self.hosted:
|
|
70
|
+
return self._engine.check_signup(user_id, email, ip, device_id, user_agent)
|
|
71
|
+
out = self._call("POST", "/v1/signups/check", {"user_id": str(user_id), "email": email, "ip": ip,
|
|
72
|
+
"device_id": device_id, "user_agent": user_agent})
|
|
73
|
+
if out is None:
|
|
74
|
+
return Risk(score=0, action="allow", reasons=["tenkyu unavailable, failed open"])
|
|
75
|
+
return Risk(**{k: out[k] for k in ("score", "action", "reasons", "cluster_id", "cluster_size") if k in out})
|
|
76
|
+
|
|
77
|
+
def guard(self, user_id, estimate_usd: float = 0.0, paid: bool = False) -> bool:
|
|
78
|
+
if not self.hosted:
|
|
79
|
+
return self._engine.guard(user_id, estimate_usd, paid)
|
|
80
|
+
out = self._call("POST", "/v1/usage/guard", {"user_id": str(user_id), "estimate_usd": estimate_usd, "paid": paid})
|
|
81
|
+
return True if out is None else bool(out.get("allowed", True))
|
|
82
|
+
|
|
83
|
+
def record(self, user_id, cost_usd: float) -> None:
|
|
84
|
+
if not self.hosted:
|
|
85
|
+
return self._engine.record(user_id, cost_usd)
|
|
86
|
+
self._call("POST", "/v1/usage/record", {"user_id": str(user_id), "cost_usd": cost_usd})
|
|
87
|
+
|
|
88
|
+
def allow(self, user_id) -> bool:
|
|
89
|
+
if not self.hosted:
|
|
90
|
+
return self._engine.allow(user_id)
|
|
91
|
+
out = self._call("POST", "/v1/users/allow", {"user_id": str(user_id)})
|
|
92
|
+
return bool(out and out.get("ok"))
|
|
93
|
+
|
|
94
|
+
def stats(self) -> dict:
|
|
95
|
+
if not self.hosted:
|
|
96
|
+
return self._engine.stats()
|
|
97
|
+
return self._call("GET", "/v1/stats") or {}
|
|
98
|
+
|
|
99
|
+
def meter(self, user_id, fn, *args, estimate_usd: float = 0.0, cost_of=None, paid: bool = False, **kwargs):
|
|
100
|
+
"""Run a model call only if this person still has free budget, then record its cost.
|
|
101
|
+
|
|
102
|
+
`cost_of(result) -> float` turns the call's result into dollars. Without it the
|
|
103
|
+
estimate is recorded.
|
|
104
|
+
"""
|
|
105
|
+
if not self.guard(user_id, estimate_usd, paid):
|
|
106
|
+
raise BudgetExceeded(user_id)
|
|
107
|
+
result = fn(*args, **kwargs)
|
|
108
|
+
try:
|
|
109
|
+
cost = cost_of(result) if cost_of else estimate_usd
|
|
110
|
+
self.record(user_id, cost)
|
|
111
|
+
except Exception as e: # recording must never break the customer's app
|
|
112
|
+
log.warning("tenkyu: could not record cost (%s)", e)
|
|
113
|
+
return result
|