Self-hosting
Run the Kaimei API on your own infrastructure, against SQLite on a laptop or Postgres for a team.
The API is a FastAPI service and runs anywhere Python 3.9 does, against SQLite for a laptop or Postgres (Supabase works) for a team. Enterprise plans include a private deployment; the configuration below applies to any installation.
Service 1.13.0 serves the /v1 contract: new fields may appear, and existing fields keep their meaning, apart from four changes in 1.2.0, three of them for safety, and the ones listed for 1.3.0, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.3, 1.8.0, 1.9.0, 1.11.0, 1.12.0 and 1.13.0. See API compatibility. Rate limits, the logging rate, Idempotency-Key answers, held outcomes, sign-in sessions and failed sign-ins are stored in the database, so every process of one deployment shares them. An analysis that was still running when the process stopped is resumed; after three interrupted attempts it fails and can be started again. Every response carries X-Request-Id, a 500 included.
Configuration is through KAIMEI_* environment variables or a .env file in the working directory. The ones that matter most:
| Variable | Default | Meaning |
|---|---|---|
KAIMEI_DATABASE_URL | sqlite:///./kaimei.db | SQLAlchemy URL. Postgres in production. |
KAIMEI_SECRET_KEY | (dev value) | Signs sessions and emailed links, and seals models' endpoint credentials and accounts' two-factor secrets. At least 32 random bytes; always set it, and keep it. Production and staging refuse to start with the development value. To change it, see Changing the secret below. |
KAIMEI_PREVIOUS_SECRET_KEYS | unset | Secrets used before KAIMEI_SECRET_KEY, comma-separated, newest first. Sessions and links they signed stay valid and credentials they sealed stay readable, so the secret can change without signing everyone out. |
KAIMEI_ENV | development | production turns email verification on by default; staging logs and checks the secret as production does and is reported as staging in /health; test turns rate limits and quotas off. |
KAIMEI_LOG_FORMAT | unset | json, one object a line, or text. Unset, JSON in production and staging and text elsewhere. |
KAIMEI_ACCESS_LOG | true | One log line per request, with its route, status, time and workspace. /metrics counts requests either way. |
KAIMEI_SLOW_QUERY_MS | 1000 | A database statement taking this many milliseconds or more is logged, without its parameters, and counted. 0 turns it off. |
KAIMEI_SENTRY_DSN | unset | Send unhandled errors to Sentry. Needs the sentry extra: pip install -e ".[sentry]". |
KAIMEI_METRICS_TOKEN | unset | The bearer token for GET /metrics. Unset, the route answers 404. |
KAIMEI_HEALTH_DB_TIMEOUT_S | 3 | How long GET /health/ready waits for the database before answering 503. |
KAIMEI_PUBLIC_API_URL / KAIMEI_DASHBOARD_URL | localhost | Used for OAuth callbacks, verification and invitation links, CORS, the dashboard pages Stripe returns customers to, and the billing webhook's address, which must be https for Stripe to reach it. |
KAIMEI_ACCESS_TOKEN_TTL_MINUTES | 10080 | How long a session handed out as a bearer token lasts, to scripts and the Python client: seven days. Signing out, or a password change, ends it sooner. |
KAIMEI_SESSION_ACCESS_MINUTES / _SESSION_DAYS / _SESSION_IDLE_DAYS | 15 / 30 / 7 | A browser session's (the console's): how long its access tokens last, how many days it lasts at most, and how many unused. |
KAIMEI_LOGIN_FAILURES_PER_ACCOUNT / KAIMEI_LOGIN_LOCK_MINUTES | 10 / 15 | Wrong passwords, or second-factor codes, for one account within that many minutes before sign-in refuses it with 429 too_many_failures until they pass. KAIMEI_REAUTH_MINUTES (10) is how recent a sign-in must be to set a first password or start two-factor setup without one. |
KAIMEI_EDGE_SECRET | unset | A secret your proxy adds to every request it forwards, as the X-Kaimei-Edge header (with Cloudflare, a Transform Rule). Set, CF-Connecting-IP is believed only alongside it, and a request without it, sent to the server around the proxy, is 403 direct_access_refused, apart from /health and /health/ready. Unset, anyone who reaches the server directly can claim any address. |
KAIMEI_ALLOW_SIGNUP | true | Set false to stop self-serve sign-up, and create accounts with kaimei-api create-user <email> <password> --accept-terms, once the person has agreed to the Terms of Use. An invitation does not open sign-up: the person invited needs an account first. |
KAIMEI_MAX_REFERENCE_ROWS | 5000 | Reference rows kept per model. |
KAIMEI_EXPLANATION_EVAL_BUDGET | 60000 | Soft ceiling on model evaluations per explanation. |
KAIMEI_IMAGE_EXPLAIN_SECONDS | 40 | Time budget image explanations plan their grid to fit, and Shapley sampling over the parts of a text or series its permutations. |
KAIMEI_STRUCTURE_RUN_SECONDS | 60 | How long one pass of a general model graph may take. |
KAIMEI_REQUEST_RUN_SECONDS | 90 | How long all the passes of one request may take together, counted from the first. Keep it under your proxy's own timeout (Cloudflare's is 100 seconds). |
KAIMEI_ANALYSIS_RUN_SECONDS | 900 | How long all the passes of one background analysis may take. |
KAIMEI_GENERATION_SECONDS | 45 | How long the whole loop of POST …/generate may take. |
KAIMEI_MAX_FOREST_CACHE_BYTES | 2147483648 | What compiled forests and graphs kept in memory may hold between them, their loaded constants and parameters counted. |
KAIMEI_AGENT_WAITS / _PER_ORGANIZATION | 16 / 6 | Requests one process lets wait for agents' answers, in all and for one organization; past either, 429 agent_busy. |
KAIMEI_AGENT_ROUTE_THREADS | 8 | Threads agents' own routes run on, so waiting callers never keep an answer out. |
KAIMEI_AGENT_SESSIONS_PER_MODEL / KAIMEI_AGENT_POLLS_PER_MODEL | 32 / 32 | Agents one model may have connected, and requests for work it may have waiting. |
KAIMEI_MAX_RUN_ACTIVATION_BYTES / _PARAMETER_BYTES | 1073741824 | What one row of a model run here may hold, and its tensors. A model past them is drawn, not run. |
KAIMEI_MAX_TENSOR_BYTES | 536870912 | Largest single binary tensor upload, compressed. |
KAIMEI_REMOTE_INFERENCE_TIMEOUT_S | 30 | Default timeout for remote endpoints. |
KAIMEI_BEHIND_CLOUDFLARE / KAIMEI_TRUST_PROXY | false | Read the client IP from CF-Connecting-IP / X-Forwarded-For for rate limits. |
KAIMEI_TURNSTILE_* , KAIMEI_SMTP_*, KAIMEI_GOOGLE_* , KAIMEI_GITHUB_* | unset | Bot protection on sign-up; verification, invitation and join-confirmation email (without SMTP an invitation link is returned to whoever sent it, to pass on, and joining by email domain can neither be turned on nor used, since the API never returns those links: without SMTP they only reach the server log); OAuth sign-in. |
KAIMEI_TERMS_VERSION | 2026-11-20 | The effective date of the Terms of Use that every new account records as agreed. Every way of making an account requires that agreement. Change it when the Terms change. |
KAIMEI_STRIPE_SECRET_KEY / KAIMEI_STRIPE_WEBHOOK_SECRET | unset | Paid plans through Stripe. Without a secret key the plans are listed and buying one is 503 billing_not_configured. Use a test-mode key (sk_test_…) anywhere but production. |
KAIMEI_STRIPE_PRICE_STANDARD / _PRICE_TEAM / _PORTAL_CONFIGURATION | unset | Only for prices or a portal configuration that kaimei-api billing setup did not make; it finds its own. |
KAIMEI_STRIPE_AUTOMATIC_TAX / KAIMEI_STRIPE_PROMOTION_CODES | false | Sales tax and VAT worked out by Stripe Tax at checkout, and a promotion-code field there. |
Point the Python client at your installation with base_url or KAIMEI_BASE_URL; the dashboard with VITE_API_URL.
Paid plans. Set KAIMEI_STRIPE_SECRET_KEY, run kaimei-api billing setup to see what the Stripe account lacks, then --apply to create the plans' prices, the customer portal configuration and the webhook endpoint, and set KAIMEI_STRIPE_WEBHOOK_SECRET to the secret it prints. In Stripe, under Billing, Revenue recovery, keep cancelling the subscription as what happens when every retry of a payment has failed: a subscription left past_due keeps its plan. Enterprise is set by hand: kaimei-api billing set-limits saves the contract's limits, which the organization's admins cannot lift, and kaimei-api billing set-plan puts it on enterprise, where they apply. Save the limits first, so it is never on Enterprise without them; a limit left out is unlimited, apart from the logging rate, which stays at Enterprise's 2,000 rows a second unless --logged-rows-per-second N sets the contract's or --unlimited logged-rows-per-second removes it. billing show-limits prints what is in effect.
Upgrading. Starting the API applies any database migration it has not recorded. kaimei-api init-db does the same and then builds any missing indexes, and waits for them: run it before a new version takes traffic, as a pre-deploy step. Started without it, on Postgres, the API builds new indexes in the background without blocking writes. The release that adds organizations gives every existing account an owner's membership of its own workspace, and nothing moves. An organization that already has more than one member and is not on Team becomes read-only, so put it on a plan first if it should keep working as it does: kaimei-api billing set-plan <slug> team.
Hourly counts. Since 1.12.0 each model's predictions, explanations and outcomes are counted by the hour as they are written, and the home page, list totals, model statistics and histories read those counts, so they stay fast at hundreds of millions of predictions. After upgrading to 1.12.0, models logged before it are counted from their rows in the background, starting 10 minutes after the server starts (KAIMEI_HOURS_BACKFILL_DELAY_S, in seconds); until a model is counted, its numbers are counted from its rows as before, so they are the same, only slower. kaimei-api count-hours --check says how many models wait, kaimei-api count-hours counts them now, and --model SLUG counts one again, after its rows were changed in SQL rather than through the API, say. Every delete the API makes counts the hours it touched again.
Running it as a service. In production and staging the logs are JSON, one object a line, with time, level, logger, message and the request_id that the response carried as X-Request-Id, so a customer's id finds every line of their request. Each request also has an access line (event: "request") with its method, route, status, duration_ms and organization_id, and a slow statement a line with event: "slow_query". With KAIMEI_SENTRY_DSN set, each unhandled error goes to Sentry tagged with the request id, route and workspace; request bodies, headers and local variables are never sent, since they can hold customers' inputs and credentials. With KAIMEI_METRICS_TOKEN set, GET /metrics gives requests, durations, the database pool and the worker threads to Prometheus. Give your platform /health as its liveness check and /health/ready as its readiness check: the first answers while the server is busy, the second says 503 while the database does not answer.
Changing the secret. KAIMEI_SECRET_KEY signs sessions and emailed links and seals the endpoint credentials models are saved with, so replacing it alone signs everyone out and leaves those credentials unreadable (inference_credentials_unreadable), and two-factor secrets too (mfa_secret_unreadable). To change it, after a suspected leak or when someone who knew it leaves:
- Make a new one:
python -c "import secrets; print(secrets.token_urlsafe(48))". - Set
KAIMEI_PREVIOUS_SECRET_KEYSto the current value andKAIMEI_SECRET_KEYto the new one, together, and restart. Sessions, links and credentials made with the old one keep working. - Where the API runs, run
kaimei-api seal-credentials --apply. It seals every endpoint credential with the new secret, those saved as plain text included, and since API 1.11.0 every two-factor secret, and says how many it changed; without--applyit only reports. - After the longest session lifetime (7 days by default), or at once after a leak, when everyone signs in again, remove
KAIMEI_PREVIOUS_SECRET_KEYS.
Backups. Restore a backup into a new database, never over the one in use, and check it with kaimei-api restore-check --database-url URL. It only reads the database it is given, never the one in the settings, and reports the schema version, the row counts, the newest prediction and explanation (how old the copy is), whether recent predictions read back whole (--sample, 50 by default) and whether the endpoint credentials open with this environment's secrets. It ends with OK: this copy can be served. or a list of problems, and exits non-zero on problems. Keep the same KAIMEI_SECRET_KEY when the service moves to a restored database, and check /health/ready afterwards.
pip install -e ".[dev]" # from the kaimei API repository
kaimei-api init-db # create tables, apply migrations, build missing indexes
kaimei-api seed-demo # a demo account: five reference models, three fitted on data, an API key, a staged incident
# prints the account's email and a generated password once; --password sets your own
kaimei-api serve --reload # http://localhost:8000
# Paid plans: with KAIMEI_STRIPE_SECRET_KEY set
kaimei-api billing setup # check the Stripe account; changes nothing
kaimei-api billing setup --apply # create what is missing, print KAIMEI_STRIPE_WEBHOOK_SECRET
kaimei-api billing sync # read every subscription back from Stripe
kaimei-api billing set-limits acme-risk --models 500 --predictions-per-month 2000000 --logged-rows-per-second 5000 --note "MSA 2026-031"
kaimei-api billing set-plan acme-risk enterprise
kaimei-api billing show-limits acme-risk
# Postgres / Supabase
pip install -e ".[postgres]"
export KAIMEI_DATABASE_URL=postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:5432/postgres
kaimei-api migrate-db --inspect # row counts in the local SQLite file
kaimei-api migrate-db # copy it over
# Running it as a service
pip install -e ".[postgres,sentry]" # error reports with KAIMEI_SENTRY_DSN
curl -i http://localhost:8000/health/ready
curl http://localhost:8000/metrics -H "Authorization: Bearer $KAIMEI_METRICS_TOKEN"
kaimei-api seal-credentials --apply # after changing KAIMEI_SECRET_KEY: reseal with the new one
kaimei-api restore-check --database-url "$RESTORED_DATABASE_URL" # read-only checks of a restored backup
kaimei-api count-hours --check # how many models wait for their hourly history to be counted
kaimei-api count-hours --model credit-risk-v3 # count one model's history again from its rows
# Accounts
kaimei-api revoke-sessions [email protected] # sign out every session of an account; its API keys keep working
kaimei-api mfa-reset [email protected] # turn off two-factor sign-in for someone who lost the app and the codes