Metadata-Version: 2.4
Name: agenticml-lite
Version: 3.0.0
Summary: Lean, local-first experiment tracker for AgenticML. Installs as `agenticml-lite`, imports as `agenticml`.
Author-email: Gaurav Singh <gaurav.singh@agenticml.xyz>
License: MIT
Project-URL: Homepage, https://agenticml.github.io/agenticml-lite/
Project-URL: Documentation, https://agenticml.github.io/agenticml-lite/
Project-URL: Source, https://github.com/agenticML/agenticml-lite
Project-URL: Issues, https://github.com/agenticML/agenticml-lite/issues
Keywords: mlops,experiment-tracking,machine-learning,agentic
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31
Provides-Extra: system
Requires-Dist: psutil>=5.9; extra == "system"
Provides-Extra: gpu
Requires-Dist: nvidia-ml-py>=12; extra == "gpu"
Provides-Extra: media
Requires-Dist: Pillow>=10.0; extra == "media"
Provides-Extra: firebase
Requires-Dist: PyJWT[crypto]>=2.8; extra == "firebase"
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
Provides-Extra: s3
Requires-Dist: boto3>=1.34; extra == "s3"
Provides-Extra: hosted
Requires-Dist: agenticml-lite[firebase,postgres,s3]; extra == "hosted"
Provides-Extra: dev
Requires-Dist: boto3>=1.34; extra == "dev"
Requires-Dist: moto[s3]>=5.0; extra == "dev"
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Requires-Dist: psutil>=5.9; extra == "dev"
Requires-Dist: Pillow>=10.0; extra == "dev"
Requires-Dist: responses>=0.24; extra == "dev"
Requires-Dist: PyJWT[crypto]>=2.8; extra == "dev"
Requires-Dist: psycopg[binary]>=3.1; extra == "dev"
Dynamic: license-file

# agenticml-lite

agenticml-lite is a local-first experiment tracker. Training writes metrics, config, code, and media to files on disk, and `agenticml ui` serves a TensorBoard-style dashboard from those files. There is no server, database, or Docker image to run. Upload to an `agenticml server` (self-hosted, or the hosted service in public preview) is optional, with `agenticml login` and `agenticml sync`. Install the package as `agenticml-lite` and import it as `agenticml`. PyPI has 3.0.0, which includes the server and the hosted service (see Install).

Documentation: <https://agenticml.github.io/agenticml-lite/>

## Install

```bash
pip install agenticml-lite

# Optional client extras
pip install "agenticml-lite[system]"   # psutil: CPU, memory, disk
pip install "agenticml-lite[gpu]"      # NVIDIA GPU metrics via pynvml
pip install "agenticml-lite[media]"    # Pillow, for numpy and PIL images

# Optional server extras
pip install "agenticml-lite[postgres]" # PostgreSQL database backend (psycopg)
pip install "agenticml-lite[s3]"       # Amazon S3 object storage (boto3)
pip install "agenticml-lite[firebase]" # Firebase Auth token verification (PyJWT)
pip install "agenticml-lite[hosted]"   # Full hosted bundle (postgres, s3, firebase)
```

`pip install agenticml-lite` installs 3.0.0. The server extras and syncing to a server need 3.0 (1.0.0, the old local-only release, cannot sync). To also sample CPU, memory and disk metrics:

```bash
pip install 'agenticml-lite[system]'
```

## Quickstart

```python
import agenticml

agenticml.init(
    project="demo",
    name="exp1",
    config={"learning_rate": 0.01, "epochs": 10},
    tags=["baseline"],
)

for step in range(10):
    agenticml.log({"loss": 1 / (step + 1), "accuracy": step / 10}, step=step)

agenticml.summary["best_loss"] = 0.1
agenticml.finish()
```

`init(project, name, ...)` starts the one active run. Omit `project` and it defaults to the repository or directory name (`AGENTICML_PROJECT` overrides that; an explicit project wins). Omit `name` and it defaults to the main script's path relative to the repo root (e.g. `scripts/train.py`), or its absolute path outside a repo (empty without a main file). `log` advances the step when `step` is omitted; `commit=False` merges later metrics into the same step. `config` and `summary` are dicts on the active run. `init(verbose=True)` prints the run id, the run directory, and the `agenticml ui` command.

