# Predictabl documentation > Build and call predictive models on your own data from Python, REST or an AI agent. Every page of https://predictabl.tech/docs/ in one file. # Predictabl docs Predictabl turns a question about your data into a trained, tested model, and serves its predictions. You bring tables (files or a database) and a question in plain words, like *"Which customers will stop buying in the next 30 days?"*. Predictabl reads the tables, writes the features as SQL you can review, keeps out columns that would leak the answer, trains and tests the model, and scores new data with it. You can do all of it from the web app, from Python, from any language over REST, or from an AI agent over MCP. Everything you build from code also shows up in the web app. ## The fastest start ```bash pip install predictabl export PREDICTABL_API_KEY=pk_... # Settings → API & MCP → Create token ``` ```python import predictabl as pb data = pb.connect("customers.csv") # a file, a DataFrame, or a database churn_model = data.predict("Which customers will churn?") churn_model.predict(customer) ``` ```text Probability that customer churned: 0.82 ``` That is the whole path: connect your data, ask, get a tested model, predict. The [Quickstart](https://predictabl.tech/docs/quickstart/) walks through it with real output. ## Four objects | Object | What it is | You get it from | |---|---|---| | **Data** | Your database or files | `pb.connect()`, `pb.datasets()` | | **Plan** | What Predictabl will predict, with which features, and what it excluded | `data.plan(question)` | | **Model** | A trained, tested model | `data.predict(question)`, `plan.train()` | | **Predictions** | Scores, with what they mean and the date they are for | `model.predict()` | ## Where to go next | I want to… | Read | |---|---| | Build my first model in five minutes | [Quickstart](https://predictabl.tech/docs/quickstart/) | | Get an API key and understand what it can reach | [Authentication](https://predictabl.tech/docs/authentication/) | | Control the plan before training | [Build a model](https://predictabl.tech/docs/build-a-model/) | | Score new data with a trained model | [Make predictions](https://predictabl.tech/docs/predictions/) | | Let Claude, Cursor or another agent use my models | [AI agents and MCP](https://predictabl.tech/docs/agents/) | | Call the API from another language | [REST API](https://predictabl.tech/docs/rest-api/) | | Look up a method or parameter | [Python reference](https://predictabl.tech/docs/python-reference/) | | Understand an error or a limit | [Errors and limits](https://predictabl.tech/docs/errors-and-limits/) | ## For AI agents Every page is also plain Markdown: add `.md` to its address (this page is [`/docs/index.md`](https://predictabl.tech/docs/index.md)). The whole documentation as one file is [`/docs/llms-full.txt`](https://predictabl.tech/docs/llms-full.txt); the index is [`/docs/llms.txt`](https://predictabl.tech/docs/llms.txt). --- # Quickstart In about five minutes you will connect a public customer dataset, ask which customers will churn, get a tested model, and score customers with it. **You need:** Python 3.10 or newer, and a Predictabl account. ## 1. Install ```bash pip install predictabl ``` ## 2. Get an API key In the web app, open **Settings → API & MCP** and select **Create token** (leave *Predictions only* unticked). Copy the token: it starts with `pk_` and is shown only once. ```bash export PREDICTABL_API_KEY=pk_... ``` The library reads the key from this variable. Keep it out of your code and out of git. [More on keys](https://predictabl.tech/docs/authentication/). ## 3. Get the example data The IBM Telco sample: 7,043 customers of a phone and internet company, one row each, with a `Churn` column saying whether they left. ```bash curl -sLo telco.csv https://raw.githubusercontent.com/IBM/telco-customer-churn-on-icp4d/master/data/Telco-Customer-Churn.csv ``` ## 4. Upload, ask, train ```python import predictabl as pb data = pb.connect("telco.csv", name="Telco customers") model = data.predict("Which customers will churn?") ``` Predictabl reports each step as it goes: ```text ✓ Uploading telco.csv · 947.7 KB ✓ Reading data 1 table ✓ Understanding Predict which telco customers will churn ✓ Planning 30 features · 2 excluded ✓ Preparing ✓ Building data ✓ Training ✓ Testing ✓ Final model auc 0.8458 ``` What happened: - **Reading data**: Predictabl read the table and worked out what each column is. - **Understanding**: it turned your question into a precise target: a customer whose `Churn` is `Yes`. - **Planning**: it chose 30 features and excluded 2 columns: `Churn` itself (it *is* the answer) and `customerID` (an identifier, not a signal). - **Testing**: the model was scored on customers it never saw while training. AUC 0.85 means it ranks a random churner above a random non-churner 85% of the time. Your numbers can differ slightly between runs. ## 5. Look at the result ```python print(model.report()) ``` ```python {'predicts': 'Predict which telco customers will churn', 'meaning': 'probability that customer churned / left the telco provider', 'kind': 'flat', 'metric': 'auc', 'score': 0.8458, 'rows_trained': 5634, 'rows_tested': 1409, 'top_features': [...], 'url': 'https://app.predictabl.tech/runs/...'} ``` Open `model.url` to see the same model in the web app: its plan, test results and feature importance. ## 6. Score customers ```python import csv customers = list(csv.DictReader(open("telco.csv")))[:3] preds = model.predict(rows=customers) print(preds.meaning) for p in preds: print(p["entity_id"], round(p["prediction"], 2), p.get("actual")) ``` ```text probability that customer churned / left the telco provider 7590-VHVEG 0.71 0 5575-GNVDE 0.04 0 3668-QPYBK 0.39 1 ``` These rows still contain their `Churn` column. It never reaches the model; it comes back as `actual`, so you can check the scores against what really happened. For new customers, just leave the column out. A pandas DataFrame works too: `model.predict(rows=df).to_pandas()`. ## Next - [Build a model](https://predictabl.tech/docs/build-a-model/): review and change the plan before training. - [Make predictions](https://predictabl.tech/docs/predictions/): score from your database, by date, or for one customer. - [AI agents and MCP](https://predictabl.tech/docs/agents/): let Claude or Cursor use your models. --- # Authentication Every request carries an API key (a *token*). A token belongs to one account and reaches only that account's data and models. ## Create a token In the web app, open **Settings → API & MCP**, give the token a name (for example *Nightly churn script*) and select **Create token**. The token starts with `pk_` and is **shown only once**: Predictabl stores only a hash of it, so it cannot be shown again. If you lose it, create another and revoke the old one. ## Full access or predictions only A new token has **full access**: from code, it can do what you do in the web app (upload data, ask questions, plan, train and get predictions), on your own account only. Tick **Predictions only** for a read-only token: it can get predictions and model results from your trained models, and change nothing. Use it for someone, or an app, that should only use your predictions. | | Full access | Predictions only | |---|---|---| | Get predictions and model results | ✓ | ✓ | | Upload data, ask, plan, train | ✓ | | | Change your AI-provider setting | ✓ | | | Create or revoke tokens | | | A token can never reach another account's data or models: someone else's model looks exactly like one that does not exist (`404`). ## Use the token ```bash export PREDICTABL_API_KEY=pk_... ``` ```python import predictabl as pb print(pb.account()) # who the token belongs to, plan, what is left ``` Or pass it explicitly, for example to use two accounts in one script: ```python client = pb.Client(api_key="pk_...") client.account() ``` Over REST, send it as a bearer token: ```bash curl https://app.predictabl.tech/pub/v1/account \ -H "Authorization: Bearer $PREDICTABL_API_KEY" ``` ## Which server | | Base URL | |---|---| | Hosted app (default) | `https://app.predictabl.tech/pub/v1` | | Your own instance | `http://localhost:8000/api/v1` | ```bash export PREDICTABL_BASE_URL=http://localhost:8000/api/v1 ``` or `pb.Client(base_url="http://localhost:8000/api/v1")`. ## Revoke a token **Settings → API & MCP → Your tokens**, then the bin icon. It stops working on the next request; there is no cache to wait for. ## Keep it safe - Read the key from the environment or a secrets manager. Never commit it. - One token per script or service, named after it, so you can revoke one without breaking the others. - Tick **Predictions only** wherever building is not needed. - If a token leaks, revoke it. **Settings → API & MCP** shows when each token was last used. --- # Build a model Building has three steps: **data**, **plan**, **train**. `data.predict(question)` runs all three. This page shows each one, so you can review and adjust before training. ## 1. Data ```python import predictabl as pb data = pb.connect("postgresql://readonly:pw@db.acme.com/sales") # a database data = pb.connect("orders.csv") # one file data = pb.connect(["customers.csv", "orders.csv", "tickets.csv"]) # several related tables data = pb.connect(df, name="Orders") # a pandas DataFrame ``` Several tables are fine: Predictabl finds how they link (`customer_id` in orders to `customer_id` in customers) and can join them. You do **not** need to pre-join or clean the data, or build a training table. `connect()` returns once Predictabl has read the tables. ### A database Predictabl reads the database **where it is, read-only**: it only runs `SELECT` queries and never writes to it. Postgres is supported. - **Use a read-only user.** Create one that can only `SELECT` from the tables Predictabl should see. - **Let Predictabl reach it.** The database must accept connections from the internet from Predictabl's server (`app.predictabl.tech`); allow its address in your firewall. - **The password is stored encrypted** on the server, and is never shown in progress, errors or the web app. ### Files CSV, Excel (`.xlsx`, `.xls`) and Parquet files, or a pandas DataFrame, up to 200 MB per call. Files are **uploaded** to Predictabl, and the progress shows `Uploading`. ### Data you added before To reuse data connected earlier, in code or in the web app: ```python for d in pb.datasets(): print(d.id, d.name, d.table_count) data = pb.data("") ``` ## 2. Plan A plan is what Predictabl will train: the exact target, the features, and the columns it excluded and why. ```python plan = data.plan("Which customers will stop buying in the next 30 days?") print(plan) ``` For example: ```text Predicting: 1 if the customer places no order in the 30 days after the cutoff, else 0 Task: binary_classification Features (28): orders_90d, revenue_90d, days_since_last_order, avg_basket_value, … Excluded refund_issued_at: dated after the outcome, so it would leak the answer ``` ### Ask a good question - **Name the outcome and the time window:** "stop buying in the next 30 days", not "churn". - **Say who it is about:** "for each store", "for customers active this year". - **Say what counts:** "a delivery is late if it arrives after the promised date". - **Forecasts:** "daily sales for each store for the next 6 weeks". ### Review the plan | | | |---|---| | `plan.target` | The outcome in words, as Predictabl defined it | | `plan.task` | `binary_classification`, `multiclass` or `regression` | | `plan.features` | The features it will use | | `plan.excluded` | Columns left out, each with a reason | | `plan.spec` | The full plan, including the SQL that builds the training data | Check the exclusions most carefully. A column that is only known *after* the outcome (a refund date, a cancellation reason) would make the model look great in testing and useless in production. Predictabl excludes those; make sure it caught all of them. ### Change it in plain words ```python plan = plan.refine("Don't use the support_tier column") plan = plan.refine("Only include customers with at least two past orders") ``` Each refinement returns a new version; the old one is unchanged. ## 3. Train ```python model = plan.train() ``` `train()` builds the training data from the plan, trains, tests the model on data it did not learn from, then retrains on everything for the final model. For a quick sanity check on a sample first: ```python preview = plan.train(preset="fast_preview") # about 15 seconds ``` Training runs on Predictabl's servers. Closing your script does not stop it; `model.wait()` picks it up again, and `model.cancel()` stops it. ### Progress Each step is printed as it happens (on one updating line in a terminal, one line per step in notebooks and logs). To silence it or handle it yourself: ```python model = plan.train(quiet=True) def show(update): # update.step, update.status, update.detail print(update.step, update.status, update.detail) model = plan.train(on_progress=show) ``` ### If something fails A failed step raises `predictabl.BuildFailed` with the reason and, when the server has them, suggested fixes: ```python try: model = plan.train() except pb.BuildFailed as e: print(e.code, e.message, e.suggestions) ``` ## Retrain later To train a plan again, for example with newer data, without planning again: ```python plan = pb.plan("") # the id is in the web app address of the question model = plan.train() ``` ## Credits and limits Planning a new question and changing a plan use credits on Predictabl's AI key; training and retraining never do. With your own OpenAI or Anthropic key (**Settings → AI provider**), building uses no credits. Check what is left: ```python pb.account()["credits"] ``` See [Errors and limits](https://predictabl.tech/docs/errors-and-limits/). --- # Make predictions There are two ways to score with a trained model: 1. **Send records**: `model.predict(rows=...)`. You pass the data. 2. **Score from your data**: `model.predict()`. Predictabl reads the data the model was trained on and builds the features itself. Which one fits depends on the model's **kind**. ## Model kinds ```python model = pb.model("") print(model.kind, "·", model.meaning) ``` | `kind` | One prediction is for… | Score with | |---|---|---| | `flat` | One record (a survey answer, a sensor reading, a form) | `rows=`: send the records | | `event` | One row of your data at a point in time (an order, a booking, a customer) | `model.predict()` with a date window, or `rows=` | | `forecast` | One entity on each future day or week (sales per store, demand per item) | `model.predict()`, optionally `as_of=` | `model.meaning` says what the number is, for example *"probability that customer churned"* or *"predicted sales: daily sales for a store"*. Show it next to the numbers; a score without it is easy to misread. ## Send records ```python preds = model.predict(rows=[ {"tenure": 2, "Contract": "Month-to-month", "MonthlyCharges": 89.1, ...}, ]) ``` `rows` can be one dict, a list of dicts, or a pandas DataFrame. Use the same column names as the data the model was trained on. Predictabl applies the model's own feature SQL to them, so the features are built exactly as in training. Any number of rows works; the library sends them in batches of 1,000. Send every column you know. A column you leave out counts as unknown: the request still works, but the score rests on less information and is less reliable. If a record has no id column, its `entity_id` is its position in your list (`"0"`, `"1"`, …). A record that still contains its outcome column (a row copied from the training file, say) scores the same as without it: the outcome never reaches the model. It comes back as `actual`, which makes a quick check easy. If a model summarises history (counts or averages over many rows per customer), the records you send are the only history it sees. `preds.warning` says so; score from your data instead. ## Score from your data ### Forecast models ```python preds = model.predict() # from the latest data preds = model.predict(as_of="2026-10-01") # as if today were 1 October print(preds.as_of) ``` `preds.as_of` is the date the forecast is made **from**; each prediction's `entity_id` reads `entity·as_of·step`, where step 1 is the first period after it. Check `as_of`: if your data stopped updating, it will be in the past. ### Event models By default, `model.predict()` scores rows dated **today**. Choose a window: ```python preds = model.predict(since_days=7) # the last 7 days preds = model.predict(since="2026-10-01", until="2026-10-31") # October ``` If nothing matched, `preds.note` says why and gives the newest date in the data. ### Narrow it down ```python model.predict(ids=["store_12", "store_40"]) # specific entities model.predict(limit=100) # the 100 highest scores model.predict(filters=[{"column": "city", "op": "eq", "value": "Milano"}]) model.predict(include=["city", "branch_name"]) # extra columns per prediction ``` Filters accept `eq`, `ne`, `in`, `contains`, `gt`, `gte`, `lt`, `lte`, on the model's table or a table it joins. Results are sorted highest first, at most 2,000 per call. Filters and `include` apply to event models. ## Read the predictions `model.predict()` returns a list of dicts with extra attributes: ```python preds[0] # {'entity_id': 'C-1042', 'prediction': 0.83, ...} preds.meaning # what 'prediction' is preds.kind # flat | event | forecast preds.as_of # forecasts: the date they are made from preds.note # why nothing matched, if so preds.warning # a caveat about how the scores were made, if any preds.count # how many matched (can exceed len(preds) when limited) preds.to_pandas() ``` Each prediction has: | Key | | |---|---| | `entity_id` | Which customer, order, store… (forecasts add `·as_of·step`) | | `prediction` | Probability of the outcome (classification) or the value (regression) | | `predicted_class`, `probabilities` | Multiclass models only: the likeliest class and every class's probability | | `actual` | The real outcome, when the record you sent contained it | | `context` | The columns you asked for with `include` | | `label` | A display name for the entity, when the data has one | For multiclass models, read `predicted_class`, not `prediction`: `prediction` is the probability of the likeliest class and does not say which class that is. ## Calibrated probabilities Classification scores rank well but are not always true probabilities. When scoring from your data, `model.predict(calibrated=True)` returns probabilities you can read as "how often this happens", for models that have a calibrator. --- # AI agents and MCP There are two ways an AI agent works with Predictabl: | | The agent… | Use | |---|---|---| | **An assistant answers questions** | calls your trained models as tools: "which customers are most likely to churn this month?" | The MCP server (below) | | **A coding agent writes code** | builds and scores models in your project with the Python library | The docs as Markdown, and an `AGENTS.md` note (below) | ## Connect an assistant over MCP The Python library includes an MCP server. It runs on your machine and talks to Predictabl with your token. Use a **Predictions only** token: the tools read and predict, and never upload or train. You need [`uv`](https://docs.astral.sh/uv/) installed (`uvx` comes with it). ### Claude Code ```bash claude mcp add predictabl --env PREDICTABL_API_KEY=pk_... -- uvx --from "predictabl[mcp]" predictabl mcp ``` ### Claude Desktop In **Settings → Developer → Edit Config**, add to `claude_desktop_config.json`: ```json { "mcpServers": { "predictabl": { "command": "uvx", "args": ["--from", "predictabl[mcp]", "predictabl", "mcp"], "env": { "PREDICTABL_API_KEY": "pk_..." } } } } ``` ### Cursor In `.cursor/mcp.json` (this project) or `~/.cursor/mcp.json` (every project), add the same `mcpServers` entry as for Claude Desktop. ### Any other MCP client Run `uvx --from "predictabl[mcp]" predictabl mcp` over stdio, with `PREDICTABL_API_KEY` set. For your own instance, also set `PREDICTABL_BASE_URL=http://localhost:8000/api/v1`. ### Tools | Tool | What it does | |---|---| | `list_models` | Your trained models: what each predicts, its test metric | | `get_model` | One model: what its number means, its kind, how well it tested, top features | | `predict` | Score from your data: forecasts from the latest data or a date; event models by date window; filters, extra columns, one entity | | `predict_rows` | Score records the agent passes in (up to 1,000 per call) | | `top_risks` | The entities a classifier scored highest on its test, with the real outcome next to each | | `top_forecasts` | The highest (or lowest) forecasts across every entity | | `get_forecast` | The forecasts made at training time | | `get_backtest` | Predicted against actual on held-out data, for one entity | | `list_connections` | Your datasets (needs a Full access token) | | `account` | Your plan and what is left of it | ### Things to ask - "List my Predictabl models and tell me which one I can trust most." - "Which 10 customers are most likely to churn, and how good is that model?" - "Forecast sales for store 12 for the next two weeks. What date is the forecast from?" - "Would a customer on a month-to-month contract paying 90 a month churn?" ## Help a coding agent build with Predictabl Point the agent at the whole documentation as one Markdown file: ```text https://predictabl.tech/docs/llms-full.txt ``` Each page also exists as Markdown at its own address plus `.md` (for example [`/docs/predictions.md`](https://predictabl.tech/docs/predictions.md)), and [`/docs/llms.txt`](https://predictabl.tech/docs/llms.txt) lists them all. To make it stick in a project, add this to the project's `AGENTS.md` (or `CLAUDE.md`): ```markdown ## Predictabl This project uses Predictabl (`pip install predictabl`) for predictive models. Docs for agents: https://predictabl.tech/docs/llms-full.txt - Read the key from the PREDICTABL_API_KEY environment variable. Never write a key into code, tests, notebooks or commits. - Build: `data = pb.connect(path_or_database_url)`, then `plan = data.plan(question)`. Show the user `print(plan)` (target, features, exclusions) before `plan.train()`. Each new question uses credits; check `pb.account()["credits"]` first. - Score: check `model.kind` first. `flat` needs `rows=`; `event` scores rows dated today unless given `since`/`until`/`since_days`; `forecast` projects from the latest data (`preds.as_of` says from when). - Always report `preds.meaning` with the numbers, and `preds.as_of` for forecasts. For multiclass models use `predicted_class`, not `prediction`. - Errors are `predictabl.PredictablError` subclasses with `.code` and a message that says what to do: show the message to the user rather than retrying. ``` ### Rules of thumb for agents - **Plan before you train.** `data.plan()` is cheap to read and catches a wrong target before credits are spent; `data.predict()` skips that review. - **Do not loop new questions.** Each one uses credits and a model slot. Refine the plan instead of asking again. - **Use `fast_preview` to check a plan,** then train for real. - **A `LimitReached` error is not transient.** Retrying will not help; the message says what will (the user's own AI key, or an upgrade). - **An empty result is an answer.** Read `preds.note` before widening the window. --- # REST API The Python library is a thin layer over this API; anything it does, you can do over HTTP. ## Basics | | | |---|---| | Base URL | `https://app.predictabl.tech/pub/v1` | | Authentication | `Authorization: Bearer pk_...` ([get a token](https://predictabl.tech/docs/authentication/)) | | Format | JSON in and out; uploads are `multipart/form-data` | Every response has the same envelope: ```json {"data": { ... }, "error": null} ``` ```json {"data": null, "error": {"code": "NOT_FOUND", "message": "Run not found", "details": null}} ``` Key and access problems answer `401` or `403` with `{"detail": "..."}` instead. [All error codes](https://predictabl.tech/docs/errors-and-limits/). The examples below use: ```bash export P=https://app.predictabl.tech/pub/v1 export AUTH="Authorization: Bearer $PREDICTABL_API_KEY" ``` ## Score with a trained model Any token can do these, including a **Predictions only** one. ### List your models ```bash curl -s "$P/runs?limit=50" -H "$AUTH" ``` Each item has `id`, `state` (`SUCCEEDED` when ready), `opportunity_title` (what it predicts) and `headline_metric`. `GET /runs/{id}` adds `kind` and `meaning`, and `GET /runs/{id}/results` the full test results. ### Score records ```bash curl -s -X POST "$P/runs/$MODEL_ID/predict-records" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"rows": [{"tenure": 2, "Contract": "Month-to-month", "MonthlyCharges": 89.1}]}' ``` ```json {"data": {"run_id": "...", "task": "binary_classification", "target": "churned", "meaning": "probability that customer churned", "count": 1, "predictions": [{"entity_id": "0", "prediction": 0.71}]}, "error": null} ``` At most 1,000 rows per request. Send every column you know: left-out columns count as unknown, which makes the score less reliable. A record without an id column gets its position as `entity_id`. ### Score from your data ```bash curl -s -X POST "$P/runs/$MODEL_ID/predict" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"since": "2026-10-01", "until": "2026-10-31", "top": 100}' ``` | Field | | |---|---| | `top` | How many to return, highest first (default 200, at most 2,000) | | `since`, `until` | Event models: a date window (`YYYY-MM-DD`, inclusive) | | `since_days` | Event models: the last N days | | `cutoff` | Forecast models: forecast as of this date instead of the latest data | | `entity_contains` | Only entities whose id contains this text | | `filters` | `[{"column": "city", "op": "eq", "value": "Milano"}]`; `op` is `eq`, `ne`, `in`, `contains`, `gt`, `gte`, `lt` or `lte` | | `include` | Extra columns to return with each prediction, under `context` | | `calibrated` | `true` for calibrated probabilities, where the model has a calibrator | | `new_rows` | Rows to add to the model's data for this call only, by table: `{"orders": [{...}, ...]}`. For example the coming days of a forecast (promotions, holidays), or history newer than the database. Never saved | To fill a form or a picker: `GET /runs/{id}/record-fields` lists the fields a record needs (`required`, `optional`), and `GET /runs/{id}/entities` the entity ids a model knows. The response adds `kind`, `meaning`, `count` (all that matched) and `showing`; forecasts add `as_of`; an empty event-model result adds a `note`. See [Make predictions](https://predictabl.tech/docs/predictions/) for what each means. ## Build a model These need a **Full access** token. Planning and training run in the background: start them, then poll. ### 1. Connect your data Files: ```bash curl -s -X POST "$P/connections/from-csv" -H "$AUTH" \ -F name="Telco customers" -F files=@telco.csv ``` Repeat `-F files=@...` for several tables. Or a Postgres database (read-only user recommended), then start reading it: ```bash curl -s -X POST "$P/connections" -H "$AUTH" -H "Content-Type: application/json" \ -d '{"name": "Sales", "kind": "postgres", "config": {"dsn": "postgresql://readonly:pw@db.acme.com/sales"}}' curl -s -X POST "$P/connections/$DATA_ID/introspect" -H "$AUTH" ``` Then poll until `status` is `ready` (or `error`): ```bash curl -s "$P/connections" -H "$AUTH" ``` ### 2. Ask the question ```bash curl -s -X POST "$P/connections/$DATA_ID/opportunities" -H "$AUTH" \ -H "Content-Type: application/json" \ -d '{"mode": "single", "user_context": "Which customers will churn?"}' ``` The answer has a `job_id`. Poll `GET /connections/$DATA_ID/opportunities/job` until that job's `state` is `done` (or `failed`, with a `message`), then take the new question from `GET /connections/$DATA_ID/opportunities`. ### 3. Plan ```bash curl -s -X POST "$P/opportunities/$QUESTION_ID/spec" -H "$AUTH" \ -H "Content-Type: application/json" -d '{}' ``` Poll `GET /opportunities/$QUESTION_ID/spec` until `spec` is no longer `null`. If planning failed, `GET /opportunities/$QUESTION_ID` has `last_generation_error`. The plan's `id` is what you train. To change it in plain words: `POST /opportunities/$QUESTION_ID/spec/refine` with `{"message": "Don't use the support_tier column"}`, then poll for a higher `version`. ### 4. Train ```bash curl -s -X POST "$P/runs" -H "$AUTH" -H "Content-Type: application/json" \ -d '{"spec_id": "'"$PLAN_ID"'", "preset": "full_quality"}' ``` `preset` is `full_quality` (default) or `fast_preview` (a quick check on a sample). Poll `GET /runs/$MODEL_ID` until `state` is `SUCCEEDED`, `FAILED` (with `error_code`, `error_message` and `suggestions`) or `CANCELLED`. Step-by-step progress is at `GET /runs/$MODEL_ID/events.json`; `POST /runs/$MODEL_ID/cancel` stops it. ## Your account ```bash curl -s "$P/account" -H "$AUTH" ``` ```json {"data": {"email": "you@example.com", "plan": "...", "llm_source": "managed", "credits": {"balance": ..., "costs": {...}}, "predictions_this_month": ..., "predictions_monthly_limit": ..., "models_kept": ..., "models_limit": ..., "schedules": ...}, "error": null} ``` ## Polling Poll every 2 to 5 seconds. Planning usually takes one to a few minutes; training from seconds to tens of minutes, depending on the data. Requests time out after 15 minutes, so never hold one open waiting: start the job, then poll. --- # Errors and limits ## Errors Every error from the Python library is a `predictabl.PredictablError` with `.code` (the API's code, when it sent one), `.status` (the HTTP status) and `.message`, written to say what to do next. ```python import predictabl as pb try: model = data.predict("Which customers will churn?") except pb.LimitReached as e: print(e.message) # how to continue except pb.PredictablError as e: print(e.code, e.message) ``` | Exception | HTTP | Means | Do | |---|---|---|---| | `AuthenticationError` | 401 | The key is missing, wrong or revoked | Check `PREDICTABL_API_KEY`; create a new token | | `LimitReached` | 402 | An allowance of your plan is used up | The message says what is left and how to continue. Retrying will not help | | `PermissionDenied` | 403 | The token's access does not allow this | Use a **Full access** token to upload or train | | `NotFound` | 404 | No such dataset, question or model on this account | Check the id. Other accounts' objects also answer 404 | | `InvalidRequest` | 4xx | The request was refused; the message says why | Fix the request | | `BuildFailed` | — | Reading the data, planning or training failed | Read `.message` and `.suggestions` | | `ApiError` | 5xx | Something failed on the server, or it could not be reached | Retry later. Reads are retried for you | ### Codes you may see | Code | Where | Meaning | |---|---|---| | `CREDITS_EXHAUSTED` | Planning or changing a plan | Not enough credits left for this | | `MODEL_LIMIT` | Planning or training a new question | Your plan's number of models is reached; delete one to make room | | `PREDICTIONS_LIMIT` | Scoring | This request needs more predictions than are left this month; nothing was scored or counted | | `SCHEDULES_PAID` | Creating or resuming a schedule | Schedules are on paid plans | | `FILE_TOO_LARGE` | Uploading | A file is larger than your plan allows | | `MISSING_REQUIRED_FIELDS` | Scoring records | A record leaves out a field the model needs; `details.missing` lists them | | `LLM_DAILY_LIMIT` | Any step that uses AI | Today's AI calls on Predictabl's key are used; resets at 00:00 UTC | | `PREDICT_UNAVAILABLE` | `model.predict()` | This model cannot score that way; for a flat model, send `rows=` | | `RUN_NOT_READY` | Scoring | The model has not finished training | | `NOT_FOUND` | Anywhere | The id does not exist on this account | | `SPEC_CONFLICT` | Changing a plan | Someone changed the plan at the same time; read it again | A training run that fails ends with `state: FAILED`, an `error_code`, an `error_message` and `suggestions`, which `BuildFailed` carries. ## Limits ### Your plan Your plan's allowances, and how much of each is left, are in **Settings → API & MCP**, or from code: ```python acct = pb.account() acct["credits"] # balance, and what a model costs acct["predictions_this_month"], acct["predictions_monthly_limit"] acct["models_kept"], acct["models_limit"] ``` - **Credits** pay for the AI work on Predictabl's key: turning a question into a plan, and changing a plan. Training, retraining and predictions never use credits. A plan or model that fails to build is refunded automatically. - **With your own OpenAI or Anthropic key** (**Settings → AI provider**), building uses no credits: you pay your provider directly. Your plan's other allowances still apply. - **Predictions** are counted per prediction returned, across all your models. The Prediction explorer in the web app is not counted. A request is all or nothing: if it needs more than you have left, nothing is scored or counted, and the message says how many it needed. - **A limit of `None`** means your plan has none for that allowance. A daily cap on AI calls on Predictabl's key stops a runaway script; it resets at 00:00 UTC. ### Requests | | Limit | |---|---| | Records per `predict-records` request | 1,000 (the Python library batches for you) | | Predictions per `predict` request | 2,000 | | Upload size | 200 MB per request | | Request duration | 15 minutes; long work runs in the background and is polled | --- # Python reference `predictabl` 0.1.1. Generated from the library itself, so the signatures here always match the package. `pip install predictabl`; source on [GitHub](https://github.com/predictabl/predictabl-python). ## Module functions These use one shared client, configured by `login()` or the `PREDICTABL_API_KEY` and `PREDICTABL_BASE_URL` environment variables. ### `pb.login()` ```python pb.login(api_key: str | None = None, base_url: str | None = None, **kw) ``` Configure the shared client. Without arguments, reads PREDICTABL_API_KEY (and PREDICTABL_BASE_URL) from the environment. Other keyword arguments are passed to `Client`. ### `pb.account()` ```python pb.account() ``` Who you are, your plan, your credits and what is left of your allowances. ### `pb.connect()` ```python pb.connect( source: str | Path | Iterable[str | Path] | Any, name: str | None = None, *, wait: bool = True, quiet: bool = False, on_progress: Callback | None = None, timeout: float | None = 1800, ) ``` Connect data to Predictabl: a database or files. * A Postgres address (``"postgresql://user:password@host:5432/db"``): Predictabl reads the database where it is, read-only. Use a read-only user, and make sure the database accepts connections from Predictabl's server. * CSV, Excel or Parquet files, a list of them, or a pandas DataFrame: the files are uploaded to Predictabl. Several files become several tables Predictabl can join. With `wait` (default) returns once Predictabl has read the tables. ### `pb.datasets()` ```python pb.datasets() ``` Every dataset on this account: uploads and connected databases. ### `pb.data()` ```python pb.data(data_id: str) ``` One dataset by id (from `datasets()` or the web app). ### `pb.plan()` ```python pb.plan(question_id: str) ``` The latest plan of a question (opportunity) planned earlier, e.g. in the web app, to retrain it from code without planning again. ### `pb.model()` ```python pb.model(model_id: str) ``` One model by id (from `models()` or the web app address). ### `pb.models()` ```python pb.models(limit: int = 50) ``` Your models, newest first, trained or not (check `model.ready`). ## Client A connection to Predictabl. `api_key` defaults to the PREDICTABL_API_KEY environment variable and `base_url` to PREDICTABL_BASE_URL, else the hosted app. For a local instance use `base_url="http://localhost:8000/api/v1"`. ```python pb.Client( api_key: str | None = None, base_url: str | None = None, *, timeout: float = 120.0, poll_interval: float = 2.0, ) ``` ### `client.account()` ```python client.account() ``` Who you are, your plan, your credits and what is left of your allowances. ### `client.connect()` ```python client.connect( source: str | Path | Iterable[str | Path] | Any, name: str | None = None, *, wait: bool = True, quiet: bool = False, on_progress: Callback | None = None, timeout: float | None = 1800, ) ``` Connect data to Predictabl: a database or files. * A Postgres address (``"postgresql://user:password@host:5432/db"``): Predictabl reads the database where it is, read-only. Use a read-only user, and make sure the database accepts connections from Predictabl's server. * CSV, Excel or Parquet files, a list of them, or a pandas DataFrame: the files are uploaded to Predictabl. Several files become several tables Predictabl can join. With `wait` (default) returns once Predictabl has read the tables. ### `client.datasets()` ```python client.datasets() ``` Every dataset on this account: uploads and connected databases. ### `client.data()` ```python client.data(data_id: str) ``` One dataset by id (from `datasets()` or the web app). ### `client.plan()` ```python client.plan(question_id: str) ``` The latest plan of a question (opportunity) planned earlier, e.g. in the web app, to retrain it from code without planning again. ### `client.model()` ```python client.model(model_id: str) ``` One model by id (from `models()` or the web app address). ### `client.models()` ```python client.models(limit: int = 50) ``` Your models, newest first, trained or not (check `model.ready`). ### `client.close()` ```python client.close() ``` Close the HTTP connection. `with pb.Client() as c:` does it for you. ## Data A dataset on Predictabl: uploaded files or a connected database. | Attribute | | |---|---| | `id` | Dataset id | | `name` | Its name | | `status` | `ready` once read | | `table_count` | How many tables | | `error` | Why reading failed, if it did | ### `data.plan()` ```python data.plan( question: str, *, quiet: bool = False, on_progress: Callback | None = None, timeout: float | None = 1800, ) ``` Turn a question into a reviewable plan: target, features and what was excluded as leakage. Spends one build on Predictabl's AI key. ### `data.predict()` ```python data.predict( question: str, *, preset: str = "full_quality", engine: str = "auto", quiet: bool = False, on_progress: Callback | None = None, timeout: float | None = None, ) ``` The whole path: question -> plan -> trained, tested model. ### `data.questions()` ```python data.questions() ``` Questions (prediction opportunities) found or asked on this data. ### `data.wait_ready()` ```python data.wait_ready(*, timeout: float | None = 1800) ``` Wait until Predictabl has read the tables (status "ready"). ### `data.refresh()` ```python data.refresh() ``` Reload status and table count from the server. ### `data.delete()` ```python data.delete() ``` Delete this dataset and its uploaded files. Models trained on it can no longer read it, so delete only data you no longer score from. ## Plan What Predictabl will train: the target, the features, and what it excluded as leakage. Review it, refine it in plain words, then train. | Attribute | | |---|---| | `id` | Plan id (what `train` uses) | | `version` | Plan version | | `opportunity_id` | The question it belongs to | | `target` | The outcome, in words | | `task` | `binary_classification`, `multiclass` or `regression` | | `features` | Features it will use | | `excluded` | Columns left out, with reasons | | `spec` | The full plan, including its SQL | ### `plan.summary()` ```python plan.summary() ``` The plan in a few readable lines; also what `print(plan)` shows. ### `plan.refine()` ```python plan.refine( message: str, *, quiet: bool = False, on_progress: Callback | None = None, timeout: float | None = 1800, ) ``` Change the plan in plain words ("don't use the courier column"). Returns the new version; this object stays the version it was. ### `plan.train()` ```python plan.train( *, preset: str = "full_quality", engine: str = "auto", wait: bool = True, quiet: bool = False, on_progress: Callback | None = None, timeout: float | None = None, ) ``` Train and test this plan. `preset="fast_preview"` is a ~15-second sanity check on a sample; the default is the real model. ## Model A trained (or training) model. `predict()` scores with it. | Attribute | | |---|---| | `id` | Model id | | `state` | `SUCCEEDED` when ready; `FAILED`, `CANCELLED`, or a step name while training | | `ready` | `True` once trained | | `title` | What it predicts | | `kind` | `flat`, `event` or `forecast` | | `meaning` | What its prediction number is | | `created_via` | The token that created it, if made from code | | `url` | The model in the web app | | `error_code` | Why it failed, if it did | | `suggestions` | Server-suggested fixes | ### `model.predict()` ```python model.predict( rows: Any = None, *, ids: Iterable[str] | str | None = None, since: str | date | datetime | None = None, until: str | date | datetime | None = None, since_days: int | None = None, as_of: str | date | datetime | None = None, limit: int | None = None, filters: list[dict] | None = None, include: list[str] | None = None, calibrated: bool = False, ) ``` Score with this model. * `rows` (DataFrame, list of dicts or one dict): score these records. Predictabl builds the features from them with the model's own SQL. * otherwise Predictabl scores from the data it was trained on: forecasts from the latest data (or `as_of`), event models for rows dated today (or `since`/`until`/`since_days`), optionally only `ids`, highest first, at most `limit` (server cap 2000). ### `model.report()` ```python model.report() ``` The tested result: metric, rows, top features, what it predicts. ### `model.wait()` ```python model.wait( *, quiet: bool = False, on_progress: Callback | None = None, timeout: float | None = None, ) ``` Block until training ends. Raises BuildFailed if it failed. ### `model.events()` ```python model.events() ``` Everything the run reported, step by step. ### `model.refresh()` ```python model.refresh() ``` Reload state, kind and errors from the server. ### `model.cancel()` ```python model.cancel() ``` Stop training. The model ends CANCELLED. ## Predictions A list of predictions (dicts with `entity_id`, `prediction`, ...), plus what they mean: `meaning`, `kind`, `as_of`, and any `note` or `warning` the server attached. | Attribute | | |---|---| | `meaning` | What `prediction` is, in words | | `kind` | `flat`, `event` or `forecast` | | `as_of` | Forecasts: the date they are made from | | `note` | Why nothing matched, when nothing did | | `warning` | A caveat about how the scores were made | | `where_used` | Which rows were scored, as the server applied it | | `count` | How many matched (can exceed `len()` when limited) | | `raw` | The server's full response, without the predictions | ### `predictions.to_pandas()` ```python predictions.to_pandas() ``` The predictions as a DataFrame (needs pandas). Context columns requested with `include` become their own columns. ## Progress updates `on_progress` callbacks receive `pb.Update` objects: | Field | | |---|---| | `step` | e.g. `Uploading`, `Planning`, `Training`, `Final model` | | `status` | `running`, `done` or `failed` | | `detail` | Short text, e.g. `30 features · 2 excluded` | ## Errors Every error carries the server's machine `code` (when it sent one) and a message meant for a person: the API phrases refusals as "what happened and what to do", and these classes pass that through untouched. | Exception | | |---|---| | `pb.PredictablError` | Base class for everything this package raises. | | `pb.AuthenticationError` | The API key is missing, wrong or revoked (HTTP 401). | | `pb.PermissionDenied` | The API key is valid but its scope does not allow this (HTTP 403). Predictions only keys cannot connect data, plan or train. | | `pb.NotFound` | No such object for this account (HTTP 404). Someone else's objects look exactly like missing ones, by design. | | `pb.LimitReached` | A free-plan allowance on Predictabl's AI key is used up (HTTP 402). The message says how to continue (your own AI key, or an upgrade). | | `pb.InvalidRequest` | The request was understood but refused (HTTP 4xx), e.g. a model that needs rows was asked to score without them. | | `pb.BuildFailed` | A step of building a model (reading the data, finding the question, planning, training) ended in failure. `suggestions` lists the server's recovery options when it gave any. | | `pb.ApiError` | Anything else the server answered with an error. | ---