linkflint 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- linkflint/__init__.py +69 -0
- linkflint/_context.py +79 -0
- linkflint/_labels.py +30 -0
- linkflint/_patch.py +66 -0
- linkflint/_where.py +45 -0
- linkflint/asgi.py +51 -0
- linkflint/reports.py +94 -0
- linkflint-0.1.0.dist-info/METADATA +48 -0
- linkflint-0.1.0.dist-info/RECORD +11 -0
- linkflint-0.1.0.dist-info/WHEEL +5 -0
- linkflint-0.1.0.dist-info/top_level.txt +1 -0
linkflint/__init__.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Linkflint for Python: send your AI calls through Linkflint, label them automatically, and read what they cost.
|
|
2
|
+
|
|
3
|
+
import linkflint
|
|
4
|
+
linkflint.init() # once, before you create the AI client; reads LINKFLINT_API_KEY and LINKFLINT_BASE_URL
|
|
5
|
+
|
|
6
|
+
with linkflint.track(end_user="u_482", task="page-8841"): # optional: say whose work this is
|
|
7
|
+
client.chat.completions.create(...) # your normal OpenAI code; nothing else changes
|
|
8
|
+
|
|
9
|
+
The calls then go to Linkflint, carry the labels (and the name of the function that made them), and show up by user, task, feature and step in your
|
|
10
|
+
Linkflint project. A web adapter (linkflint.asgi) adds the page. Reports: linkflint.reports. Nothing here can break a call: any problem in the labelling
|
|
11
|
+
leaves the call exactly as it was."""
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from . import _context, _patch, reports
|
|
18
|
+
from ._context import current as current_labels
|
|
19
|
+
from ._context import step, track
|
|
20
|
+
from ._labels import KINDS, clean
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
__all__ = ["init", "shutdown", "track", "step", "current_labels", "reports", "LinkflintError", "KINDS", "__version__"]
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("linkflint")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class LinkflintError(Exception):
|
|
29
|
+
"""A plain-words problem with how Linkflint was set up or called."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def init(api_key: str | None = None, base_url: str | None = None, *, auto_step: bool = True, environment: str | None = None,
|
|
33
|
+
set_provider_env: bool = True, provider_urls: dict | None = None) -> None:
|
|
34
|
+
"""Connects this app to Linkflint. Call it once, before the AI client is created (a client reads its address and key when it is made).
|
|
35
|
+
|
|
36
|
+
api_key your Linkflint gateway key (starts with gwk_). Default: the LINKFLINT_API_KEY setting.
|
|
37
|
+
base_url your Linkflint address, for example https://gateway.example.com. Default: the LINKFLINT_BASE_URL setting.
|
|
38
|
+
auto_step name each call after the function that made it (only the name is sent). Default on.
|
|
39
|
+
environment a label for where this app runs ("production", "staging", "test"), sent on every call.
|
|
40
|
+
set_provider_env point the OpenAI library at Linkflint by setting OPENAI_BASE_URL and OPENAI_API_KEY (default on).
|
|
41
|
+
provider_urls for libraries that need their provider's own address, for example {"anthropic": "https://.../proxy/PROJECT_KEY/claude"}:
|
|
42
|
+
sets ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY (the address is shown on your Providers page).
|
|
43
|
+
"""
|
|
44
|
+
key = (api_key or os.environ.get("LINKFLINT_API_KEY") or "").strip()
|
|
45
|
+
base = (base_url or os.environ.get("LINKFLINT_BASE_URL") or "").strip().rstrip("/")
|
|
46
|
+
if not key.startswith("gwk_"):
|
|
47
|
+
raise LinkflintError("Linkflint needs your gateway key (it starts with gwk_): pass api_key=... or set LINKFLINT_API_KEY.")
|
|
48
|
+
if not base:
|
|
49
|
+
raise LinkflintError("Linkflint needs your Linkflint address: pass base_url=... or set LINKFLINT_BASE_URL.")
|
|
50
|
+
url = httpx.URL(base)
|
|
51
|
+
if url.scheme not in ("http", "https") or not url.host:
|
|
52
|
+
raise LinkflintError("base_url must be a web address such as https://gateway.example.com")
|
|
53
|
+
_patch.install(url.host, url.port, auto_step, clean(environment))
|
|
54
|
+
if set_provider_env:
|
|
55
|
+
os.environ["OPENAI_BASE_URL"] = f"{base}/v1"
|
|
56
|
+
os.environ["OPENAI_API_KEY"] = key
|
|
57
|
+
for provider, address in (provider_urls or {}).items():
|
|
58
|
+
if provider == "anthropic":
|
|
59
|
+
os.environ["ANTHROPIC_BASE_URL"] = str(address).rstrip("/")
|
|
60
|
+
os.environ["ANTHROPIC_API_KEY"] = key
|
|
61
|
+
else:
|
|
62
|
+
raise LinkflintError(f"provider_urls: '{provider}' is not supported yet (supported: anthropic).")
|
|
63
|
+
os.environ.setdefault("LINKFLINT_BASE_URL", base)
|
|
64
|
+
logger.info("linkflint: connected to %s", base)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def shutdown() -> None:
|
|
68
|
+
"""Stops labelling calls (the wrapper around httpx is removed). Mostly for tests."""
|
|
69
|
+
_patch.uninstall()
|
linkflint/_context.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""What is known about the work being done right now, carried with it through awaits and threads started by asyncio (contextvars).
|
|
2
|
+
|
|
3
|
+
`track(...)` puts labels on every Linkflint call made inside it. A web adapter (linkflint.asgi) also registers a function that tells the page (the route
|
|
4
|
+
pattern) and the end user when a call is made, because the route is only known after the framework has routed the request."""
|
|
5
|
+
import functools
|
|
6
|
+
import inspect
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
from contextvars import ContextVar
|
|
9
|
+
|
|
10
|
+
from ._labels import KINDS, clean
|
|
11
|
+
|
|
12
|
+
_explicit: ContextVar = ContextVar("linkflint_labels", default=None)
|
|
13
|
+
_providers: ContextVar = ContextVar("linkflint_providers", default=())
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def current() -> dict:
|
|
17
|
+
"""Every label known now: those set with track() (the innermost wins), then those the web adapter can tell (only for a label not set otherwise).
|
|
18
|
+
Anything that breaks a rule is left out. Never raises."""
|
|
19
|
+
labels = dict(_explicit.get() or {})
|
|
20
|
+
for provider in _providers.get():
|
|
21
|
+
try:
|
|
22
|
+
found = provider()
|
|
23
|
+
except Exception: # noqa: BLE001 -- a customer's lookup (who is logged in) must never break a call
|
|
24
|
+
continue
|
|
25
|
+
for kind, value in (found or {}).items():
|
|
26
|
+
if kind in KINDS and kind not in labels:
|
|
27
|
+
cleaned = clean(value)
|
|
28
|
+
if cleaned:
|
|
29
|
+
labels[kind] = cleaned
|
|
30
|
+
return labels
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@contextmanager
|
|
34
|
+
def providing(provider):
|
|
35
|
+
"""Registers a function returning {"feature": ..., "end_user": ...} for the length of a request (used by the web adapters)."""
|
|
36
|
+
token = _providers.set((*_providers.get(), provider))
|
|
37
|
+
try:
|
|
38
|
+
yield
|
|
39
|
+
finally:
|
|
40
|
+
_providers.reset(token)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class track:
|
|
44
|
+
"""Labels for every Linkflint call made inside: `with linkflint.track(end_user="u_482", task="page-8841"):` or `@linkflint.track(feature="recipe-page")`
|
|
45
|
+
on a function (a normal one or an async one). Nested blocks add to the outer ones; the inner value wins. A label that breaks a rule (an email, too
|
|
46
|
+
long, odd characters) is dropped, the call still goes through."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, **labels):
|
|
49
|
+
unknown = set(labels) - set(KINDS)
|
|
50
|
+
if unknown:
|
|
51
|
+
raise TypeError(f"unknown label(s) {sorted(unknown)}: use {', '.join(KINDS)}")
|
|
52
|
+
self._labels = {kind: cleaned for kind, value in labels.items() if (cleaned := clean(value))}
|
|
53
|
+
self._tokens = []
|
|
54
|
+
|
|
55
|
+
def __enter__(self):
|
|
56
|
+
self._tokens.append(_explicit.set({**(_explicit.get() or {}), **self._labels}))
|
|
57
|
+
return self
|
|
58
|
+
|
|
59
|
+
def __exit__(self, *exc):
|
|
60
|
+
_explicit.reset(self._tokens.pop())
|
|
61
|
+
return False
|
|
62
|
+
|
|
63
|
+
def __call__(self, function):
|
|
64
|
+
if inspect.iscoroutinefunction(function):
|
|
65
|
+
@functools.wraps(function)
|
|
66
|
+
async def wrapped(*args, **kwargs):
|
|
67
|
+
with track(**self._labels):
|
|
68
|
+
return await function(*args, **kwargs)
|
|
69
|
+
else:
|
|
70
|
+
@functools.wraps(function)
|
|
71
|
+
def wrapped(*args, **kwargs):
|
|
72
|
+
with track(**self._labels):
|
|
73
|
+
return function(*args, **kwargs)
|
|
74
|
+
return wrapped
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def step(name):
|
|
78
|
+
"""Marks one part of the work: `with linkflint.step("write-intro"):`. Use it when one function holds two parts, since the function's own name is used otherwise."""
|
|
79
|
+
return track(step=name)
|
linkflint/_labels.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""The labels a Linkflint call can carry, and the rules for them. The same rules as the server's (app/usage_labels.py): an ID, never a name or an email.
|
|
2
|
+
A label that breaks a rule is dropped here (the server would drop it too), so a mistake never reaches the network."""
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
KINDS = ("end_user", "task", "feature", "environment", "session", "step", "plan")
|
|
6
|
+
HEADERS = {
|
|
7
|
+
"end_user": "X-Linkflint-End-User", "task": "X-Linkflint-Task", "feature": "X-Linkflint-Feature",
|
|
8
|
+
"environment": "X-Linkflint-Environment", "session": "X-Linkflint-Session", "step": "X-Linkflint-Step", "plan": "X-Linkflint-Plan",
|
|
9
|
+
}
|
|
10
|
+
MAX_LENGTH = 100
|
|
11
|
+
_ALLOWED = re.compile(r"^[A-Za-z0-9_.:\-/#+=]+$")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def clean(value):
|
|
15
|
+
"""The label to send, or None when it is empty or breaks a rule (an email, longer than 100 characters, characters outside letters, digits and . _ : - / # + =)."""
|
|
16
|
+
if value is None:
|
|
17
|
+
return None
|
|
18
|
+
text = str(value).strip()
|
|
19
|
+
if not text or "@" in text or len(text) > MAX_LENGTH or not _ALLOWED.match(text):
|
|
20
|
+
return None
|
|
21
|
+
return text
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def route_to_label(pattern) -> str | None:
|
|
25
|
+
"""A route pattern as a label: /recipe/{recipe_id} and /recipe/<int:recipe_id> both become /recipe/:recipe_id. Never a real address (no query string, no IDs)."""
|
|
26
|
+
if not pattern:
|
|
27
|
+
return None
|
|
28
|
+
text = re.sub(r"\{([^}:]+)(?::[^}]*)?\}", r":\1", str(pattern))
|
|
29
|
+
text = re.sub(r"<(?:[^>:]+:)?([^>]+)>", r":\1", text)
|
|
30
|
+
return clean(text)
|
linkflint/_patch.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Puts the labels on the calls that go to Linkflint, whichever AI library makes them.
|
|
2
|
+
|
|
3
|
+
The OpenAI, Anthropic and Google libraries all send their requests with httpx, so one small wrapper around httpx's `send` is enough: before a request
|
|
4
|
+
leaves, if it is going to the Linkflint address that was set in init(), the labels known right now are added as X-Linkflint-* headers. A request to ANY other
|
|
5
|
+
address is never touched: no label ever goes to a provider or anyone else. A header the app already set itself is kept. Nothing here can break a call: if
|
|
6
|
+
anything goes wrong while adding labels, the request is sent as it was."""
|
|
7
|
+
import logging
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from . import _context, _where
|
|
12
|
+
from ._labels import HEADERS
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("linkflint")
|
|
15
|
+
|
|
16
|
+
_state = {"host": None, "port": None, "auto_step": True, "environment": None, "installed": False}
|
|
17
|
+
_original = {}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _ours(request) -> bool:
|
|
21
|
+
url = request.url
|
|
22
|
+
host = _state["host"]
|
|
23
|
+
return bool(host) and url.host == host and url.port == _state["port"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _add_labels(request) -> None:
|
|
27
|
+
try:
|
|
28
|
+
if not _ours(request):
|
|
29
|
+
return
|
|
30
|
+
labels = _context.current()
|
|
31
|
+
if _state["environment"] and "environment" not in labels:
|
|
32
|
+
labels["environment"] = _state["environment"]
|
|
33
|
+
if _state["auto_step"] and "step" not in labels:
|
|
34
|
+
name = _where.function_name()
|
|
35
|
+
if name:
|
|
36
|
+
labels["step"] = name
|
|
37
|
+
for kind, value in labels.items():
|
|
38
|
+
header = HEADERS[kind]
|
|
39
|
+
if header not in request.headers:
|
|
40
|
+
request.headers[header] = value
|
|
41
|
+
except Exception: # noqa: BLE001
|
|
42
|
+
logger.debug("linkflint: could not add labels to a call", exc_info=True)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def install(host: str, port, auto_step: bool, environment) -> None:
|
|
46
|
+
_state.update(host=host, port=port, auto_step=auto_step, environment=environment)
|
|
47
|
+
if _state["installed"]:
|
|
48
|
+
return
|
|
49
|
+
_original["sync"], _original["async"] = httpx.Client.send, httpx.AsyncClient.send
|
|
50
|
+
|
|
51
|
+
def send(self, request, *args, **kwargs):
|
|
52
|
+
_add_labels(request)
|
|
53
|
+
return _original["sync"](self, request, *args, **kwargs)
|
|
54
|
+
|
|
55
|
+
async def send_async(self, request, *args, **kwargs):
|
|
56
|
+
_add_labels(request)
|
|
57
|
+
return await _original["async"](self, request, *args, **kwargs)
|
|
58
|
+
|
|
59
|
+
httpx.Client.send, httpx.AsyncClient.send = send, send_async
|
|
60
|
+
_state["installed"] = True
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def uninstall() -> None:
|
|
64
|
+
if _state["installed"]:
|
|
65
|
+
httpx.Client.send, httpx.AsyncClient.send = _original["sync"], _original["async"]
|
|
66
|
+
_state.update(host=None, port=None, auto_step=True, environment=None, installed=False)
|
linkflint/_where.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Which part of the customer's own code is making an AI call: the name of the function. Only the name is used, never code, a file path or a line number.
|
|
2
|
+
|
|
3
|
+
The stack is walked from the call outwards; frames that belong to libraries (site-packages, the standard library, frozen modules, this package) and
|
|
4
|
+
the helper frames Python makes for comprehensions and lambdas are skipped, and the first frame of the customer's own code gives the name
|
|
5
|
+
("write_story", or "Pages.about" for a method). Whether a file is the customer's own is decided once per file and remembered."""
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import sysconfig
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from ._labels import clean
|
|
12
|
+
|
|
13
|
+
_HERE = str(Path(__file__).resolve().parent).lower()
|
|
14
|
+
_LIBRARY_MARKERS = ("site-packages", "dist-packages", "<frozen", "<string>", "<stdin>")
|
|
15
|
+
_STDLIB = tuple(p.lower() for p in {sysconfig.get_paths().get("stdlib", ""), sysconfig.get_paths().get("platstdlib", "")} if p)
|
|
16
|
+
_HELPERS = {"<module>", "<lambda>", "<listcomp>", "<dictcomp>", "<setcomp>", "<genexpr>"}
|
|
17
|
+
_is_user_file: dict = {}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _own_code(filename: str) -> bool:
|
|
21
|
+
known = _is_user_file.get(filename)
|
|
22
|
+
if known is None:
|
|
23
|
+
low = filename.lower().replace("\\", "/")
|
|
24
|
+
raw = filename.lower()
|
|
25
|
+
known = not (
|
|
26
|
+
any(marker in low for marker in _LIBRARY_MARKERS) or raw.startswith(_HERE)
|
|
27
|
+
or any(raw.startswith(root) for root in _STDLIB if "site-packages" not in raw)
|
|
28
|
+
)
|
|
29
|
+
_is_user_file[filename] = known
|
|
30
|
+
return known
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def function_name(skip: int = 0) -> str | None:
|
|
34
|
+
"""The name of the customer's function that is making the call now, or None when the call comes from no function of theirs (a bare script line)."""
|
|
35
|
+
try:
|
|
36
|
+
frame = sys._getframe(skip)
|
|
37
|
+
except ValueError:
|
|
38
|
+
return None
|
|
39
|
+
while frame is not None:
|
|
40
|
+
code = frame.f_code
|
|
41
|
+
if code.co_name not in _HELPERS and _own_code(code.co_filename):
|
|
42
|
+
name = getattr(code, "co_qualname", code.co_name)
|
|
43
|
+
return clean(re.sub(r"<locals>\.?", "", name))
|
|
44
|
+
frame = frame.f_back
|
|
45
|
+
return None
|
linkflint/asgi.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""The page for FastAPI and Starlette: every AI call made while a request is handled is labelled with the page (the route pattern) and, if you say how, the end user.
|
|
2
|
+
|
|
3
|
+
from linkflint.asgi import LinkflintMiddleware
|
|
4
|
+
app.add_middleware(LinkflintMiddleware, end_user=lambda scope: getattr(scope.get("user"), "username", None))
|
|
5
|
+
|
|
6
|
+
The page is the route PATTERN ("/recipe/:recipe_id"), never the real address, so no query string and no ID of a person goes with it. The page and the end user are looked
|
|
7
|
+
up at the moment of the AI call (the route is only known once the framework has routed the request, and the login once your own middleware has run).
|
|
8
|
+
`end_user`, `session` and `plan` are optional functions that get the ASGI scope and return an ID (never a name or an email; one that looks like an email is dropped)."""
|
|
9
|
+
from ._context import providing
|
|
10
|
+
from ._labels import route_to_label
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _pattern(scope) -> str | None:
|
|
14
|
+
route = scope.get("route")
|
|
15
|
+
pattern = getattr(route, "path", None) or getattr(route, "path_format", None)
|
|
16
|
+
if pattern:
|
|
17
|
+
return pattern
|
|
18
|
+
path = scope.get("path") or "" # a framework that does not tell the route: put the path parameters back as :name
|
|
19
|
+
for name, value in (scope.get("path_params") or {}).items():
|
|
20
|
+
path = path.replace(f"/{value}", f"/:{name}", 1)
|
|
21
|
+
return path if scope.get("path_params") is not None and scope.get("endpoint") else None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LinkflintMiddleware:
|
|
25
|
+
def __init__(self, app, end_user=None, session=None, feature=True, plan=None):
|
|
26
|
+
self.app, self._end_user, self._session, self._feature, self._plan = app, end_user, session, feature, plan
|
|
27
|
+
|
|
28
|
+
async def __call__(self, scope, receive, send):
|
|
29
|
+
if scope["type"] not in ("http", "websocket"):
|
|
30
|
+
await self.app(scope, receive, send)
|
|
31
|
+
return
|
|
32
|
+
|
|
33
|
+
def known() -> dict:
|
|
34
|
+
found = {}
|
|
35
|
+
lookups = {"feature": (lambda: route_to_label(_pattern(scope))) if self._feature else None,
|
|
36
|
+
"end_user": (lambda: self._end_user(scope)) if self._end_user else None,
|
|
37
|
+
"session": (lambda: self._session(scope)) if self._session else None,
|
|
38
|
+
"plan": (lambda: self._plan(scope)) if self._plan else None}
|
|
39
|
+
for kind, lookup in lookups.items():
|
|
40
|
+
if lookup is None:
|
|
41
|
+
continue
|
|
42
|
+
try: # the customer's own lookup (who is logged in) may fail: the others still count, and the call goes on
|
|
43
|
+
value = lookup()
|
|
44
|
+
except Exception: # noqa: BLE001
|
|
45
|
+
continue
|
|
46
|
+
if value:
|
|
47
|
+
found[kind] = value
|
|
48
|
+
return found
|
|
49
|
+
|
|
50
|
+
with providing(known):
|
|
51
|
+
await self.app(scope, receive, send)
|
linkflint/reports.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Read what your calls cost, from your own server: linkflint.reports.totals(task="page-8841"), .summary(by="end_user"), .breakdown(...), .token_for(...).
|
|
2
|
+
|
|
3
|
+
Uses a REPORTS key (starts with gwr_, made on your project's Reports API page; set LINKFLINT_REPORTS_KEY), which can only read reports: it cannot call a provider,
|
|
4
|
+
spend money or see any key. Keep it on your server. To show one of your users their own usage, make a short-lived token for that user with
|
|
5
|
+
token_for("u_482") and hand only the token to their page: it can read that one end user's calls and nothing else."""
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ReportsError(Exception):
|
|
12
|
+
"""Linkflint refused or could not answer; the message is Linkflint's own plain explanation."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, message: str, status_code: int | None = None):
|
|
15
|
+
super().__init__(message)
|
|
16
|
+
self.status_code = status_code
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Reports:
|
|
20
|
+
def __init__(self, key: str | None = None, base_url: str | None = None, client: httpx.Client | None = None, timeout: float = 20.0):
|
|
21
|
+
self.key = (key or os.environ.get("LINKFLINT_REPORTS_KEY") or "").strip()
|
|
22
|
+
self.base_url = (base_url or os.environ.get("LINKFLINT_BASE_URL") or "").strip().rstrip("/")
|
|
23
|
+
if not self.key.startswith(("gwr_", "gwt_")):
|
|
24
|
+
raise ReportsError("Reports need a reports key (starts with gwr_): pass key=... or set LINKFLINT_REPORTS_KEY. A gateway key (gwk_) cannot read reports.")
|
|
25
|
+
if not self.base_url:
|
|
26
|
+
raise ReportsError("Reports need your Linkflint address: pass base_url=... or set LINKFLINT_BASE_URL.")
|
|
27
|
+
self._client = client or httpx.Client(timeout=timeout)
|
|
28
|
+
|
|
29
|
+
def _call(self, method: str, path: str, params: dict | None = None, json: dict | None = None) -> dict:
|
|
30
|
+
response = self._client.request(
|
|
31
|
+
method, f"{self.base_url}/v1/reports{path}", params={k: v for k, v in (params or {}).items() if v not in (None, "")},
|
|
32
|
+
json=json, headers={"Authorization": f"Bearer {self.key}"})
|
|
33
|
+
if response.status_code >= 400:
|
|
34
|
+
try:
|
|
35
|
+
detail = response.json()["detail"]
|
|
36
|
+
message = detail["error"]["message"] if isinstance(detail, dict) else str(detail)
|
|
37
|
+
except Exception: # noqa: BLE001
|
|
38
|
+
message = f"Linkflint answered {response.status_code}"
|
|
39
|
+
raise ReportsError(message, response.status_code)
|
|
40
|
+
return response.json()
|
|
41
|
+
|
|
42
|
+
def totals(self, **filters) -> dict:
|
|
43
|
+
"""{"calls", "live_sessions", "cost_usd", "calls_without_price"} for everything matching the filters: task=, end_user=, feature=, environment=,
|
|
44
|
+
session=, step=, plan=, model=, from_="2026-11-01", to="2026-11-30"."""
|
|
45
|
+
return self._call("GET", "/totals", _filters(filters))
|
|
46
|
+
|
|
47
|
+
def summary(self, by: str = "end_user", **filters) -> dict:
|
|
48
|
+
"""One line per label of the kind `by` (end_user, task, feature, environment, session, step, plan), biggest cost first."""
|
|
49
|
+
return self._call("GET", "/summary", {"by": by, **_filters(filters)})
|
|
50
|
+
|
|
51
|
+
def daily(self, **filters) -> dict:
|
|
52
|
+
return self._call("GET", "/daily", _filters(filters))
|
|
53
|
+
|
|
54
|
+
def calls(self, page: int = 1, page_size: int = 50, **filters) -> dict:
|
|
55
|
+
return self._call("GET", "/calls", {"page": page, "page_size": page_size, **_filters(filters)})
|
|
56
|
+
|
|
57
|
+
def call(self, call_id: str) -> dict:
|
|
58
|
+
"""One call in detail; its id is the X-Linkflint-Request-Id header of the response it made."""
|
|
59
|
+
return self._call("GET", f"/calls/{call_id}")
|
|
60
|
+
|
|
61
|
+
def breakdown(self, value: str, parent: str = "feature", child: str = "step", **filters) -> dict:
|
|
62
|
+
"""What is inside one page: breakdown("/about") splits everything with that feature by step, with the models, calls and cost of each part."""
|
|
63
|
+
return self._call("GET", "/breakdown", {"parent": parent, "value": value, "child": child, **_filters(filters)})
|
|
64
|
+
|
|
65
|
+
def token_for(self, end_user: str, ttl_seconds: int = 600, hide_cost: bool = False) -> dict:
|
|
66
|
+
"""A short-lived token for ONE end user (10 minutes by default, 1 hour at most): {"token", "end_user", "expires_at"}. Hand only the token to that
|
|
67
|
+
user's page; it can read that user's calls and nothing else. hide_cost=True removes every cost (if you charge your users more than you pay)."""
|
|
68
|
+
return self._call("POST", "/tokens", json={"end_user": end_user, "ttl_seconds": ttl_seconds, "hide_cost": hide_cost})
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _filters(filters: dict) -> dict:
|
|
72
|
+
out = dict(filters)
|
|
73
|
+
if "from_" in out:
|
|
74
|
+
out["from"] = out.pop("from_")
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
_default: Reports | None = None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _reports() -> Reports:
|
|
82
|
+
global _default
|
|
83
|
+
if _default is None:
|
|
84
|
+
_default = Reports()
|
|
85
|
+
return _default
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def totals(**filters): return _reports().totals(**filters)
|
|
89
|
+
def summary(by="end_user", **filters): return _reports().summary(by, **filters)
|
|
90
|
+
def daily(**filters): return _reports().daily(**filters)
|
|
91
|
+
def calls(page=1, page_size=50, **filters): return _reports().calls(page, page_size, **filters)
|
|
92
|
+
def call(call_id): return _reports().call(call_id)
|
|
93
|
+
def breakdown(value, parent="feature", child="step", **filters): return _reports().breakdown(value, parent, child, **filters)
|
|
94
|
+
def token_for(end_user, ttl_seconds=600, hide_cost=False): return _reports().token_for(end_user, ttl_seconds, hide_cost)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: linkflint
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Send AI calls through Linkflint, label them automatically (end user, page, function), and read what they cost.
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: httpx>=0.24
|
|
8
|
+
|
|
9
|
+
# linkflint (Python)
|
|
10
|
+
|
|
11
|
+
Send your AI calls through Linkflint, label them automatically, and read what they cost.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import linkflint
|
|
15
|
+
linkflint.init() # once, before you create the AI client. Reads LINKFLINT_API_KEY (gwk_...) and LINKFLINT_BASE_URL.
|
|
16
|
+
|
|
17
|
+
from openai import OpenAI
|
|
18
|
+
client = OpenAI() # your normal code. It now talks to Linkflint.
|
|
19
|
+
|
|
20
|
+
with linkflint.track(end_user="u_482", task="page-8841"): # optional: whose work is this?
|
|
21
|
+
client.chat.completions.create(model="gpt-5", messages=[...])
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Every call carries the labels, and the name of the function that made it (only the name), so Linkflint can show cost by end user, task, feature and step.
|
|
25
|
+
A label is an ID, never a name or an email: one that looks like an email, or is longer than 100 characters, is dropped and the call still goes through.
|
|
26
|
+
|
|
27
|
+
**The page, automatically (FastAPI / Starlette):**
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from linkflint.asgi import LinkflintMiddleware
|
|
31
|
+
app.add_middleware(LinkflintMiddleware, end_user=lambda scope: getattr(scope.get("user"), "username", None), plan=lambda scope: getattr(scope.get("user"), "plan", None))
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Every AI call made while a request is handled is labelled with the route pattern (`/recipe/:recipe_id`, never the real address).
|
|
35
|
+
|
|
36
|
+
**Two parts in one function:** `with linkflint.step("write-intro"):` around each part (otherwise the function's name is used).
|
|
37
|
+
|
|
38
|
+
**Reports (from your server, with a reports key `gwr_...` from your project's Reports API page):**
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
linkflint.reports.totals(task="page-8841") # what did that page cost?
|
|
42
|
+
linkflint.reports.summary(by="end_user") # one line per user
|
|
43
|
+
linkflint.reports.breakdown("/about") # the parts of a page, with models and cost
|
|
44
|
+
linkflint.reports.token_for("u_482") # a 10-minute token for ONE user's own page
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
What it never does: it never sends a label to any address except your Linkflint address, never sends code, file paths or line numbers, and never raises into
|
|
48
|
+
your code because of a labelling problem. Labels follow the work through `await` and `asyncio.to_thread`; a plain `threading.Thread` does not inherit them.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
linkflint/__init__.py,sha256=3n5zZPDb7c2hivcJ7R9yLJVJqkapalj6UJmAO6nuhSY,3898
|
|
2
|
+
linkflint/_context.py,sha256=PLi8niT30Bl_vCtg2S-RCW6XU8QBnABs6PaTY2f6-L0,3355
|
|
3
|
+
linkflint/_labels.py,sha256=vFO0v6IfEHx1GKqTTZ9BPsLoYw1PYF7L8_f3d3yuiRs,1464
|
|
4
|
+
linkflint/_patch.py,sha256=U0aTt_ftqLcnJBu_NoRWd9M6-5boxGLOHmhafoUdFuk,2711
|
|
5
|
+
linkflint/_where.py,sha256=rSmLvP1o7p695pJ2b-_RJNljmpNpZfBYRqekxExmLiY,2081
|
|
6
|
+
linkflint/asgi.py,sha256=LspNw2PIWOnZ0MKtEDRS2BnTIRRo52RANAgM-d2mvuo,2807
|
|
7
|
+
linkflint/reports.py,sha256=GpNG8RGBshRVKLNqfAX85SCyYe034w0g3Kw5X0UiqrM,5294
|
|
8
|
+
linkflint-0.1.0.dist-info/METADATA,sha256=gN5b1k9i_6Qws_nO61Jyjd7PZaCqXXwSPS0dnjYmlfU,2464
|
|
9
|
+
linkflint-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
linkflint-0.1.0.dist-info/top_level.txt,sha256=AUS4OYQ2jOQmOrs0fVUigX1mmo4nIMdWS4aVxYsjAvc,10
|
|
11
|
+
linkflint-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
linkflint
|