`init` also turns on runtime code snapshots and PyTorch component detection (`auto_track=True`). Automatic loss / learning-rate / epoch metrics and TensorBoard mirroring stay off until you pass `auto_metrics=True` and `sync_tensorboard=True`. System metrics are on (every 10 seconds) when `psutil` is installed; `system_metrics=False` disables them.

```python
agenticml.log({"pred": agenticml.Image("pred.png", caption="val")})
agenticml.log_artifact("model.pt", name="checkpoint")          # reference
agenticml.log_artifact("model.pt", name="checkpoint", copy=True)  # snapshot bytes
agenticml.track_model(model)  # after the object exists
```

`Image` accepts a path, bytes, a file object, a PIL image, or a numpy array. Numpy arrays and PIL images need the `media` extra. `track_optimizer`, `track_loss`, and `track_dataloader` work the same way as `track_model`.

## Zero-code

`agenticml run` executes a script inside a run. The script can omit `import agenticml`.

```bash
agenticml run --project demo -- python train.py --lr 1e-3
agenticml python train.py --lr 1e-3          # same interpreter, or re-exec
agenticml run -m mypkg.train --epochs 3
agenticml run -- python examples/train_toy.py --lr 0.05 --epochs 5
```

### Command forms

There are several ways to write the same launch. All of them run the target in-process as `__main__` inside one tracked run. The `run` forms take agenticml options; the bare `agenticml python` form does not, so set `AGENTICML_*` environment variables there. They differ in how you name the interpreter and the target, so pick the one that matches how you already start training.

| Form | Use it when | Equivalent to |
| --- | --- | --- |
| `agenticml run train.py [args]` | You just want to track a script with the current interpreter. Shortest form. | `agenticml run -- python train.py [args]` |
| `agenticml run -m pkg.train [args]` | Your entry point is a module (`python -m pkg.train`), so relative imports and package layout keep working. | `agenticml run -- python -m pkg.train [args]` |
| `agenticml run -- python train.py [args]` | You are wrapping an existing command line, for example from a Makefile, a shell script or a README. Swap `python` for `agenticml run --` and nothing else changes. | `agenticml python train.py [args]` |
| `agenticml python train.py [args]` | You want the least typing and no `run` or `--`. It reads as "python, but tracked". Options come from `AGENTICML_*` variables. | `agenticml run -- python train.py [args]` |
| `agenticml run --project demo -- python -u train.py` | You need Python flags (`-u`, `-X`, `-W`, ...) or a specific interpreter such as `python3.11` or a venv's `python`. Agenticml re-launches itself under that interpreter, so `agenticml-lite` must be installed there. | `agenticml python -u train.py` (options via env vars) |
| `python -m agenticml run train.py` | `agenticml` is not on `PATH` (for example inside `torchrun`, `accelerate launch`, or a scheduler that takes a Python command). | `agenticml run train.py` |

Rules that apply to every form:

- Agenticml options (`--project`, `--name`, ...) must come before the script or module. Everything after the target is the script's own argv, passed through untouched.
- With `run`, the `--` separator is optional when the target is a bare script or `-m` module. It is needed in front of `python ...` so that the options before it are not read as Python flags.
- The default run name is the script's repo-relative path (e.g. `scripts/train.py`), or the module's file path for `-m`, unless `--name` is given.
- `python -c "..."` and reading the script from stdin are not supported. Put the code in a file.
- Only Python targets are supported. To track a shell script, call `agenticml run -- python ...` from inside it.
- Multi-GPU: launch as `torchrun ... -m agenticml run -- train.py`. Only rank 0 logs.

Options go before the script; everything after it is the script's own argv. See `agenticml run -h`. A CLI flag overrides its environment variable; a blank environment variable counts as unset. Repeatable flags replace (rather than extend) any environment variable list. There is no positive override flag: once a feature is disabled via its environment variable (such as `AGENTICML_SYSTEM_METRICS=0` or `AGENTICML_ALL_RANKS=1`), the CLI cannot re-enable it; unset the variable instead.

`--project`, `--name`, `--tags`, `--notes`, `--group`, `--job-type`, `--mode`, `--dir`, and `--log-every` read `AGENTICML_PROJECT`, `AGENTICML_NAME`, `AGENTICML_TAGS`, `AGENTICML_NOTES`, `AGENTICML_GROUP`, `AGENTICML_JOB_TYPE`, `AGENTICML_MODE`, `AGENTICML_DIR`, and `AGENTICML_LOG_EVERY`. `--verbose` has no variable. `--all-ranks` (`AGENTICML_ALL_RANKS=1`) tracks every distributed rank instead of rank 0 only. `--flush-interval` (`AGENTICML_FLUSH_INTERVAL`, default 2 s) sets the background flush interval.

