Python client fione-sdk
fione-sdk is a small Python client for the Fione API. Use it in a notebook or a script to upload datasets, train models with AutoML, read leaderboards, make predictions and run Python modules. Data goes in and out as pandas DataFrames, and it needs Python 3.12 or later.
It talks to the REST API with an API token, so it can do what the person who owns the token can do, and nothing more.
Install
The client lives in the sdk/ folder of the Fione repository. Install it from a clone:
git clone https://github.com/codelibs/fione.git
pip install ./fione/sdkIt depends on httpx and pandas, which pip installs for you.
Configure
Create an API token on the Account page (see Users, roles and sharing), then give the client your server's address and the token. Client() reads two environment variables:
| Variable | What it is |
|---|---|
FIONE_URL | The address of your Fione server, for example http://localhost:8080. |
FIONE_TOKEN | An API token. |
export FIONE_URL=http://localhost:8080
export FIONE_TOKEN=<your-token>Client(url=..., token=...) takes the same two values as arguments instead. Two more options:
timeout=is the request timeout in seconds (default 60).http=is anhttpx.Clientto send through instead of the client's own.urlandtimeoutare then ignored, and the token goes to wherever that client points.
If the token or the address is missing, Client() raises FioneError with the code config. Do not put the token in code you share; read it from the environment or a secret store.
Example
import pandas as pd
from fione_sdk import Client
fione = Client()
project = fione.create_project("demo")
dataset = fione.upload(project["id"], pd.read_csv("train.csv"), "train")
print(fione.profile(project["id"], dataset["id"]))
frame = fione.read(project["id"], dataset["id"])create_project and upload return the objects the API returns, as dicts: a project has an id (a text id such as demo-1a2b3c) and a dataset has a number id. upload takes the dataset type as its fourth argument: "train" (the default), "test" or "predict".
Train, wait, predict
train queues AutoML training and returns a Job. wait blocks until the job has ended.
job = fione.train(project["id"], dataset["id"], "species", max_runtime_secs=300)
for event in job.events(follow=True): # progress, until the job has ended
print(event["type"], event["data"])
job.wait()
model_id = job.result["model_id"]
print(fione.leaderboard(model_id)) # one row per model AutoML tried
print(fione.models(project["id"])) # one row per model of the project
new_rows = pd.read_csv("new_rows.csv") # the same input columns, without "species"
predictions = fione.predict(project["id"], model_id, new_rows) # a "predict" columntrain(project_id, dataset_id, target, *, name=None, extra_dataset_ids=None, **config) takes the column to predict and the other training options as keyword arguments. The dataset must be a train dataset. extra_dataset_ids names other train datasets of the project whose rows are only learned from, never validated (see Extra training data). The options are those of a training run:
| Option | Default | Meaning |
|---|---|---|
task | "auto" | "auto", "classification" or "regression". |
max_runtime_secs | 3600 | Training stops at this time and keeps the best model so far. |
max_runtime_secs_per_model | none | Caps each model's training. |
max_models | none | Stops after this many models. |
nfolds | 5 | Cross-validation folds (2 or more). |
cv_repeats | by rows | How many times the folds are drawn again with other seeds (1 to 10); by default 3 up to 2,000 rows, 2 up to 5,000, else 1. |
cv_group_column | none | Rows that share a value of this column stay in one fold (for example several rows per customer). |
time_column | none | Validates forward in time: the rows ordered by this number or date column are cut into parts, and each fold learns from the parts before the one it predicts. |
seed | 0 | The same seed gives the same splits and search. |
balance_classes | False | Gives rare classes more weight while learning. |
decision | "argmax" | "argmax", "balanced" (adjusts for class sizes; not together with balance_classes), "tuned" (fits the decision threshold to sort_metric; two classes, or qwk with ordered classes) or "cost" (the threshold with the lowest cost; two classes). Ignored for regression. |
cost_miss, cost_false_alarm | none | With decision="cost" only, and then both required: the cost of a row of the class listed last that is given the other class, and of the opposite (above 0, up to 1e12, in the same unit). |
target_transform | "none" | "none" or "log1p" (regression only; ignored for classification). |
quantile | none | Learns this quantile (between 0 and 1) of a regression target instead of its mean, with the pinball loss. |
event_column | none | Survival: the target is a time that may be cut short, and this 0/1 column says whether the event happened. Models are ranked by concordance. Not with quantile or target_transform. |
feature_engineering | True | Adds derived features that clearly help. |
stopping_rounds, stopping_metric, stopping_tolerance | 10, "auto", 0.001 | Early stopping of a model family. |
sort_metric | "auto" | The score the leaderboard is ranked by (see below). |
keep_cv_predictions, keep_cv_models, keep_cv_fold_assignment | False | Keep cross-validation results (the models make the model file much larger). |
ignored_columns | [] | Columns that are not used as inputs. |
extra_weight | 1 | The weight of the rows of extra_dataset_ids while learning (above 0, at most 1e6). Scores are never weighted. |
embedding_backend, embedding_model, embedding_layer, embedding_max_length | none, "", 0.75, 384 | Language-model vectors of the text columns for the TextEmbedding family; see Language-model vectors of text. |
Training does not leave out ID columns by itself (it drops only empty columns and columns with one value): with a configuration you write yourself, a row number, for example, is then an input like any other number. List ID-like columns in ignored_columns, or take the columns from a configuration that leaves them out: the training settings page unchecks them, and the MCP tool propose_training_config (see MCP) lists them, up to 200, in its ignored_columns.
sort_metric and stopping_metric take auto or one of logloss, auc, aucpr, accuracy, balanced_accuracy, f1, macro_f1, precision, recall, mcc, kappa, qwk, rounded_qwk, brier, balanced_logloss, top3_accuracy, map3, gini, normalized_gini, lift_top_group, misclassification, mean_per_class_error, rmse, mse, mae, medae, r2, rmsle, mape, rmspe, smape, explained_variance, pearson, spearman, poisson, pinball (with quantile) and concordance (with event_column), as far as they fit the task. The settings and metrics are explained in AutoML screens.
The web app offers the same settings on its training screen (see AutoML screens). A configuration the engine refuses (an unknown option, or a target column with gaps or a single value) raises FioneError with HTTP status 422 and nothing is queued.
Jobs
Everything that takes time is a job on the server: training, batch prediction, modules. A Job has:
job.id,job.data(the job as last fetched), andjob.status(queued,running,done,failedorcancelled) andjob.result, which read fromjob.data.job.refresh()andjob.cancel(), which updatejob.data. Cancelling a job that has already finished raisesFioneError(409).fione.job(job_id)gets a job again later.job.events(after=0, follow=False), which yields the job's events, oldest first, as dicts withid,type,tsanddata. Withfollow=Trueit waits for new ones until the job has ended.job.wait(timeout=None, poll=1.0, max_poll=10.0), which polls and doubles the interval up tomax_poll. It returns the job when it isdone. It raisesfione_sdk.JobFailed(aFioneError) when the job failed or was cancelled:codeis"failed"or"cancelled",messageis the job's message,jobis the job, andstatusis 0 because no HTTP response is involved. Aftertimeoutseconds it raisesTimeoutErrorand leaves the job running. Interrupting a wait (Ctrl-C in a notebook) cancels the job.
Predict
predict(project_id, model_id, df, *, include_columns=None, timeout=None) uploads the frame as a temporary dataset, predicts on the server, reads the result back in the order of the rows and deletes the temporary dataset. The upload is deleted also when the prediction fails or times out. After timeout seconds it cancels its batch-prediction job and raises TimeoutError; a job that failed raises JobFailed. It needs write access to the project.
The result has a predict column with the predicted value or class and, for classification, one p_<class> column per class with its probability. By default the input columns follow; pass include_columns=[...] to copy only those. The result dataset (named predict_sdk_predict_<8 characters>) stays in the project, so you can find it again among its datasets; delete the ones you no longer need.
Datasets and models
| Call | Returns |
|---|---|
projects(), project(project_id), create_project(name) | The projects you can see, one project, or a new project (dicts). |
datasets(project_id), dataset(project_id, dataset_id) | The datasets of a project, or one dataset with its column schema. |
upload(project_id, df, name, type="train") | The new dataset. |
read(project_id, dataset_id) | The dataset as a DataFrame. |
preview(project_id, dataset_id, rows=50) | The first rows (at most 200) as {"columns": ..., "rows": ...}. |
profile(project_id, dataset_id), column_profile(project_id, dataset_id, column) | Statistics, histograms and correlations of the dataset, or the profile of one column. |
delete_dataset(project_id, dataset_id) | Nothing. |
models(project_id) | A DataFrame with one row per model of the project. |
model(model_id) | One model with its metrics, configuration, leaderboard and variable importance. |
leaderboard(model_id) | A DataFrame, one row per model AutoML tried, best first. |
Modules
modules() lists what the server can run. run_module queues one over a dataset and returns a Job; the module runs on the server, not in your notebook, so it needs no packages here.
job = fione.run_module(project["id"], "sort", dataset["id"], {"column": "age"})
job.wait()
sorted_frame = fione.read(project["id"], job.result["dataset_id"])run_module(project_id, module_id, dataset_id, params=None, *, name=None) takes the module's parameters as a dict and, optionally, a name for the new dataset. See Python modules for the built-in modules and for writing your own.
Errors and limits
- A response that is not a 2xx raises
fione_sdk.FioneError, with the HTTPstatus, the API's errorcodeand amessage. For example, a project you cannot see raisesFioneError: project not found (not_found, HTTP 404). - A redirect is an error too. It usually means
FIONE_URLshould be thehttpsaddress. The client never follows redirects, so the token is never sent to another address. - Transport errors (
httpx.ConnectError, timeouts) are not wrapped and propagate as they are. - Frames travel as CSV, so data types do not round-trip exactly:
readinfers them again (dates come back as text, for example).
from fione_sdk import Client, FioneError, JobFailed
fione = Client()
try:
fione.train(project_id, dataset_id, "species", max_runtime_secs=120).wait()
except JobFailed as e:
print(e.code, e.message) # "failed" or "cancelled", and the job's message
except FioneError as e:
print(e.status, e.code, e.message)For the endpoints behind these calls, and to call the API without Python, see the REST API.