lancelotwatch 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.
@@ -0,0 +1,4 @@
1
+ __pycache__/
2
+ *.pyc
3
+ dist/
4
+ .venv/
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.5
2
+ Name: lancelotwatch
3
+ Version: 0.1.0
4
+ Summary: Report per-customer AI usage to Lancelot. Wraps the OpenAI and Anthropic Python clients. No dependencies, never raises, never sees prompt content.
5
+ Project-URL: Homepage, https://lancelot.watch
6
+ Author: Lancelot
7
+ License-Expression: MIT
8
+ Keywords: ai,anthropic,cost,llm,margin,openai,stripe,usage
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+
17
+ # lancelotwatch
18
+
19
+ Report per-customer AI usage to [Lancelot](https://lancelot.watch) so you can see which customers make you money and which lose it. Wraps the official OpenAI and Anthropic Python clients, sync and async. No dependencies. Never raises into your app. Never sees prompt or completion content, only token counts.
20
+
21
+ ```bash
22
+ pip install lancelotwatch
23
+ ```
24
+
25
+ Python 3.9 or newer.
26
+
27
+ ## Wrap your client
28
+
29
+ ```python
30
+ from openai import OpenAI
31
+ from anthropic import Anthropic
32
+ from lancelotwatch import lancelot
33
+
34
+ lc = lancelot() # reads LANCELOT_API_KEY
35
+
36
+ # Per request: bind the client to the customer you are serving.
37
+ openai = lc.wrap_openai(OpenAI(), customer_id=user.id, feature="chat")
38
+ res = openai.chat.completions.create(model="gpt-5-mini", messages=messages)
39
+
40
+ anthropic = lc.wrap_anthropic(Anthropic(), customer_id=user.id, feature="summarize")
41
+ msg = anthropic.messages.create(model="claude-haiku-5-5", max_tokens=500, messages=messages)
42
+ ```
43
+
44
+ `AsyncOpenAI` and `AsyncAnthropic` work the same way. Wrapping is cheap: wrap once per request with that request's customer, or once at startup with `customer_id=lambda params: ...` to read it from the call.
45
+
46
+ Streams work: `stream=True`, and the `.stream()` helpers (`with client.messages.stream(...) as stream:`). For OpenAI chat streams we set `stream_options={"include_usage": True}` for you so the last chunk carries token counts.
47
+
48
+ If you already pass `user` (OpenAI) or `metadata={"user_id": ...}` (Anthropic), you can skip `customer_id` and we use that.
49
+
50
+ The wrapped client is a thin stand-in for yours: every method works as before, but `isinstance(wrapped, OpenAI)` is false.
51
+
52
+ ## Or report usage yourself
53
+
54
+ ```python
55
+ lc.track(
56
+ "cus_123", # customer
57
+ "openai", # provider
58
+ "gpt-5-mini", # model
59
+ 1200, # input tokens: the whole prompt, cache reads and writes included
60
+ 300, # output tokens
61
+ cached_input_tokens=800, # optional: cache reads
62
+ cache_write_tokens=0, # optional: Anthropic 5-minute cache writes
63
+ cache_write_1h_tokens=0, # optional: Anthropic 1-hour cache writes
64
+ feature="search", # optional
65
+ idempotency_key=response.id, # optional, dedupes retries
66
+ )
67
+ ```
68
+
69
+ Events are batched on a background thread and sent every two seconds or every 100 events. In serverless functions, call `lc.flush()` (or `await lc.aflush()`) before returning. Pending events are also flushed when the process exits.
70
+
71
+ ## Letting Lancelot act
72
+
73
+ When Lancelot (or you, from the dashboard) throttles, pauses or switches a customer to a cheaper model, the SDK applies it before each wrapped call:
74
+
75
+ ```python
76
+ lc = lancelot(enable_flags=True) # polls every 60s, fails open
77
+ ```
78
+
79
+ - **Throttle:** the customer gets a set number of AI calls a minute. Calls beyond that raise `LancelotBlockedError` with `reason == "throttled"`, so you can show your own message.
80
+ - **Pause:** every call for that customer raises `LancelotBlockedError` with `reason == "paused"`.
81
+ - **Cheaper model:** if you approved a swap (for example `claude-sonnet-5-5` to `claude-haiku-5-5`), requests for that customer on the expensive model are sent with the cheaper one instead. Nothing else changes.
82
+
83
+ ```python
84
+ from lancelotwatch import LancelotBlockedError
85
+
86
+ try:
87
+ reply = openai.chat.completions.create(model="gpt-5", messages=messages)
88
+ except LancelotBlockedError as e:
89
+ return "You've hit your plan's limit for now." # e.customer_id, e.reason
90
+ ```
91
+
92
+ If Lancelot is unreachable, everything is allowed: an outage on our side never blocks your product. Without `enable_flags`, Lancelot can only suggest these fixes.
93
+
94
+ Or check yourself: `lc.get_flags(customer_id)` returns `CustomerFlags(throttled, paused, throttle_cpm, downgrade)`, and `lc.model_for(customer_id, model)` returns the model to call.
95
+
96
+ ## Emergency stop and budgets
97
+
98
+ With `enable_flags`, the SDK also guards your AI bill locally, inside your app, with no network request on the hot path:
99
+
100
+ - **Emergency stop:** a customer who suddenly makes too many calls (default 600 a minute) or spends too fast (default $50 in 5 minutes) is stopped for a cooldown (default 5 minutes). Calls raise `LancelotBlockedError` with `reason == "runaway"`. Lancelot is told at once.
101
+ - **Budgets:** a customer with an hourly or daily budget is held once they reach it, with `reason == "budget"`, until the period resets.
102
+
103
+ Set the limits in Lancelot under **Agent → Settings → Emergency stop**. To override them in one process, or turn the stop off:
104
+
105
+ ```python
106
+ lc = lancelot(enable_flags=True, breaker={"max_calls_per_minute": 2000})
107
+ quiet = Lancelot(enable_flags=True, breaker=False)
108
+ ```
109
+
110
+ Counts are kept per process, so with many workers the limits are approximate. Lancelot's own detectors catch what one process can't see. Forked workers (gunicorn, multiprocessing) start fresh.
111
+
112
+ ## Customer IDs
113
+
114
+ Use the same ID you store in Stripe customer `metadata.customer_id` (or `metadata.user_id`), or the customer's email. That is how we join your model cost to their revenue.
115
+
116
+ ## Options
117
+
118
+ `Lancelot(api_key=None, *, base_url=None, flush_interval=2.0, max_batch_size=100, max_queue_size=10_000, enable_flags=False, flags_interval=60.0, on_error=None, disabled=False, breaker=None)`
119
+
120
+ Delivery problems go to `on_error` (default: a `logging` warning at most once a minute, logger `lancelotwatch`). `disabled=True` turns off all network activity, for tests.
@@ -0,0 +1,104 @@
1
+ # lancelotwatch
2
+
3
+ Report per-customer AI usage to [Lancelot](https://lancelot.watch) so you can see which customers make you money and which lose it. Wraps the official OpenAI and Anthropic Python clients, sync and async. No dependencies. Never raises into your app. Never sees prompt or completion content, only token counts.
4
+
5
+ ```bash
6
+ pip install lancelotwatch
7
+ ```
8
+
9
+ Python 3.9 or newer.
10
+
11
+ ## Wrap your client
12
+
13
+ ```python
14
+ from openai import OpenAI
15
+ from anthropic import Anthropic
16
+ from lancelotwatch import lancelot
17
+
18
+ lc = lancelot() # reads LANCELOT_API_KEY
19
+
20
+ # Per request: bind the client to the customer you are serving.
21
+ openai = lc.wrap_openai(OpenAI(), customer_id=user.id, feature="chat")
22
+ res = openai.chat.completions.create(model="gpt-5-mini", messages=messages)
23
+
24
+ anthropic = lc.wrap_anthropic(Anthropic(), customer_id=user.id, feature="summarize")
25
+ msg = anthropic.messages.create(model="claude-haiku-5-5", max_tokens=500, messages=messages)
26
+ ```
27
+
28
+ `AsyncOpenAI` and `AsyncAnthropic` work the same way. Wrapping is cheap: wrap once per request with that request's customer, or once at startup with `customer_id=lambda params: ...` to read it from the call.
29
+
30
+ Streams work: `stream=True`, and the `.stream()` helpers (`with client.messages.stream(...) as stream:`). For OpenAI chat streams we set `stream_options={"include_usage": True}` for you so the last chunk carries token counts.
31
+
32
+ If you already pass `user` (OpenAI) or `metadata={"user_id": ...}` (Anthropic), you can skip `customer_id` and we use that.
33
+
34
+ The wrapped client is a thin stand-in for yours: every method works as before, but `isinstance(wrapped, OpenAI)` is false.
35
+
36
+ ## Or report usage yourself
37
+
38
+ ```python
39
+ lc.track(
40
+ "cus_123", # customer
41
+ "openai", # provider
42
+ "gpt-5-mini", # model
43
+ 1200, # input tokens: the whole prompt, cache reads and writes included
44
+ 300, # output tokens
45
+ cached_input_tokens=800, # optional: cache reads
46
+ cache_write_tokens=0, # optional: Anthropic 5-minute cache writes
47
+ cache_write_1h_tokens=0, # optional: Anthropic 1-hour cache writes
48
+ feature="search", # optional
49
+ idempotency_key=response.id, # optional, dedupes retries
50
+ )
51
+ ```
52
+
53
+ Events are batched on a background thread and sent every two seconds or every 100 events. In serverless functions, call `lc.flush()` (or `await lc.aflush()`) before returning. Pending events are also flushed when the process exits.
54
+
55
+ ## Letting Lancelot act
56
+
57
+ When Lancelot (or you, from the dashboard) throttles, pauses or switches a customer to a cheaper model, the SDK applies it before each wrapped call:
58
+
59
+ ```python
60
+ lc = lancelot(enable_flags=True) # polls every 60s, fails open
61
+ ```
62
+
63
+ - **Throttle:** the customer gets a set number of AI calls a minute. Calls beyond that raise `LancelotBlockedError` with `reason == "throttled"`, so you can show your own message.
64
+ - **Pause:** every call for that customer raises `LancelotBlockedError` with `reason == "paused"`.
65
+ - **Cheaper model:** if you approved a swap (for example `claude-sonnet-5-5` to `claude-haiku-5-5`), requests for that customer on the expensive model are sent with the cheaper one instead. Nothing else changes.
66
+
67
+ ```python
68
+ from lancelotwatch import LancelotBlockedError
69
+
70
+ try:
71
+ reply = openai.chat.completions.create(model="gpt-5", messages=messages)
72
+ except LancelotBlockedError as e:
73
+ return "You've hit your plan's limit for now." # e.customer_id, e.reason
74
+ ```
75
+
76
+ If Lancelot is unreachable, everything is allowed: an outage on our side never blocks your product. Without `enable_flags`, Lancelot can only suggest these fixes.
77
+
78
+ Or check yourself: `lc.get_flags(customer_id)` returns `CustomerFlags(throttled, paused, throttle_cpm, downgrade)`, and `lc.model_for(customer_id, model)` returns the model to call.
79
+
80
+ ## Emergency stop and budgets
81
+
82
+ With `enable_flags`, the SDK also guards your AI bill locally, inside your app, with no network request on the hot path:
83
+
84
+ - **Emergency stop:** a customer who suddenly makes too many calls (default 600 a minute) or spends too fast (default $50 in 5 minutes) is stopped for a cooldown (default 5 minutes). Calls raise `LancelotBlockedError` with `reason == "runaway"`. Lancelot is told at once.
85
+ - **Budgets:** a customer with an hourly or daily budget is held once they reach it, with `reason == "budget"`, until the period resets.
86
+
87
+ Set the limits in Lancelot under **Agent → Settings → Emergency stop**. To override them in one process, or turn the stop off:
88
+
89
+ ```python
90
+ lc = lancelot(enable_flags=True, breaker={"max_calls_per_minute": 2000})
91
+ quiet = Lancelot(enable_flags=True, breaker=False)
92
+ ```
93
+
94
+ Counts are kept per process, so with many workers the limits are approximate. Lancelot's own detectors catch what one process can't see. Forked workers (gunicorn, multiprocessing) start fresh.
95
+
96
+ ## Customer IDs
97
+
98
+ Use the same ID you store in Stripe customer `metadata.customer_id` (or `metadata.user_id`), or the customer's email. That is how we join your model cost to their revenue.
99
+
100
+ ## Options
101
+
102
+ `Lancelot(api_key=None, *, base_url=None, flush_interval=2.0, max_batch_size=100, max_queue_size=10_000, enable_flags=False, flags_interval=60.0, on_error=None, disabled=False, breaker=None)`
103
+
104
+ Delivery problems go to `on_error` (default: a `logging` warning at most once a minute, logger `lancelotwatch`). `disabled=True` turns off all network activity, for tests.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "lancelotwatch"
7
+ version = "0.1.0"
8
+ description = "Report per-customer AI usage to Lancelot. Wraps the OpenAI and Anthropic Python clients. No dependencies, never raises, never sees prompt content."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "Lancelot" }]
13
+ keywords = ["openai", "anthropic", "ai", "llm", "cost", "margin", "usage", "stripe"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Typing :: Typed",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://lancelot.watch"
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/lancelotwatch"]
28
+
29
+ [tool.hatch.build.targets.sdist]
30
+ include = ["src/lancelotwatch", "README.md", "pyproject.toml"]
@@ -0,0 +1,51 @@
1
+ """Report per-customer AI usage to Lancelot (https://lancelot.watch).
2
+
3
+ Wraps the official OpenAI and Anthropic Python clients, sync and async. No
4
+ dependencies. Never raises into your app. Never sees prompt or completion
5
+ content, only token counts.
6
+
7
+ from openai import OpenAI
8
+ from lancelotwatch import lancelot
9
+
10
+ lc = lancelot() # reads LANCELOT_API_KEY
11
+ openai = lc.wrap_openai(OpenAI(), customer_id=user.id, feature="chat")
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import threading
17
+ from typing import Any, Optional
18
+
19
+ from ._client import CustomerFlags, Lancelot, LancelotBlockedError
20
+ from ._guard import DEFAULT_BREAKER
21
+ from ._usage import Usage, usage_from_anthropic, usage_from_openai
22
+ from ._version import __version__
23
+ from ._wrap import wrap_anthropic, wrap_openai
24
+
25
+ __all__ = [
26
+ "Lancelot",
27
+ "LancelotBlockedError",
28
+ "CustomerFlags",
29
+ "DEFAULT_BREAKER",
30
+ "Usage",
31
+ "lancelot",
32
+ "usage_from_anthropic",
33
+ "usage_from_openai",
34
+ "wrap_anthropic",
35
+ "wrap_openai",
36
+ "__version__",
37
+ ]
38
+
39
+ _singleton: Optional[Lancelot] = None
40
+ _singleton_lock = threading.Lock()
41
+
42
+
43
+ def lancelot(**options: Any) -> Lancelot:
44
+ """A shared client for the process, configured from LANCELOT_API_KEY.
45
+ Options apply the first time it's created."""
46
+ global _singleton
47
+ if _singleton is None:
48
+ with _singleton_lock:
49
+ if _singleton is None:
50
+ _singleton = Lancelot(**options)
51
+ return _singleton