`--config KEY=VALUE` (repeatable) passes explicit config values. `VALUE` parses as JSON when possible (`lr=1e-3` -> 0.001, `amp=true` -> true, `layers=[64,64]` -> list), else stays a string (`opt=adam`); quote to force a string (`--config 'tag="1e-3"'`). `NaN` and `Infinity` are rejected (exit 2). Later occurrences of a key win. `--config-file PATH` (`AGENTICML_CONFIG_FILE`) reads config from a JSON file with a top-level object. Merge precedence: config file < `--config` pairs < the script's own `init(config=...)`. These explicit keys are never overwritten by `argparse` or Hydra. Example:
```bash
agenticml run --config lr=1e-3 --config amp=true --config-file base.json -- python train.py
```

`--id RUN_ID` (`AGENTICML_RUN_ID`) and `--resume MODE` (`AGENTICML_RESUME`: `never`, `allow`, `must`) resume or name a run. `--id` requires `--resume allow` or `must`, and `--resume allow` or `must` requires `--id` (exit 2 otherwise). `must` requires the run to exist; `allow` resumes or creates it. A resumed run keeps its stored project, name, task, and parent (a differing `--parent` warns). Steps continue from the last stored step, and new config values merge over stored config. If the run cannot be resumed (missing under `must`, open in another process, pruned by `sync --prune`, or missing `meta.json`), `agenticml run` prints an error and exits 2 without running the script. An in-script `init(id=..., resume=...)` is ignored with a warning under `agenticml run`. Example:
```bash
agenticml run --id 20261101T130355-1cded4a7 --resume must -- python train.py
```

Code and environment capture switches: `--no-code` (`AGENTICML_TRACK_CODE=0`) disables source code tracking (`track_source=False`). `--track-file PATH` (repeatable; env `AGENTICML_TRACK_FILES`, path-separated) tracks additional source files. `--source-root DIR` (repeatable; env `AGENTICML_SOURCE_ROOTS`, path-separated) adds source directories. `--max-file-bytes N` (`AGENTICML_MAX_FILE_BYTES`, default 10 MiB) and `--max-total-bytes N` (`AGENTICML_MAX_TOTAL_BYTES`, default 100 MiB) cap snapshot sizes. `--no-lineage` (`AGENTICML_LINEAGE=0`) turns off shadow-Git lineage snapshots. `--no-env` (`AGENTICML_CAPTURE_ENV=0`) disables environment metadata. `--no-system-metrics` (`AGENTICML_SYSTEM_METRICS=0`) turns off CPU/GPU/memory sampling, and `--system-metrics-interval S` (`AGENTICML_SYSTEM_METRICS_INTERVAL`, default 10 s) sets the sample interval. Defaults differ between the SDK and CLI: `auto_metrics` and `sync_tensorboard` are off by default in `agenticml.init()` and on under `agenticml run` (disable with `--no-auto-metrics`, `--no-tensorboard`).

`--task` sets the run's task and overrides `AGENTICML_TASK`, the parent's task, an `agenticml.toml` `task`, and the entry script's folder (see [docs/SDK.md](docs/SDK.md)). With an explicit parent that is readable, in the same project, and has a task, a differing `--task` or valid `AGENTICML_TASK` logs a warning that the lineage link crosses tasks. `--allow-cross-task` or `AGENTICML_ALLOW_CROSS_TASK=1` silences it.

`--parent RUN_ID` (env `AGENTICML_PARENT`) selects an explicit lineage parent. New runs inherit the parent's task unless `--task` or a valid `AGENTICML_TASK` supplies one. A parent in another project is recorded, but its task is not inherited. An invalid `--parent` / `AGENTICML_PARENT` is a usage error (exit 2). `--parent` only applies to new runs: a resumed run keeps its stored parent, with a warning if it differs.

