opensi·si

Trackio is designed from the ground up to support autonomous ML experimentation driven by LLM agents. This guide covers how to structure your training code, configure alerts,…

ML Agents

Trackio is designed from the ground up to support autonomous ML experimentation driven by LLM agents. This guide covers how to structure your training code, configure alerts, and wire up the feedback loop so that an agent can launch experiments, monitor them, react to problems, and iterate on hyperparameters — all without human intervention.

Why Trackio for Agents?

Most experiment trackers assume a human is watching a dashboard. Trackio gives agents first-class programmatic access through multiple channels:

  • CLI with JSON output — every trackio command supports --json, making it trivial to parse in any language
  • Python API — trackio.Api() provides direct access to runs, metrics, and alerts
  • HTTP API / MCP — the Trackio dashboard exposes Gradio API endpoints, and can run as an MCP server so LLMs can call tools directly
  • Alerts with webhooks — agents can insert trackio.alert() calls like print statements and poll for them later
  • since filtering — efficient polling for new alerts without re-reading the full history

The Agent Feedback Loop

A typical autonomous experiment loop looks like this:

┌─────────────────────────────────────┐
│  1. Agent writes training script    │
│     with trackio.init(), log(),     │
│     and alert() calls               │
├─────────────────────────────────────┤
│  2. Agent launches the script       │
├─────────────────────────────────────┤
│  3. Agent polls for alerts and      │
│     metrics while training runs     │
├─────────────────────────────────────┤
│  4. Agent reads results, decides    │
│     next hyperparameters            │
├─────────────────────────────────────┤
│  5. Agent writes a new script       │
│     and repeats from step 1         │
└─────────────────────────────────────┘

The rest of this guide walks through each step with concrete code.

Step 1: Structuring Training Code for Agents

The key insight is that an agent can insert trackio.alert() calls the same way it would insert print() statements for debugging. Alerts are more structured than print statements: they have a title, optional description, severity level, and are automatically persisted and queryable.

Here is a training script written the way an agent would write it, with alerts at every decision point:

コード(86 行)
import trackio
import torch

trackio.init(
    project="cifar10-hparam-search",
    name="run-lr0.001-bs64",
    config={
        "learning_rate": 0.001,
        "batch_size": 64,
        "optimizer": "adamw",
        "epochs": 50,
        "weight_decay": 1e-4,
    },
)

model = build_model()
optimizer = torch.optim.AdamW(
    model.parameters(), lr=0.001, weight_decay=1e-4
)

best_val_loss = float("inf")
patience_counter = 0
patience_limit = 5

for epoch in range(50):
    train_loss = train_one_epoch(model, train_loader, optimizer)
    val_loss, val_acc = evaluate(model, val_loader)

    trackio.log({
        "train_loss": train_loss,
        "val_loss": val_loss,
        "val_accuracy": val_acc,
        "learning_rate": optimizer.param_groups[0]["lr"],
    })

    # Alert on loss divergence
    if train_loss > 10.0:
        trackio.alert(
            title="Training diverged",
            text=f"train_loss={train_loss:.4f} at epoch {epoch}. "
                 "Learning rate is likely too high.",
            level=trackio.AlertLevel.ERROR,
        )
        break

    # Alert when validation stops improving
    if val_loss < best_val_loss:
        best_val_loss = val_loss
        patience_counter = 0
        torch.save(model.state_dict(), "best_model.pt")
    else:
        patience_counter += 1
        if patience_counter >= patience_limit:
            trackio.alert(
                title="Early stopping triggered",
                text=f"No improvement for {patience_limit} epochs. "
                     f"Best val_loss={best_val_loss:.4f} at epoch "
                     f"{epoch - patience_limit}.",
                level=trackio.AlertLevel.WARN,
            )
            break

    # Alert on overfitting
    if epoch > 10 and (train_loss < 0.1 and val_loss > 1.5):
        trackio.alert(
            title="Overfitting detected",
            text=f"train_loss={train_loss:.4f} vs val_loss={val_loss:.4f}. "
                 "Consider adding regularization or reducing model capacity.",
            level=trackio.AlertLevel.WARN,
        )

    # Alert on good results
    if val_acc > 0.93:
        trackio.alert(
            title="High accuracy reached",
            text=f"val_accuracy={val_acc:.4f} at epoch {epoch}.",
            level=trackio.AlertLevel.INFO,
        )

