Natural language EEG lab notebook. Train pattern classifiers, analyze connectivity, compare sessions β all by talking to an AI copilot that reads your live brain signals.
Linux / macOS / WSL:
# One-line remote install (recommended)
curl -sSL https://raw.githubusercontent.com/pieeg-club/PiEEG-agent/main/install.sh | bash
# Or clone and setup manually
git clone https://github.com/pieeg-club/PiEEG-agent.git
cd PiEEG-agent
chmod +x setup.sh && ./setup.shWindows:
git clone https://github.com/pieeg-club/PiEEG-agent.git
cd PiEEG-agent
install.cmdWhat it does:
- β Creates Python virtual environment
- β Installs all dependencies
- β Sets up command-line launcher
- β Runs verification tests
No Node.js required β the React frontend is prebuilt and included.
# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install package
pip install -e ".[web,dev]"# Start with any LSL stream (PiEEG, OpenBCI, Muse, etc.)
pieeg-agent web
# Or test with synthetic data (no hardware)
pieeg-server --mock --lsl # Terminal 1
pieeg-agent web # Terminal 2Open http://localhost:8000 for:
- π¬ Chat with brain copilot β "am I focused?", "train a relaxation pattern"
- π§ Live brain state cards β focus/relax/engagement, band powers, quality
- π¨ Pattern training UI β record mental states, train classifiers
- π Connectivity visualization β cross-channel coupling analysis
- ποΈ Device control (optional) β adjust filters, start recording, enable OSC
First-time setup:
You'll be prompted to select an LLM provider and enter an API key (or use local Ollama/LM Studio). Configuration is saved to ~/.pieeg-agent/config.json.
# Discover LSL streams
pieeg-agent streams
# Monitor live state (no LLM needed)
pieeg-agent monitor
# Ask one-shot questions
pieeg-agent ask "am I focused?"
# Interactive chat
pieeg-agent chat# Terminal 1: Start PiEEG server with LSL
pieeg-server --lsl
# Terminal 2: Launch agent with device control
pieeg-agent web --allow-actions --executeAction modes:
pieeg-agent webβ Read-only (monitoring + analysis)pieeg-agent web --allow-actionsβ Preview mode (shows what it would do)pieeg-agent web --allow-actions --executeβ Execute mode (actually controls device)
All actions pass through a safety gate with cooldowns, allowlists, and audit logging.
Neural State Tools:
get_neural_stateβ Current focus, relaxation, engagement (0-1, session-relative)get_band_powersβ Delta, theta, alpha, beta, gamma power distributionget_channel_qualityβ Per-channel signal quality (good/flat/rail/noisy/line)get_recent_eventsβ Debounced state transitions and quality changes
Artifact Detection:
find_artifactsβ Eye blinks (single/double), jaw clenches, motion artifacts
Example:
you > how's my signal?
copilot > All channels read "good", quality 0.98 β trustworthy signal.
you > am I focused or relaxed?
copilot > Relaxed. Alpha is dominant (0.87) and focus is low (0.31).
Train custom mental state classifiers:
you > train a pattern called "meditation"
copilot > Starting pattern training for "meditation". I'll guide you through recording segments.
First, I need a baseline. Sit normally with eyes open.
Ready to record 'rest' for 4 seconds? (say yes when ready)
you > yes
copilot > [Recording rest...] β Captured 32 frames, quality 0.94.
Now, close your eyes and meditate for 4 seconds.
Ready? (say yes)
you > yes
copilot > [Recording active...] β Captured 32 frames, quality 0.96.
That's rep 1 of 3. Let me record another rest segment...
[repeats 2 more times]
Training classifier... Done!
Pattern "meditation" trained:
- Balanced accuracy: 0.89 (leave-one-rep-out CV)
- Top cue: Alpha increase in O1/O2 (occipital)
- Channel importance: O1β
β
β
O2β
β
β
C3β
C4β
Features:
- L2 + group-lasso regularization for spatial sparsity
- Leave-one-rep-out cross-validation (no temporal leakage)
- Balanced accuracy (immune to class imbalance)
- Channel importance shows which electrodes matter
- Live scoring β patterns activate in real-time after training
Pattern Tools:
start_pattern_trainingβ Begin teaching a new patternrecord_segmentβ Capture labeled rest/active segmentsfinish_pattern_trainingβ Fit detector and validatelist_patternsβ Show all trained patterns with CV scoresdetect_patternsβ Live activation of all loaded patternsexplain_patternβ Channel importance and feature weightsdelete_patternβ Remove a pattern
Deep frequency-domain analysis:
you > analyze my alpha rhythm
copilot > Spectral analysis:
- Individual alpha peak (IAF): 10.2 Hz
- Alpha power: 0.73 (dominant)
- 1/f slope: -1.1 (typical healthy EEG)
- Spectral entropy: 0.68 (moderate complexity)
- Frontal alpha asymmetry: -0.05 (balanced)analyze_spectrum returns:
- Individual alpha frequency (IAF) β your personal alpha peak
- Aperiodic 1/f slope β reflects excitation/inhibition balance
- Theta/beta ratio β cognitive load / vigilance marker
- Spectral entropy β signal complexity measure
- Frontal alpha asymmetry β hemispheric balance (approach/withdrawal)
you > show connectivity in the alpha band
copilot > Alpha-band connectivity (amplitude coupling):
Mean correlation: 0.34
Strongest pair: C3βC4 (r=0.72) β motor cortex synchrony
Most connected: C3 (6 strong links)
Least connected: Fp1 (2 weak links)connectivity tool computes cross-channel amplitude coupling in any frequency band. Useful for:
- Network topology analysis
- Hemispheric synchrony
- Rest vs. task comparisons
Capture labeled windows for later comparison:
you > record a session called "meditation" for 60 seconds
copilot > [Capturing...] β Session saved.
Alpha dominant (0.81), high relaxation (0.76)
C3-C4 coupling: 0.68
you > record "eyes-open-focus" for 60 seconds
[later...]
you > compare meditation vs eyes-open-focus
copilot > Session comparison (within-session Cohen's d):
Alpha power: +0.92 SD (meditation higher)
Beta power: -0.54 SD (meditation lower)
Relaxation index: +0.71 SD
C3-C4 coupling: +0.45 SD
Meditation shows classic eyes-closed signature:
increased alpha, decreased beta, stronger bilateral sync.Session Tools:
record_sessionβ Capture labeled window with full metricslist_sessionsβ Show all recorded sessionssession_summaryβ Detailed view of one sessioncompare_sessionsβ Statistical comparison with effect sizes
Create publication-ready analysis notebooks:
you > create a notebook analyzing my meditation pattern
copilot > [Generating notebook...]
β Created: meditation_analysis.ipynb
Includes:
- Pattern ROC curve (LORO-CV)
- Feature importance rankings
- Per-channel band power evolution
- Confusion matrix
- Statistical summary tablecreate_jupyter_notebook auto-populates templates with:
- Session data from store
- Pattern classifiers with provenance
- Matplotlib/seaborn visualization code
- Markdown explanations
Templates available:
- Session summary (band powers, artifacts, quality)
- Pattern performance (ROC, confusion matrix, feature importance)
- Connectivity heatmaps
- Spectral evolution (time Γ frequency)
Search neuroscience literature:
you > search pubmed for P300 event-related potentials
copilot > Found 5 papers:
1. "The P300 wave of the human event-related potential"
[shows snippet + PubMed link]
...Web Tools:
search_webβ Wikipedia or PubMed searchfetch_urlβ Fetch from trusted domains (scientific publishers, Wikipedia)list_trusted_sourcesβ Show allowed domains
Documentation Tools:
search_docsβ Search PiEEG documentationfetch_docβ Retrieve specific doc pages
This agent is designed for neurofeedback research and UX prototyping, not clinical use.
focus, relax, engagement are normalized to the session's own range (rolling 10-minute window). They mean "high for you, right now" β not absolute or clinical values.
- Warm-up period: Indices show 0.50 until signal variance is established. A
~prefix marks this, and the copilot says "still warming up" instead of inventing numbers. - Quality gates: Poor electrode contact or artifacts are flagged before reporting state.
Pattern training uses:
- L2 + group-lasso regularization β drives whole channels to zero if uninformative
- Leave-one-rep-out CV β temporally-correlated frames in one rep can't leak into their own test
- Balanced accuracy β mean of sensitivity and specificity, immune to class imbalance
No overfitting claims: CV scores are reported honestly. If you have 3 reps, you get 3-fold LORO-CV.
Session comparisons report within-session Cohen's d (standardized mean difference). This is a descriptive effect size for your data, not a generalization or clinical claim.
Example caveat in output:
"Cohen's d = 0.8 within this session. This does NOT mean the effect generalizes across days, subjects, or conditions."
State transitions require:
- Threshold crossing (default: 0.70 for high, 0.30 for low)
- Minimum dwell time (2 seconds β no flicker)
- Quality floor (0.50 β no events during artifacts)
No spurious events from noise.
| Principle | Implementation | Why It Matters |
|---|---|---|
| Ingestion never blocks | Dedicated LSL thread, ring buffer | No sample loss even if LLM is slow |
| LLM pulls, never pushed | Tools request state on demand | Token costs stay sane |
| Language-sized representations | Events, not voltage arrays | Models reason about "focus_high", not floats |
| Scientifically honest metrics | Within-session normalization, warm-up flags | Users know what numbers mean |
| Decoupled layers | Swap providers, run without LLM, test with mock | Debuggable, testable, maintainable |
| Safe by default | Dry-run, cooldown, audit log | AI can't spam device commands |
The challenge: LLMs reason at ~1 Hz. EEG arrives at 250-500 Hz Γ 8 channels = 2,000-4,000 samples/second.
The solution: Progressive semantic compression
βββββββββββββββ¬βββββββββββ¬βββββββββββββββββββββββββ¬βββββββββββββββ
β Tier β Rate β Representation β LLM sees it? β
βββββββββββββββΌβββββββββββΌβββββββββββββββββββββββββΌβββββββββββββββ€
β T0 Raw β 250 Hz β float32 Β΅V samples β never β
β T1 Features β 8 Hz β band powers, quality β never β
β T2 State β 1 Hz β focus/relax/engagement β on demand β
β T3 Events β ~sparse β "focus_high" @10:04:32 β YES β main β
β T4 Reason β on query β NL questions + tools β β β
βββββββββββββββ΄βββββββββββ΄βββββββββββββββββββββββββ΄βββββββββββββββ
Three architectural rules:
- High-rate intake runs in dedicated thread β never waits on LLM
- LLM pulls via tools β never spammed with raw data
- Everything the model sees is language-sized β indices, events, verdicts
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PiEEG Hardware + Server (Raspberry Pi or PC) β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β ADS1299 β pieeg-server β β
β β β’ 8-ch EEG @ 250 Hz β β
β β β’ Hardware filtering β β
β β β’ CSV recording β β
β β β’ LSL broadcast (data) β β
β β β’ WebSocket :1616 (control) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ¬βββββββββββ
β LSL (data) β WS (control)
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PiEEG-Agent β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β INGEST: LSL intake β 60s ring buffer β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β PERCEIVE: Cascade (T0βT1βT2βT3) β β
β β T1: FFT β band powers @ 8 Hz β β
β β T2: State indices @ 1 Hz β β
β β T3: Sparse events (debounced) β β
β β Artifacts: blink/jaw/motion detection β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β DECODE: Lab notebook tools β β
β β β’ Pattern training (L2+group-lasso, LORO-CV) β β
β β β’ Connectivity (cross-channel coupling) β β
β β β’ Sessions (capture + compare with Cohen's d) β β
β β β’ Spectral (IAF, 1/f slope, theta/beta, entropy) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β REASON: LLM copilot β β
β β Providers: Anthropic, OpenAI, Groq, Ollama, etc. β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β ACT: Safety gate (with --allow-actions) β β
β β β Allowlist β β Cooldown β β Dry-run β β Audit β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β http://localhost:8000
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Web Interface (browser) β
β β’ Chat with brain copilot β
β β’ Live brain state cards β
β β’ Pattern training UI β
β β’ System control panel β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Module | Purpose | Key Files |
|---|---|---|
ingest/ |
LSL intake, ring buffer | lsl_inlet.py, ring.py |
perceive/ |
Feature extraction, state estimation, events | features.py, state.py, events.py, artifacts.py, quality.py, cascade.py |
decode/ |
Pattern training, connectivity, sessions, spectral | patterns.py, classifier.py, connectivity.py, session.py, spectral.py, features.py, calibrate.py, train.py, store.py |
llm/ |
Provider abstraction (HTTP-only, no SDKs) | provider.py, anthropic.py, openai_compat.py, factory.py, echo.py |
agent/ |
Copilot, tool dispatch | copilot.py, tools.py, decode_tools.py, actuator_tools.py, utility_tools.py, web_tools.py, doc_tools.py, context.py |
server/ |
Device control (optional) | client.py, gate.py, actions.py |
web/ |
FastAPI backend + React frontend | app.py, engine.py, frontend/ |
First-time usage launches an interactive setup:
- Provider selection β Anthropic, OpenAI, Groq, Together, Ollama, LM Studio, Echo
- API key input β Secure prompt (hidden) for cloud providers
- Save option β Persist to
~/.pieeg-agent/config.json(chmod 600)
Manage configuration:
pieeg-agent config # View current settings
pieeg-agent config reset # Delete saved configNon-interactive mode (Docker, CI):
export PIEEG_LLM_PROVIDER=anthropic
export ANTHROPIC_API_KEY=sk-ant-...
pieeg-agent web # Skips wizard| Provider | Type | API Key Needed | Get Key From |
|---|---|---|---|
| Anthropic | Cloud | β
ANTHROPIC_API_KEY |
https://console.anthropic.com/settings/keys |
| OpenAI | Cloud | β
OPENAI_API_KEY |
https://platform.openai.com/api-keys |
| Groq | Cloud | β
GROQ_API_KEY |
https://console.groq.com/keys |
| Together AI | Cloud | β
TOGETHER_API_KEY |
https://api.together.xyz/settings/api-keys |
| Ollama | Local | β None | Install from https://ollama.ai |
| LM Studio | Local | β None | Install from https://lmstudio.ai |
| Echo | Debug | β None | Built-in (keyword-based simulator) |
| Variable | Default | Purpose |
|---|---|---|
PIEEG_LSL_NAME |
PiEEG |
LSL stream name |
PIEEG_LSL_TYPE |
EEG |
LSL stream type |
PIEEG_RING_SECONDS |
60 |
Ring buffer depth (seconds) |
PIEEG_LLM_PROVIDER |
anthropic |
LLM provider |
PIEEG_LLM_MODEL |
provider default | Model override |
ANTHROPIC_API_KEY |
β | Anthropic API key |
OPENAI_API_KEY |
β | OpenAI API key |
GROQ_API_KEY |
β | Groq API key |
TOGETHER_API_KEY |
β | Together AI API key |
PIEEG_WS_URL |
ws://localhost:1616 |
PiEEG-server WebSocket |
PIEEG_WS_TOKEN |
β | WebSocket auth token |
PIEEG_AUDIT_LOG |
~/.pieeg-agent/audit.jsonl |
Action audit log path |
# Minimal (monitoring + analysis)
pip install -e .
# With device control
pip install -e ".[server]"
# Full dev environment
pip install -e ".[dev,server]"# Mock EEG stream (deterministic signal)
pieeg-server --mock --lsl --seed 42
# Validate stream throughput
pieeg-agent ingest --seconds 10
# Exit code 0 = no samples lost
# Monitor live (no LLM needed)
pieeg-agent monitor# Echo provider (keyword-based simulator with real tools)
pieeg-agent web --provider echo
pieeg-agent chat --provider echo
pieeg-agent ask --provider echo "am I focused?"pytest tests/ # All tests
pytest tests/test_ring.py # Specific module
pytest -v --tb=short # Verbose with short tracebacksTest coverage includes:
- Ring buffer overwrite logic
- FFT feature extraction
- Event detector hysteresis
- Pattern classifier LORO-CV
- Connectivity computation
- Session comparison
- Provider wire format
- Gate enforcement (allowlist, cooldown)
- PiEEG Hardware β Open-source EEG shield for Raspberry Pi
- Lab Streaming Layer β Time-sync for multi-modal biosignals
- Anthropic Tool Use β How the copilot calls functions
- Discord Community β Get help, share projects
Contributions welcome! Whether fixing bugs, adding features, or improving documentation:
For bugs, include:
pieeg-agent config # Current configuration
pieeg-agent streams # LSL stream discovery
# Paste error tracebackFor feature requests, include:
- Use case: What problem are you solving?
- Proposed API: CLI commands or copilot interactions
- Why existing tools don't work: What's missing?
For scientific/algorithmic changes, include:
- Citations: Papers or validated implementations
- Test data: Public datasets showing improvement
- Justification: Why this threshold/method?
# Fork and clone
git clone https://github.com/YOUR-USERNAME/PiEEG-agent
cd PiEEG-agent
# Install with dev dependencies
pip install -e ".[dev,server]"
# Run tests before changes
pytest tests/
# Make changes, add tests, verify
pytest tests/- Honest metrics: Clearly document within-session vs generalizable claims
- No blocking: LSL ingestion must never wait on LLM/network
- Language-sized: Tools return events/verdicts, not voltage arrays
- Typed interfaces: Use dataclasses/TypedDicts for tool contracts
- Decoupled layers: Perception works without LLM, LLM works without device
- Tests pass (
pytest tests/) - New features have tests
- Documentation updated (README, docstrings)
- Metrics have citations (if scientific claims)
- No vendor SDK dependencies (use stdlib HTTP)
- High-rate LSL intake β Chunked pulls, ring buffer
- Perception cascade β Features β state β events
- LLM copilot β Read-only tools, provider-agnostic
- Gated device actions β Allowlist, dry-run, audit
- Artifact detection β Blinks, jaw, movement + quality tracking
- Pattern training β L2+group-lasso, LORO-CV, balanced accuracy
- Web UI β FastAPI + React, chat + live brain cards
- Connectivity analysis β Cross-channel coupling
- Session comparison β Lab notebook tools
- Pattern health monitoring β Confidence scoring, degradation alerts
- Jupyter notebook templates β Auto-generated analysis notebooks
- P300 decoder β Event-related potential for single-trial BCI control
- Multi-modal fusion β EEG + EOG + EMG streams
CC BY-NC 4.0 (Creative Commons Attribution-NonCommercial 4.0 International) β see LICENSE
You are free to share and adapt this work for non-commercial purposes with attribution.