| What | Where it comes from | Turn off |
| --- | --- | --- |
| Config | `argparse` parses of `sys.argv`, and `@hydra.main` | `--no-capture-args` (`AGENTICML_CAPTURE_ARGS=0`) |
| Code snapshot | imported project modules and files opened for reading | `--no-code` (`AGENTICML_TRACK_CODE=0`; `track_source=False` on `Run`) |
| Model, optimizer, loss, dataloader | PyTorch construction hooks | `--no-auto-track` (`AGENTICML_AUTO_TRACK=0`) |
| `auto/loss`, `auto/lr`, `auto/epoch` | `backward()` and `optimizer.step()` | `--no-auto-metrics` (`AGENTICML_AUTO_METRICS=0`); `--log-every N` |
| TensorBoard | `SummaryWriter` / `tensorboardX` (scalars, images, figures, hparams) | `--no-tensorboard` (`AGENTICML_SYNC_TENSORBOARD=0`) |
| System metrics | psutil, plus pynvml when installed | `--no-system-metrics` (`AGENTICML_SYSTEM_METRICS=0`; `--system-metrics-interval S`) |

Loss is unscaled under `GradScaler` and averaged over gradient-accumulation steps. Several optimizers are prefixed (`auto/<name>/loss`, `auto/<name>/lr`); `auto/epoch` stays unprefixed. TensorBoard event files are still written. Keys passed to `init(config=...)` win over captured hyperparameters.

A script that calls `agenticml.init()` joins the launcher's run. Exit 0 finishes as `finished`; any other exit finishes as `crashed`, with `_exit_code` and `_exception` in the summary. The script's exit code is preserved. SIGTERM finishes the run and exits 143.

The zero-code toy example captures config, code and system information, but no training metrics: its pure-Python loop has no framework hooks. `examples/train_toy.py --explicit` is the same loop calling the Python API itself to log metrics. See [examples/README.md](examples/README.md).

## Viewing

```bash
agenticml ui          # http://127.0.0.1:6006
agenticml ls          # newest first
agenticml ls --project demo --json
agenticml show RUN_ID
agenticml show RUN_ID --json
agenticml export RUN_ID --format csv -o metrics.csv
agenticml export RUN_ID --key loss --key acc --format json
agenticml ui --open --port 6006 --host 127.0.0.1
agenticml ui --read-only
```

`agenticml ui` binds to `127.0.0.1` and port 6006. On loopback it answers only loopback `Host` headers. `--dir` selects the store (else `AGENTICML_DIR`, else `~/.agenticml`). `ls` prints run id, project, name, status, created time, and last step. A run stays `running` while its lifetime lock is held, even when it logs infrequently. If the lock is free, it is shown as `crashed`; sync finalizes it with `_exit_reason: "process died"`. On filesystems without locking, mtimes older than 120 seconds are the fallback for `stale` status.

`agenticml show` displays run metadata (run, project, name, status, task, created, parent, and tags/group/job type/notes when set), config (internal keys starting with `_` hidden), summary, metrics table (KEY, LAST, STEP, POINTS), artifacts table (NAME, TYPE, VERSION, SIZE, PATH), and media item counts. `--json` outputs a strict JSON object (non-finite values become `null`). LAST/STEP reflect the last record written; for series pruned by `sync --prune`, they are the largest step and last finite value from the overview. Missing runs or corrupt metadata print one line to stderr and exit 1.

`agenticml export` exports full raw metric series. Default output is CSV (`key,step,value` in file order, float32 formatted exactly, non-finite values as `nan`, `inf`, `-inf`). `--format json` outputs `{"run_id": ..., "series": {key: [[step, value], ...]}}` with non-finite values as `null`. Filter series with repeatable `--key K`. `-o PATH` writes to a file instead of stdout. Unknown keys fail before writing (exit 1). Series pruned by `sync --prune` are skipped with a warning; if all selected series were pruned, it exits 1.

The dashboard pages do not show run notes. Launch notes (`--notes` / `init(notes=)`) are still stored with the run, and the server keeps the `/api/runs/<id>/notes` endpoint, which is the only write it accepts; `--read-only` disables it (recommended when exposing a non-loopback `--host`).

## Editing ended runs

Ended runs can be modified from the CLI. `edit`, `artifact add`, and `finish` refuse live runs whose lock is held (exit 1). They never mark a run running and never refresh its heartbeat. Changes are uploaded by the next `agenticml sync` (including for already-synced runs). Runs pruned by `sync --prune` cannot be edited.

```bash
agenticml edit RUN_ID --tag best --summary test_acc=0.913 --group sweep-3
agenticml artifact add RUN_ID model.pt --name checkpoint --copy
agenticml finish RUN_ID --status crashed
agenticml note RUN_ID --set "Checked checkpoint at step 10k"
```