trackio.alert(
    title="Training complete",
    text=f"Final val_loss={val_loss:.4f}, val_accuracy={val_acc:.4f}. "
         f"Best val_loss={best_val_loss:.4f}.",
    level=trackio.AlertLevel.INFO,
)
trackio.finish()

The alerts here are not just for humans — they are structured signals that the agent will read later to decide what to do next.

Guidelines for Agent-Friendly Alerts

  • Use ERROR for conditions that should stop the run (divergence, NaN loss, out of memory).
  • Use WARN for conditions that suggest the hyperparameters should change (overfitting, early stopping, slow convergence).
  • Use INFO for milestones (training complete, high accuracy reached, checkpoint saved).
  • Include numeric values in text so the agent can parse them and reason about them.
  • Include actionable suggestions in text (e.g., "Learning rate is likely too high") to help the agent decide what to change.

Step 2: Launching the Script

The agent can launch the script in a subprocess or background process. In most agent frameworks, this is as simple as running a shell command:

python train.py

If the agent is using an MCP-connected LLM, it can also launch scripts through a shell tool.

Step 3: Monitoring During Training

While training runs, the agent polls for alerts and metrics. The --since flag makes this efficient — only new alerts since the last check are returned.

Polling via CLI

# First poll — get all alerts
trackio get alerts --project "cifar10-hparam-search" --run "run-lr0.001-bs64" --json

# Subsequent polls — only new alerts
trackio get alerts --project "cifar10-hparam-search" --since "2025-06-15T14:30:00" --json

Polling via Python API

import trackio
from datetime import datetime, timezone

api = trackio.Api()
last_check = None

while training_is_running():
    alerts = api.alerts(
        "cifar10-hparam-search",
        run="run-lr0.001-bs64",
        since=last_check,
    )
    if alerts:
        last_check = alerts[0]["timestamp"]  # alerts are sorted newest-first
        for a in alerts:
            print(f"[{a['level'].upper()}] {a['title']}: {a['text']}")

            if a["level"] == "error":
                # Stop the run and re-plan
                handle_error(a)

    time.sleep(30)

Polling via MCP

If the Trackio dashboard is running as an MCP server, the agent can call the get_alerts tool directly through the MCP protocol. See Trackio as an API and MCP Server for setup instructions.

Step 4: Reading Results and Deciding Next Steps

After a run finishes, the agent reads the full results:

# Get run summary (metrics, config, step count)
trackio get run --project "cifar10-hparam-search" --run "run-lr0.001-bs64" --json

# Get the loss curve
trackio get metric --project "cifar10-hparam-search" --run "run-lr0.001-bs64" --metric "val_loss" --json

# Get all alerts (the most useful signal for decision-making)
trackio get alerts --project "cifar10-hparam-search" --run "run-lr0.001-bs64" --json

The alerts provide a concise summary of what happened during training. Instead of parsing thousands of metric values, the agent can read a handful of alerts to understand:

  • Did the run diverge? → Lower the learning rate
  • Did it overfit? → Add regularization or reduce capacity
  • Did it early-stop? → The hyperparameters are in the right ballpark but might need tuning
  • Did it reach high accuracy? → This configuration is working well

Step 5: Iterating on Hyperparameters

The agent uses the alerts from the previous run to choose new hyperparameters. Here is a concrete example of the decision logic an agent might follow:

import json
import subprocess
import trackio

api = trackio.Api()

# Read alerts from the last run
alerts = api.alerts("cifar10-hparam-search", run="run-lr0.001-bs64")

# Read the config from the last run
runs = api.runs("cifar10-hparam-search")
last_run = [r for r in runs if r.name == "run-lr0.001-bs64"][0]
config = last_run.config

# Decision logic based on alerts
new_config = dict(config)
for alert in alerts:
    if "diverged" in alert["title"].lower():
        new_config["learning_rate"] = config["learning_rate"] * 0.1
    elif "overfitting" in alert["title"].lower():
        new_config["weight_decay"] = config.get("weight_decay", 1e-4) * 10
    elif "early stopping" in alert["title"].lower():
        new_config["learning_rate"] = config["learning_rate"] * 0.5
    elif "high accuracy" in alert["title"].lower():
        # This config is good — try fine-tuning
        new_config["learning_rate"] = config["learning_rate"] * 0.5
        new_config["epochs"] = config["epochs"] + 20

The agent then generates a new training script with the updated config and launches it, repeating the loop.