LancelotDocs
Python SDK

Send usage

Python SDK

`lancelotwatch` wraps the official OpenAI and Anthropic clients, sync and async. No dependencies. Never raises into your app.

pip install lancelotwatch

Python 3.9 or newer.

Create a client

from lancelotwatch import lancelot

lc = lancelot()  # reads LANCELOT_API_KEY

Create it once and reuse it. Events are batched on a background thread and sent every two seconds, or every 100 events. Pending events are flushed when the process exits.

Wrap OpenAI and Anthropic

from openai import OpenAI
from anthropic import Anthropic

openai = lc.wrap_openai(OpenAI(), customer_id=user.id, feature="chat")
res = openai.chat.completions.create(model="gpt-5-mini", messages=messages)

anthropic = lc.wrap_anthropic(Anthropic(), customer_id=user.id, feature="summarize")
msg = anthropic.messages.create(model="claude-haiku-5-5", max_tokens=500, messages=messages)

AsyncOpenAI and AsyncAnthropic work the same way. Wrap once per request with that request's customer, or once at startup with customer_id=lambda params: ... to read it from the call.

If you already pass user (OpenAI) or metadata={"user_id": ...} (Anthropic), the SDK uses it and you can skip customer_id.

The wrapped client behaves like yours, but isinstance(wrapped, OpenAI) is false.

Streams

stream=True and the .stream() helpers both work. For OpenAI chat streams the SDK sets stream_options={"include_usage": True} for you.

Report usage yourself

lc.track(
    "cus_123",       # customer
    "openai",        # provider
    "gpt-5-mini",    # model
    1200,            # input tokens: the whole prompt, cache reads and writes included
    300,             # output tokens
    cached_input_tokens=800,       # optional: cache reads
    cache_write_tokens=0,          # optional: Anthropic 5-minute cache writes
    cache_write_1h_tokens=0,       # optional: Anthropic 1-hour cache writes
    feature="search",              # optional
    idempotency_key=response.id,   # optional: dedupes retries
)

Serverless

Call lc.flush() (or await lc.aflush()) before your function returns.

Letting Lancelot act

lc = lancelot(enable_flags=True)

With enable_flags, the SDK polls each customer's flags every 60 seconds and applies them before each wrapped call. See Fixes and autonomy and Emergency stop and budgets.

Blocked calls raise LancelotBlockedError, with reason set to "throttled", "paused", "runaway" or "budget":

from lancelotwatch import LancelotBlockedError

try:
    reply = openai.chat.completions.create(model="gpt-5", messages=messages)
except LancelotBlockedError as e:
    return "You've hit your plan's limit for now."  # e.customer_id, e.reason

To check without calling a model: lc.get_flags(customer_id) returns CustomerFlags(throttled, paused, throttle_cpm, downgrade), and lc.model_for(customer_id, model) returns the model to call.

Forked workers (gunicorn, multiprocessing) start with fresh counters.

Options

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)

Delivery problems go to on_error. By default that's a logging warning at most once a minute, on the lancelotwatch logger. disabled=True turns off all network activity, for tests.