- `agenticml edit RUN_ID`: updates run metadata. `--tag T` and `--untag T` are repeatable (add if absent / remove every occurrence). `--notes TEXT` sets the launch note (`""` clears it). `--group NAME` and `--job-type NAME` set group and job type (cannot be cleared). `--config KEY=VALUE` and `--summary KEY=VALUE` merge values using the same JSON/string parsing rules as `run --config`. `--unset-summary KEY` removes a summary key. Project, name, task, parent, and id cannot be changed.
- `agenticml artifact add RUN_ID PATH`: records an artifact on an ended run (`--name` defaults to file stem, `--type` defaults to `file`, `--metadata` accepts a JSON object). `--copy` stores bytes in `objects/`; otherwise only path, size, and mtime are recorded. Version increments per name.
- `agenticml finish RUN_ID --status finished|crashed`: sets the final status of a run left `running`, `stale`, or `crashed` (or switches between finished and crashed), keeping its summary and writing overviews and `finished_at`. If already that status, prints a message and exits 0.
- `agenticml note RUN_ID`: reads or writes the run's local Markdown note (`runs/<id>/notes.md`) using `--set TEXT`, `--file PATH` (`-` for stdin), or `--clear`. The notepad is not synced to the server. Works even while the run is live. Without options, prints the note (or the launch note if no notepad exists). Note that `note` operates on the local note file, whereas `edit --notes` updates the synced launch note.

## Where data lives

The store root is `init(dir=...)`, else `AGENTICML_DIR`, else `~/.agenticml`. Layout (details in [docs/FORMAT.md](docs/FORMAT.md)):

```
<root>/
  objects/<hh>/<sha256>          content-addressed bytes, shared by every run
  runs/<run_id>/
    meta.json                    project, config, status, summary, env, git
    events.jsonl                 config updates, code, artifacts, finish
    notes.md                     run note (Markdown, up to 256 KiB)
    sync.json                    upload cursor per server and workspace, after a sync
    scalars/<id>.bin             8 bytes per point: uint32 step, float32 value
    scalars/<id>.ovw             overview, at finish, if the series has > 65536 points
    scalars/_time.bin            one record per scalar flush
    scalars/index.json
    media/index.json
```

New run ids look like `20261027T021500-ab12cd34` (UTC). Each scalar point is 8 bytes in `<id>.bin`. An overview is written at finish only when a series has more than 65,536 points, and it is at most 40 + 36×2048 = 73,768 bytes. Worst-case overview overhead is about 14% of the raw series (the 73,768-byte cap next to a 65,537-point `<id>.bin`); the share falls as the series grows, to about 0.6 B/pt past ~120,000 points. At or below 65,536 points the reader builds the overview from `<id>.bin` on demand. TensorBoard tfevents are ~51 B/pt, and the old JSONL journal was ~57 B/pt.

Code snapshots and media are stored once, keyed by SHA-256. The same bytes logged again share one object. Default snapshot caps are 10 MB per file and 100 MB total. Media indexes retain at most 64 rows per key by default, thinning older rows as new media arrives (`AGENTICML_MEDIA_MAX_PER_KEY` overrides the cap). Artifacts are a path, size, and mtime unless `copy=True`, which hashes the bytes into `objects/`.

## Disk

```bash
agenticml du
agenticml gc --dry-run
agenticml gc --older-than DAYS --keep-last N
agenticml gc --include-unsynced
agenticml sync --all --prune
```

`agenticml du` reports how much space the local store uses. `agenticml gc` removes runs. Only synced runs are eligible unless you pass `--include-unsynced`. `--older-than` and `--keep-last` narrow the set. `--dry-run` prints the plan and deletes nothing. `agenticml sync --prune` drops raw `<id>.bin` files for series that already have an overview; series of 65,536 points or fewer keep their `.bin` (≤ 512 KB each). A pruned run cannot be resumed or synced to another host, or uploaded again after `sync --reset`. Unreferenced objects have a one-hour grace period before gc removes them. Agenticml warns when the store exceeds `AGENTICML_MAX_BYTES` (default 5 GiB).

## Upload

