SDKs
Python
Server-side decisions for Django, Flask, FastAPI and workers, plus AI config helpers.
liftcanary decides on your Python server: Django, Flask, FastAPI, Celery workers or scripts. One client serves every request, refreshes the datafile in a background thread and sends events in batches. A decision is a function call of about 1–2 µs, and it gives a user the same variation as the website, app and Node SDKs.
Install#
pip install liftcanaryPython 3.9 or newer. No dependencies: it uses only the standard library.
Usage#
import os
from liftcanary import Client
liftcanary = Client(os.environ["LIFTCANARY_SDK_KEY"])
liftcanary.ready() # at startup; waits up to 3 s for the first datafilefrom .liftcanary_client import liftcanary
def checkout(request):
user = liftcanary.create_user(
str(request.user.id),
{"plan": request.user.plan, "country": request.headers.get("CF-IPCountry")},
)
flow = user.get_variable("new_checkout", "flow", "classic")
order = place_order(request.POST, flow)
user.track("purchase", value=float(order.total))
return JsonResponse(order.as_dict())The user#
| Method | Returns |
|---|---|
is_enabled(flag) | Whether the feature is on for this user. |
get_variable(flag, name, fallback) | The variable's value, or the fallback when the flag or variable is missing or has another type. |
decide(flag) | A Decision: enabled, variation_key, rule_key, in_experiment, reason, variables. |
decide_all() | Decisions for every flag, by key. |
track(event, value=None, properties=None) | Records a goal event. value is summed or averaged by goals (revenue, latency). |
create_user(id, attributes, bucketing_id=None, page=None, active_locations=(), anonymous_id=None) takes the same fields as the other SDKs; anonymous_id (the liftcanary_anon cookie) links a visitor's landing-page visit to the user, see From landing page to app. Attributes are sent with events; page (the full request URL, for location conditions) and active_locations never are. Experiment exposures are logged automatically, once per user, flag and variation; pass send_exposure=False to decide to skip it.
Options#
sdk_keyrequiredstr | The environment's public SDK key (pk_…). |
datafiledict | A datafile to start from, so the first decisions need no download. |
cdn_urlstr | Where datafiles come from. Default https://cdn.liftcanary.com; use your own domain or the API when self-hosting. |
events_urlstr | The collector. Default https://events.liftcanary.com. |
streamingTrue | Live updates: a published change arrives in about a second, in a background thread. False turns it off. |
stream_urlstr | Where live updates connect: <stream_url>/stream/<sdk_key>. Default: cdn_url. |
polling_interval30.0 | Seconds between datafile checks, in case the live connection drops (ETag, so unchanged datafiles cost almost nothing). 0 turns polling off. |
event_flush_interval2.0 | Seconds between event sends. |
event_batch_size200 | Events per request; a full batch is sent at once. |
event_max_queue_size20000 | Events held in memory before the oldest are dropped (counted in client.events.dropped). |
model_pricesdict | Price per 1M tokens per model, for AI configs. |
transportcallable | Replaces the HTTP layer (tests, corporate proxies). Live updates then need stream_transport too, and are off without it. |
stream_transportcallable | Replaces the HTTP layer of live updates: (url, headers, timeout) returns a response with readline() and close(), or raises StreamRefused(status). |
Processes and shutdown#
- Forking servers (gunicorn with
--preload, uWSGI,multiprocessing): background threads don't survive a fork, so the client restarts them in each child automatically. Create the client once at import time. - Exit: remaining events are sent when the process exits normally.
client.close()does it explicitly, and the client is also a context manager (with Client(...) as liftcanary:). - Short jobs and serverless (AWS Lambda, Cloud Functions, cron scripts): call
liftcanary.flush()before returning, because a frozen process sends nothing. - Logs go to the
liftcanarylogger. The library adds no handler, so configure logging to see warnings such as failed downloads.
AI configs#
Test models, prompts and parameters on real users, measured on latency, tokens, cost, errors and feedback. Your code still calls the provider, so any provider works.
from liftcanary import Client, ModelPrice, ai_config, measure_llm, render_prompt, track_feedback
liftcanary = Client(
os.environ["LIFTCANARY_SDK_KEY"],
model_prices={"my-small-model": ModelPrice(input=0.25, output=1.25), "my-large-model": ModelPrice(input=3, output=15)},
)
def answer(request, messages):
user = liftcanary.create_user(str(request.user.id), {"plan": request.user.plan})
cfg = ai_config(user, "support_bot", model="my-small-model", prompt="You are a helpful assistant.")
reply = measure_llm(
user,
cfg,
lambda: llm.chat(model=cfg.model, system=render_prompt(cfg.prompt, language="Turkish"), messages=messages, **cfg.params),
usage=lambda r: {"input_tokens": r.usage.input_tokens, "output_tokens": r.usage.output_tokens},
)
return reply
# When the user rates the answer:
track_feedback(user, cfg, positive=True)With an async client, use await measure_llm_async(user, cfg, lambda: client.chat(...)); a cancelled task (the client went away) is recorded as aborted. For streamed answers, measure_llm_stream and measure_llm_stream_async also record the time to first token, and a stream left early as aborted. track_llm(user, cfg, latency_ms=…, time_to_first_token_ms=…, input_tokens=…, output_tokens=…, cost=…, outcome=…) records a call you measured yourself. The events and goals are the same as in Node; see AI configs and LLM experiments.