//WIP
π Languages: This README is being translated under
docs/i18n/. Available so far: EspaΓ±ol (partial). Seedocs/i18n/README.mdto add a locale.
AstroML is a research-driven Python framework for building dynamic graph machine learning models on the Stellar Development Foundation Stellar blockchain.
It treats blockchain data as a multi-asset, time-evolving graph, enabling advanced ML research on transaction networks such as fraud detection, anomaly detection, and behavioral modeling.
AstroML provides end-to-end tooling for:
- Ledger ingestion and normalization
- Dynamic transaction graph construction
- Feature engineering for blockchain accounts
- Graph Neural Networks (GNNs)
- Self-supervised node embeddings
- Anomaly detection
- Temporal modeling
- Reproducible ML experimentation
- LLM Agent Framework for multi-step reasoning and autonomous task execution
AstroML now includes a powerful LLM Agent Framework for autonomous task execution and multi-step reasoning:
- Multi-step reasoning with think-act-observe loops
- Task planning with automatic decomposition
- Tool calling for autonomous execution
- Memory management with conversation and vector storage
- Pre-configured agents for fraud detection and model training
# Interactive agent mode
python -m astroml agent interactive --agent-type fraud-detection
# Run a single task
python -m astroml agent run \
--agent-type model-training \
--task "Train a fraud detection model" \
--verbose
# List available tools
python -m astroml agent list-toolsSee AGENTS_FRAMEWORK.md for complete documentation.
Blockchain networks are naturally graph-structured systems:
| Blockchain Concept | Graph Representation |
|---|---|
| Accounts | Nodes |
| Transactions | Directed edges |
| Assets | Edge types |
| Time | Dynamic dimension |
Most analytics tools rely on static heuristics or SQL queries.
AstroML instead enables:
- Dynamic graph learning
- Temporal GNNs
- Representation learning
- Research-grade experimentation
AstroML is designed for:
- ML researchers
- Graph ML engineers
- Fraud detection teams
- Blockchain data scientists
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AstroML: Ingestion β Graph β Train β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββ
β Stellar β
β Ledgers β
ββββββββ¬ββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β 1. INGESTION LAYER β
β ββ Ledger backfill (Polars) β
β ββ Incremental ingestion β
β ββ State tracking (idempotent)β
β ββ PostgreSQL storage β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β 2. NORMALIZATION LAYER β
β ββ Raw Stellar schema β
β β (Ledger, Transaction, Op) β
β ββ Graph mirror layer β
β β (GraphAccount, GraphEdge) β
β ββ Composite indexes β
β (account_id, timestamp) β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β 3. GRAPH BUILDING LAYER β
β ββ Time-windowed snapshots β
β ββ Edge construction β
β ββ Node indexing β
β ββ Graph validation β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β 4. FEATURE ENGINEERING β
β ββ Transaction frequency β
β ββ Asset diversity β
β ββ Structural importance β
β β (degree, betweenness, PR) β
β ββ Feature store & versioning β
β ββ Point-in-time queries β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β 5. TRAINING LAYER β
β ββ Temporal train/test split β
β ββ Link prediction task β
β ββ Negative sampling β
β ββ PyTorch Geometric models β
β β (GCN, GraphSAGE, GAT) β
β ββ Early stopping β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β 6. BENCHMARKING & EVALUATION β
β ββ Reproducible configs β
β ββ Random seed tracking β
β ββ Metric computation β
β β (AUC, Precision, Recall) β
β ββ Memory profiling β
β ββ Result persistence β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββΌβββββββ
β Baseline β
β Results β
βββββββββββββββ
Stellar Ledger Data
β
[Ingestion Service]
ββ Fetch ledgers (1000000-1100000)
ββ Track state (.astroml_state/ingestion_state.json)
ββ Store in PostgreSQL
β
[Database Schema]
ββ Raw Layer: Ledger, Transaction, Operation, Account, Asset
ββ Graph Layer: GraphAccount, GraphEdge, GraphTransactionDetail
ββ Indexes: (account_id, timestamp) composite
β
[Graph Snapshot]
ββ Query operations by time window
ββ Create Edge objects (src, dst, timestamp, asset, amount)
ββ Build node_index mapping
ββ Validate graph (isolated nodes, self-loops, density)
β
[Feature Store]
ββ Compute node features (frequency, diversity, centrality)
ββ Compute edge features (asset type, amount, direction)
ββ Version features with metadata
ββ Store in SQLite + Parquet
β
[Temporal Split]
ββ Sort edges by timestamp
ββ Split at cutoff (80% train, 20% test)
ββ Ensure no future data leaks into training
β
[Link Prediction Task]
ββ Context window: edges before cutoff
ββ Future window: edges after cutoff
ββ Positive labels: future edges
ββ Negative sampling: random non-edges
ββ Binary classification objective
β
[Model Training]
ββ LinkPredictor(encoder + decoder)
ββ Adam optimizer with early stopping
ββ Compute AUC, Precision, Recall, F1
ββ Track training/validation losses
β
[Benchmark Results]
ββ config.json (full configuration + seed)
ββ result.json (metrics + performance)
ββ metadata.json (run_id, timestamp, linking files)
astroml/
βββ ingestion/ # Ledger ingestion & state tracking
β βββ service.py # IngestionService (incremental, idempotent)
β βββ state.py # StateStore (tracks processed ledgers)
β βββ backfill.py # Bulk ledger loading
βββ db/ # Database layer
β βββ schema.py # SQLAlchemy ORM models
β βββ session.py # Database connection management
βββ features/ # Feature engineering
β βββ feature_store.py # Enterprise feature management
β βββ graph/
β β βββ snapshot.py # Time-windowed graph construction
β βββ frequency.py # Transaction frequency features
β βββ asset_diversity.py
β βββ gnn/ # Graph neural network layers
βββ models/ # ML models
β βββ link_predictor.py
β βββ gcn.py
β βββ sage.py
β βββ deep_svdd.py
βββ tasks/ # Training tasks
β βββ link_prediction_task.py
βββ training/ # Training utilities
β βββ temporal_split.py # Prevent data leakage
β βββ train_link_prediction.py
βββ benchmarking/ # Benchmarking framework
β βββ core.py # ModelBenchmark orchestrator
β βββ config.py # Configuration management
β βββ metrics.py # Metric computation
βββ quick_start.py # Quick start pipeline
βββ cli.py # Command-line interface
Before running AstroML ensure you have the following installed:
| Requirement | Minimum version | Notes |
|---|---|---|
| Python | 3.10+ | 3.11 recommended; 3.12 supported |
| Docker & Docker Compose | 24+ | Optional; only needed to run local PostgreSQL/Redis services |
| Git | any | For cloning the repository |
| Make | any | Optional but recommended; used for convenience targets |
| CUDA toolkit | 11.8+ | Optional; only needed for GPU-accelerated training |
Verify your Python version before proceeding:
python --version # must print 3.10 or higherBefore running quick start, create or use a PostgreSQL database and provide its
connection through config/database.yaml or ASTROML_DATABASE_URL. The database
must include the AstroML schema. Quick start does not require Redis, MLflow, the
API server, or a GPU.
Several requirements files are provided β pick the profile that matches your workflow:
| File | When to use |
|---|---|
requirements.txt |
Default β full stack including training, without GPU |
requirements-cpu.txt |
CPU-only training on machines without a CUDA-capable GPU |
requirements-train.txt |
GPU training; includes PyTorch with CUDA support |
requirements-api.txt |
API server only; excludes heavy ML dependencies |
requirements-dev.txt |
Development + testing; adds linting/typing tools on top of requirements.txt |
requirements-minimal.txt |
Config parsing only β useful in CI stages that don't run training |
requirements-minimal.txtis for configuration parsing; it is not sufficient for the quick-start pipeline, which trains a model and requires a database.
See REQUIREMENTS.md for a detailed breakdown of every package.
To run the bundled sample-data ingestion/graph/features workflow, install the CPU runtime and development/test dependencies in a virtual environment. This path does not require Docker, PostgreSQL, Redis, or a live Stellar endpoint:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements-cpu.txt -r requirements-dev.txt
pip install -e .
pytest tests/integration/test_e2e_sample_data.py -m e2e -qThe database-backed make quickstart and python -m astroml.quick_start
commands below are a separate workflow. They require a reachable PostgreSQL
database configured with ASTROML_DATABASE_URL or config/database.yaml;
Docker is one way to provide that database, not a prerequisite for the
Python-only sample workflow. See Contributor Onboarding
for the supported boundary and test-suite notes.
# Run quick start with default settings (100 ledgers, 50 accounts, 10 epochs)
make quickstart
# Run with more data for thorough testing
make quickstart-verbose# Run quick start with default settings
python -m astroml.quick_start
# Run with custom parameters
python -m astroml.quick_start --num-ledgers 200 --num-accounts 100 --epochs 20 --seed 42The canonical command is the top-level CLI module:
python -m astroml quickstart --num-ledgers 100 --num-accounts 50 --epochs 10 --seed 42Use python -m astroml.cli quickstart --help to verify the supported flags.
The defaults are --num-ledgers 100, --num-accounts 50, --epochs 10, and
--seed 42. Ledger, account, and epoch values must be greater than zero.
Make is optional; make quickstart and make quickstart-verbose run the same
CLI implementation.
The quick start pipeline:
- Generates sample data: Creates 100 synthetic ledgers with 50 accounts and realistic transactions
- Builds transaction graph: Constructs a time-windowed graph with ~2000 edges
- Validates graph: Checks for isolated nodes, self-loops, and computes statistics
- Trains baseline model: Trains a LinkPredictor model for 10 epochs
- Saves reproducible results: Stores config, results, and metadata for reproducibility
Output:
benchmark_results/quickstart/
βββ config.json # Full configuration with random seed
βββ result.json # Training metrics and performance
βββ metadata.json # Run metadata linking config and result
Expected output (typical values β exact numbers vary by seed):
================================================================================
AstroML Quick Start: Ingestion β Graph β Train Pipeline
================================================================================
[Step 1/5] Generating sample ledger data...
Generated 100 ledgers with 50 accounts
[Step 2/5] Building transaction graph...
Built graph with 2000 edges and 50 nodes
[Step 3/5] Creating benchmark configuration...
[Step 4/5] Training baseline model...
Epoch 0: Train Loss = 0.6931, Val Loss = 0.6892
Epoch 5: Train Loss = 0.4521, Val Loss = 0.4612
Training complete. Best metrics: {'auc': 0.92, 'precision': 0.88, 'recall': 0.85}
[Step 5/5] Saving benchmark results...
Saved config to benchmark_results/quickstart/config.json
Saved result to benchmark_results/quickstart/result.json
Saved metadata to benchmark_results/quickstart/metadata.json
β Quick start completed successfully!
Results saved to: benchmark_results/quickstart
================================================================================
Expected metric ranges on 10 epochs with the default seed:
- AUC: 0.85 β 0.96
- Precision: 0.80 β 0.93
- Recall: 0.78 β 0.91
- Training time: 5 β 30 s (CPU) / 2 β 8 s (GPU)
Another process is bound to port 8000. Find and stop it:
# Find the process
lsof -i :8000 # macOS / Linux
netstat -ano | findstr :8000 # Windows
# Stop it, or change the API port in docker-compose.yml:
# ports: ["8001:8000"]The PostgreSQL container is not running. Start it:
docker compose up -d db
# Wait ~10 seconds for Postgres to initialise, then retry
docker compose logs dbAlso verify your DATABASE_URL in .env matches the container settings (default: postgresql://astroml:astroml@localhost:5432/astroml).
Reduce batch size or switch to CPU:
# configs/training/default.yaml
training:
device: cpu # force CPU
batch_size: 256 # reduce from default 1024Alternatively, use requirements-cpu.txt which installs a CPU-only PyTorch build.
Ensure you are in the right virtual environment and have installed dependencies:
source venv/bin/activate # or: conda activate astroml
pip install -r requirements.txtIf the error mentions astroml itself, install the package in editable mode:
pip install -e .For GPU-related import errors (No module named 'torch_geometric'), install the full training requirements:
pip install -r requirements-train.txtCheck that the SQLite temp path is writable and that no previous benchmark result is locked:
rm -rf benchmark_results/quickstart/
make quickstartFor the quickest setup with all dependencies, use Docker:
# Clone and navigate to repository
git clone https://github.com/Traqora/astroml.git
cd astroml
# Start with Docker
cp .env.example .env
./scripts/docker-start.sh core
# Access services
curl http://localhost:8000 # API
open http://localhost:3000 # Grafanaπ Full Docker Setup: See DOCKER.md for comprehensive documentation including:
- Docker Quick Reference - Quick commands and common tasks
- Environment Configuration - Configuration guide
- Production Deployment - Production setup
- Troubleshooting - Common issues and solutions
git clone https://github.com/Traqora/astroml.git
cd astromlpython -m venv venv
source venv/bin/activate
pip install -r requirements.txtNote: Three requirements files are available. See REQUIREMENTS.md for guidance on which to use based on your environment (GPU training, CPU-only, or minimal config-only).
A Docker Compose setup can provide PostgreSQL and Redis for workflows that need those services. Start only those dependencies with:
docker compose up -d postgres redisAlternatively, configure your own PostgreSQL database and update
config/database.yaml.
For the supported v1 Docker Compose deployment profile, including named volumes, recovery procedures, and resource expectations, see V1 Persistent Volumes.
For a repeatable reset of the v1 local workflow, use:
make reset-localThis stops and recreates the API, PostgreSQL, and Redis containers with
docker compose while preserving PostgreSQL, Redis, feature-store, logs,
models, and other named volumes. It does not start optional GPU, monitoring,
production, development, or full-profile services.
The destructive equivalent is not run accidentally:
make reset-local-dataThe command requires an explicit DELETE_LOCAL_USER_DATA confirmation and
removes named project volumes. Back up data first. Docker must be running and
at least 2 CPU cores and 4 GB RAM are recommended for the core v1 stack.
AstroML includes an LLM agent framework for multi-step reasoning and autonomous task execution over the graph pipeline. It is provider agnostic, dependency light (the core loop is standard library only) and traces every step so runs stay auditable.
# Offline smoke test with the deterministic echo provider
python -m astroml.agent "Summarise this transaction graph"
# Against a local Ollama server, with task decomposition
python -m astroml.agent --provider ollama --model llama3.1 --plan \
"Rank the busiest accounts and flag anything unusual"
# Analyse a graph file and print the full trace as JSON
python -m astroml.agent --edges data/edges.json --json "How many accounts?"from astroml.agent import (
AgentConfig,
AgentExecutor,
build_default_registry,
provider_from_env,
)
agent = AgentExecutor(
llm=provider_from_env(), # echo | scripted | openai | ollama | ...
tools=build_default_registry(), # graph_overview, window_stats, ...
config=AgentConfig(mode="auto", max_steps=8),
)
result = agent.run("Which accounts look unusual?")
print(result.answer)
print(result.trace.summary())π Full guide: docs/agent-framework.md β providers, tools, memory, planning, CLI flags and design notes.
Backfill ledgers:
python -m astroml.ingestion.backfill \
--start-ledger 1000000 \
--end-ledger 1100000Create a rolling time window graph:
python -m astroml.graph.build_snapshot --window 30dThe v1 integration fixture exercises raw operation normalization, idempotent database persistence, and database-backed snapshot construction without PostgreSQL, Horizon, Redis, or other optional services:
pytest -q tests/integration/test_ingestion_to_snapshot_fixture.pyThe pytest fixture is available as ingestion_to_snapshot_fixture (and the
short alias ingestion_to_snapshot). It supports Horizon-style payment and
path-payment operation dictionaries. It ingests operation payloads directly;
it does not fetch ledgers or require network access. Missing or invalid
required operation fields raise ValueError instead of producing a snapshot.
Create benchmark datasets by injecting controlled fraud structures into a clean ledger copy:
python -m astroml.ingestion.synthetic_fraud_injector \
--input data/clean_ledger.jsonl \
--output data/ledger_with_fraud.jsonl \
--summary outputs/fraud_injection_summary.json \
--sybil-clusters 3 \
--sybil-cluster-size 8 \
--wash-loops 2 \
--wash-loop-size 5The injector appends transactions tagged with synthetic_fraud=true and fraud_pattern (sybil_cluster or wash_trading_loop) for downstream benchmarking.
python -m astroml.training.train_gcn- Liquidity Monitoring for the Stellar Community Fund
- Fraud / scam detection
- Account clustering
- Transaction risk scoring
- Temporal behavior modeling
- Self-supervised embeddings
- Network anomaly detection
AstroML emphasizes:
- Reproducibility
- Modular experimentation
- Scalable ingestion
- Temporal graph learning
- Production-ready ML pipelines
- Python
- PyTorch / PyTorch Geometric
- PostgreSQL
- NetworkX / graph tooling
The default test suite is intended to run without optional external services.
Tests that require a live API, PostgreSQL, Redis, MLflow, or a deployed
application are marked with external (or external_service).
# Fast, local/default suite
pytest -m "not external and not external_service"
# Run external-service tests explicitly
pytest --run-external
# Environment-based opt-in (for CI and wrappers)
ASTROML_RUN_EXTERNAL_TESTS=1 pytestMocked HTTP/database behavior remains in the default suite. External tests must declare their service configuration and fail or skip clearly when the service is unavailable.
The following are not yet supported; the consolidated list with status and notes lives in docs/ROADMAP.md.
- Real-time streaming ingestion
- Temporal GNN models
- Contrastive learning pipelines
The feature store, the model benchmarking suite, and Docker deployment were previously listed here as to-dos. They have shipped β see docs/ROADMAP.md β and are no longer roadmap items.
Contributions are welcome!
fork β branch β commit β PRPlease open issues for bugs or feature requests.
MIT License <<<<<