```bash
agenticml login --host https://aml.example.com
agenticml whoami
agenticml logout
agenticml sync RUN_ID [RUN_ID ...]
agenticml sync --all
agenticml sync --all --watch 30 --dry-run
agenticml sync RUN_ID --reset
```

`login` checks the key (skip with `--no-verify`) and writes `~/.config/agenticml/credentials.json` at mode `0600`. The directory is `AGENTICML_CONFIG_DIR`, else `$XDG_CONFIG_HOME/agenticml`, else `~/.config/agenticml`. `AGENTICML_HOST` has no default; `login` requires `--host` unless a default host is already saved. Use the `agenticml login` prompt to enter the key, or `AGENTICML_API_KEY` for sync. Avoid command-line `--key` / `--api-key`: their values are visible in `ps`. `login` also accepts stdin. `sync` sends runs to an `agenticml server` over [protocol v2](docs/PROTOCOL.md). `sync` takes the key from `--api-key`, then `AGENTICML_API_KEY`, then the file. `whoami` uses `AGENTICML_API_KEY`, then the file. `whoami --offline` skips the server check. `logout` removes the saved key for one host. On `login`, `whoami`, and `sync`, `--insecure` allows `http://` to a non-local host; localhost does not need it.

Sync copies each run's store files byte for byte (`meta.json`, `events.jsonl`, scalars, overviews, indexes) plus the objects they reference (code, media, copied artifacts) to an `agenticml server` over [protocol v2](docs/PROTOCOL.md). A per-file cursor in `runs/<id>/sync.json` tracks accepted bytes, so an interrupted sync resumes from the last accepted request. `--all` selects runs that are incomplete or changed. `--watch N` repeats every N seconds until every selected run has synced, failed permanently, or gone stale. `--dry-run` prints counts without sending or saving state. `--reset RUN_ID ...` forgets those runs' cursors for this host, in every workspace, and the next sync resumes from the server's copy (rejects `--all`). The cursor is kept per server and workspace, so one store can sync a run to several workspaces of one server, each with its own key.

Not uploaded: notes (`notes.md`). Lineage code is uploaded to servers that support it, and by-reference (`copy=False`) artifacts are uploaded only with `sync --artifacts`. A run id already owned by another user on the server fails with an error naming that user (`run id <id> belongs to user <name> on this server`). Ownership is per user, so any key of the owning user may write to the run. See [docs/PROTOCOL.md](docs/PROTOCOL.md) for protocol details.

## On-prem server

The server runs on your own machines (or as our hosted service on AWS) to provide a shared web dashboard and synchronization endpoint. Server state lives in a SQL database (SQLite by default, or PostgreSQL), with experiment files and lineage on disk (or EFS) and content-addressed objects on disk or in Amazon S3. See [docs/SERVER.md](docs/SERVER.md) for the complete reference, [docs/HOSTED.md](docs/HOSTED.md) for hosted operations, and [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) for security.

### Start the server

Install `agenticml-lite` into a virtual environment on a POSIX host (Python 3.10+):

```bash
sudo python3 -m venv /opt/agenticml
sudo /opt/agenticml/bin/python -m pip install agenticml-lite

# Optional: PostgreSQL backend, S3 objects, or Firebase authentication
sudo /opt/agenticml/bin/python -m pip install "agenticml-lite[postgres,s3]"
```

Run directly:
```bash
/opt/agenticml/bin/agenticml server serve --data DIR --host 127.0.0.1 --port 8080 --public-url https://...
```
`--data` falls back to `AGENTICML_SERVER_DATA`, then `~/.agenticml-server`. `--database` defaults to SQLite at `<data>/server/agenticml.db`, or accepts PostgreSQL (`postgresql://...`). `--objects` defaults to `file://` (local disk) or accepts Amazon S3 (`s3://bucket/prefix`). `--public-url` falls back to `AGENTICML_SERVER_PUBLIC_URL`.

Or run as a systemd service: see [deploy/systemd/README.md](deploy/systemd/README.md) and [deploy/systemd/agenticml-server.service](deploy/systemd/agenticml-server.service).
```bash
sudo useradd --system --home /var/lib/agenticml-server --shell /usr/sbin/nologin agenticml
sudo curl -fsSL -o /etc/systemd/system/agenticml-server.service https://raw.githubusercontent.com/agenticML/agenticml-lite/v3.0.0/deploy/systemd/agenticml-server.service
```
The unit is fetched from the `v3.0.0` tag. Use the tag that matches the agenticml-lite version you installed (`pip show agenticml-lite`). Edit `AGENTICML_SERVER_PUBLIC_URL` in the unit (or `sudo systemctl edit agenticml-server`), then `daemon-reload` and `enable --now`:
```bash
sudo systemctl daemon-reload
sudo systemctl enable --now agenticml-server
```

Put a TLS reverse proxy in front:
- **Workstation:** `agenticml server up` makes the server reachable from the public internet through Tailscale Funnel. Manual steps: `tailscale serve --bg 8080` and set `AGENTICML_SERVER_PUBLIC_URL=https://<machine>.<tailnet>.ts.net`.
- **Production:** Caddy, Nginx, or an AWS Application Load Balancer. Set the public URL to the proxied HTTPS URL.

### Workspaces and roles

All experiment runs, API keys, and memberships belong to a **workspace**:
- Workspaces provide full data isolation on a single hostname. Dashboard URLs are prefixed with `/w/<slug>/` (e.g. `/w/default/`).
- Roles per workspace: `owner` (creator; cannot be removed), `admin` (manages members, keys, invites), `member` (syncs runs, edits notes), `viewer` (read-only dashboard).
- Manage workspaces via CLI: `agenticml server workspaces {list,create,rename,suspend,resume,delete,usage,set-plan}`.

### First admin account and sign in

When starting with an empty data directory, read the setup link from the server's terminal output, or from the journal under systemd:
```bash
sudo journalctl -u agenticml-server
```
Look for:
```
No admin key yet. Open <url>/setup?token=<token> to create one, or run: agenticml server keys create --name admin --scope admin
```
Open `/setup?token=<token>` in a browser to create your administrator key and sign in.

CLI alternative (creates an account and invite in the default workspace):
```bash
agenticml server users add admin --role admin --data /var/lib/agenticml-server
```

### Issue a sync key per training machine

Every API key is bound to a specific workspace and owning account. On sync (`/v2`), the server identifies the workspace directly from the key.

In the dashboard, open **Settings** > **API keys** > **New key**, name it (e.g. `gpu-box-1`), and copy the key (not the command).

CLI alternative:
```bash
agenticml server keys create --name gpu-box-1 --workspace default --data /var/lib/agenticml-server
```
The plaintext key is printed once.

### Set up each training machine

On each training machine (Python 3.10+):
```bash
pip install agenticml-lite
agenticml login --host https://...
```
Paste the key at the prompt; do not pass `--key` on the command line (visible in `ps`).

Verify authentication:
```bash
agenticml whoami
```
The response displays your key name, user account, role, and bound workspace slug.

Sync runs once, or follow continuously:
```bash
agenticml sync --all       # sync all incomplete or changed runs once
agenticml sync --follow    # keep syncing active and new runs
```
`--follow` picks up new runs, heartbeats running runs at least every 60 s, and backs off up to 5 min while the server is down. If a workspace reaches its storage limit, `--follow` automatically pauses and retries every 10 minutes until quota is raised.

### Back up

Take a consistent backup of a running server without stopping service:
```bash
agenticml server backup --to /backups/20261109-0000
```
The command snapshots the SQLite database (or requires `pg_dump` first with `--files-only` for PostgreSQL) and copies each run file up to its committed size recorded in the database.

Restore SQLite:
```bash
agenticml server serve --data /backups/20261109-0000
```
Restore PostgreSQL: restore the dump with `pg_restore`, then run `agenticml server serve --data /backups/20261109-0000 --database "$DATABASE_URL"`.

### Upgrade from 2.x to 3.0

Back up first.

When a 3.0 server starts against an existing 2.x data directory, it automatically converts the data in place into the `default` workspace:
- Accounts, keys, audit events, runs, and committed sizes migrate into the database.
- 2.x files are renamed with a `.2x` extension (`users.json.2x`, `keys.json.2x`, `audit.jsonl.2x`).
- If old 2.x files reappear alongside converted state, the server refuses to start twice to protect against data overwrites.
- Existing 2.2 sync clients continue syncing to 3.0 without changes.

## Configuration

| Variable | Default | Purpose |
| --- | --- | --- |
| `AGENTICML_DIR` | `~/.agenticml` | Store root. `init(dir=)` and `--dir` win. |
| `AGENTICML_MODE` | `local` | `local`, `offline` (alias of `local`), or `disabled`. Other values warn and use `local`. |
| `AGENTICML_HOST` | unset | Server for `login`, `whoami`, and `sync`. |
| `AGENTICML_API_KEY` | unset | Key for `sync` and `whoami`. `login` ignores it. |
| `AGENTICML_CONFIG_DIR` | `~/.config/agenticml` | Credential directory. Wins over `XDG_CONFIG_HOME`. |
| `AGENTICML_MAX_BYTES` | 5 GiB | Warn when the local store is larger than this. Nothing is deleted automatically. |
| `AGENTICML_MEDIA_MAX_PER_KEY` | `64` | Media index rows kept per key. Further rows are thinned by step. |
| `AGENTICML_MEDIA_MAX_PX` | `1024` | Longest side of a logged image, when Pillow is installed. |

`agenticml run` settings use the variables listed under [Zero-code](#zero-code). Boolean switches treat `0`, `false`, `no`, and `off` as off.

## Performance

From `python scripts/bench.py --quick` on one machine. Timings and bytes/point move with CPU, disk, and Python.

| Metric | This run | Target |
| --- | --- | --- |
| `import agenticml` (median of 5) | 39.4 ms | < 100 ms |
| `log()` ×10 scalars, median (10,000 calls) | 2.70 µs | < 10 µs |
| `log()` ×10 scalars, p99 | 8.91 µs | |
| disk, whole `scalars/` dir (100,000 points) | 8.01 B/pt | ≤ 9.0 B/pt (8 B raw + overview) |
| UI cold start, `/api/runs` (101 runs) | 8 ms | < 1 s |
| scalar request, 100,000-point series (median of 20) | 14.16 ms | < 20 ms |
| TensorBoard tfevents | not installed | |

The disk row is ten series of 10,000 points. Each series is under 65,536 points, so finish writes no overview and the directory stays at 8.01 B/pt, inside the 9.0 B/pt check. A series past 65,536 points adds one overview of at most 73,768 bytes. `python scripts/bench.py` without `--quick` uses 100,000 log calls, a 1,000,000-point run, and 1,000 small runs.

## Distributed, resume, disabled

Rank 0 logs. `init(only_main_process=True)` (the default) gives every other rank a no-op run, using `RANK`, `PMI_RANK`, `OMPI_COMM_WORLD_RANK`, `SLURM_PROCID`, then `LOCAL_RANK`. Pass `--all-ranks` or set `AGENTICML_ALL_RANKS=1` to track every distributed rank instead (`only_main_process=False` in Python). Put the tracker inside the launcher so every rank runs the script:

```bash
torchrun --nproc_per_node 4 -m agenticml run -- train.py
```

Resume with the same id. `resume="must"` errors if it is missing; `resume="allow"` opens it or creates it. The default `resume="never"` rejects an `id`. A pruned run (overview present, raw series file gone) cannot be resumed.

```python
agenticml.init(project="demo", name="exp1", id=run_id, resume="allow")
```

Under `agenticml run`, use `--id` and `--resume`:

```bash
agenticml run --id 20261101T130355-1cded4a7 --resume must -- python train.py
```

`--id` requires `--resume allow` or `must` (env `AGENTICML_RUN_ID` and `AGENTICML_RESUME`). A resumed run retains its stored project, name, task, and parent (a differing `--parent` warns). If the run cannot be resumed (missing under `must`, open in another process, pruned by `sync --prune`, or missing `meta.json`), `agenticml run` prints an error and exits 2 without running the script.

`mode="disabled"` or `AGENTICML_MODE=disabled` makes `log`, `finish`, artifacts, and the `track_*` helpers no-ops. With `verbose=True`, init prints `agenticml: tracking disabled`.

## Development

```bash
pip install -e ".[dev]"
pytest
python scripts/bench.py --quick
```

## Releasing

Bump the version in `pyproject.toml` and `src/agenticml/__init__.py`, then push a `v*` tag.

- **TestPyPI dry run:** run the "Publish to TestPyPI" workflow by hand from the Actions tab. Re-running with a version that is already there is a no-op.
- **PyPI:** `publish.yml` publishes to PyPI with Trusted Publishing (no API tokens) when the tag matches the package version.

```bash
# bump version in pyproject.toml and src/agenticml/__init__.py
git commit -am "release: v3.0.0"
git tag v3.0.0
git push origin v3.0.0
```

## License

MIT — see [LICENSE](LICENSE).
