Sabela is a reactive notebook for Haskell. The name is the Ndebele word for to respond, which is the behaviour it is built around.
git clone https://github.com/DataHaskell/sabela
cd sabela
cabal update
cabal runOpen localhost:3000/index.html, then either:
- open
examples/CaliforniaHousing.mdfor a full worked example, taking California housing data through to a Hasktorch linear-regression model, or - click the book icon, top left, for ready-to-run snippets.
There are examples in the folder showcasing different features like widgets, and Python integration.
The execution and dependency model is based on scripths.
git clone https://github.com/DataHaskell/sabela
cd sabela
cabal update
cabal runThen open http://localhost:3000/index.html. By default the file explorer is
rooted at the current directory.
To pass options, the argument order is:
sabela [port] [work-dir] [global-file] [packages...]
So to run on a different port with a notebook directory of your own:
cabal run sabela -- 8080 ~/notebooksglobal-file defaults to ~/.sabela/global.md (see section 6); any
trailing arguments are extra packages to preinstall.
A notebook is an ordinary Markdown file: prose plus fenced Haskell blocks.
# My first notebook
This is prose.
```haskell
x = 10
```
More prose.
```haskell
print (x + 5)
```Fenced code blocks load as code cells, and the text between them loads as prose cells. Saving writes the notebook back out as Markdown, so it diffs cleanly in Git and edits fine outside the browser.
Make a file examples/tutorial.md:
# Sabela basics
```haskell
x = 10
```
```haskell
y = 20
```
```haskell
print (x + y)
```When you edit a cell, Sabela parses every cell with ghc-lib-parser, a
standalone copy of GHC's own parser that works regardless of your GHC version.
From the syntax tree it reads the top-level names each cell defines and the
names each cell uses without binding them itself. That gives a real dependency
graph rather than a guess based on matching text.
Editing a cell reruns its dependents in dependency order, computed by a topological sort rather than notebook position, so every value is recomputed before the cells that read it. Two situations are reported instead of run:
- Redefinitions. The first cell to define a name owns it. A later cell that defines the same name is flagged with an error pointing back to the original, instead of silently shadowing it.
- Cycles. If two cells come to depend on each other, both are reported as a cycle rather than looping.
There are still a number of gaps in the reactivity semantics e.g. type classes definition changes don't yet propagate bu, but the common cases are covered.
Anything that runs in GHCi runs in a cell:
let triples =
[ (a, b, c)
| c <- [1..20]
, b <- [1..c]
, a <- [1..b]
, a*a + b*b == c*c
]
print triplesA notebook carries its own package requirements. You declare them with
-- cabal: directives at the top of a cell:
-- cabal: build-depends: text
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
let msg = T.pack "Hello, Sabela!"
TIO.putStrLn (T.toUpper msg)Extensions go the same way:
-- cabal: build-depends: aeson, text, bytestring
-- cabal: default-extensions: DeriveGeneric, OverloadedStringsThe directives are per cell, but they apply to the whole notebook: Sabela merges
the -- cabal: lines from every cell into one package set. When that set
changes it resolves the package environment, restarts GHCi, reinjects the
display helpers, and reruns the cells that need it. Putting your main directives
near the top keeps the environment easy to read.
For dependencies you want in every notebook, put the same directives in a
global.md (by default ~/.sabela/global.md).
Unlike other notebooks, can also compile cells with heavy computations:
```haskell
-- compile
trainEpoch :: Model -> [Batch] -> (Model, Double)
trainEpoch m bs = ...
```
```haskell
trainEpoch model batches -- calls native -O2 code
```- A compiled cell contains only what is legal at the top of a module:
imports, type signatures, bindings,
data/class/instancedeclarations. - Downstream cells use compiled names directly with no imports.
- Duplicate top-level names across cells are an error (compiled definitions cannot be shadowed), and a compiled cell cannot use a name defined in an interpreted cell.
-- compile: Training names the generated module explicitly; cells sharing
a name merge into one module (which also permits mutual recursion between
them), and modules import each other automatically when one uses the
other's names. Use the ⚡ button in a cell's actions to toggle the
directive without typing it.
A cell marked -- cache: persist keeps the values it binds on disk. When it
would otherwise be recomputed by a replay (a kernel restart, Run All, or the
replay a compiled-cell edit triggers), its values are loaded back and its
output replayed instead:
```haskell
-- cache: persist
df <- D.readCsv "data/train.csv"
features :: D.DataFrame
features = D.derive "ratio" (F.col @Double "a" / F.col @Double "b") df
```- An entry is reused only while nothing it came from has changed: the cell's
code, the cells it depends on, the resolved packages (including edits to
local packages), the notebook's imports, flags and instances, and the files
it names (string literals that are paths, plus any
-- cache: watch <path>). Comments and spacing do not count. - Pressing Run on the cell always recomputes it and refreshes the entry.
- Values need a codec. Data frames (typed or not) are stored as Parquet;
anything with a
Binaryinstance is stored after an emptyinstance Sabela.Notebook.Cache.CellCodec T. Values must have one type, so give polymorphic bindings a signature. - A cell that cannot be restored as written (a pattern bind, a splice, a value used by a declaration above it) runs normally; the tag in the cell's corner says why. Click the tag to clear the cell's entry; Clear the persistent cell cache in the command palette clears the notebook's.
- The cache lives in
.sabela/cache/(git-ignored). Entries are signed with a per-user key, so a cache copied in from elsewhere is ignored, and the oldest entries are dropped beyond 2 GB (SABELA_CACHE_MAX_BYTES).
A cell's last expression renders itself: Sabela hands GHCi's
-interactive-print to a Display class, which picks the best form the value
has. Nothing you write today changes — a value with no richer instance prints
exactly as it printed before.
Every chart in Sabela.Notebook returns a Picture, and a Picture renders
as SVG on its own — the value is the cell:
import Sabela.Notebook
lineChart [(0, 0), (1, 2), (2, 1)] -- an SVG chart, no wrapper
fill red (circle (0, 0) 40) -- so does any picture you builddisplayPicture still works and is still what you reach for mid-cell; you no
longer need it on the last line. The Svg and Html wrappers from
Sabela.Notebook.Markup display themselves the same way.
Wrap a string in the form it is, and the cell shows it that way:
md "## Results\n\nThe answer is **42**."
html "<p>Hello from <b>Sabela</b></p>"
svg "<svg viewBox='0 0 10 10'><circle cx='5' cy='5' r='4'/></svg>"
latex "\\frac{1}{2}"
json "{\"ok\": true}"
png base64Bytes -- also: jpeg
table ["city", "pop"] [["Bulawayo", "665000"]] -- the same grid, from stringsThere is no display call in any of those: the value is the whole cell.
display exists for when you want one anyway (inside a loop, say, or in the
middle of an IO block), and a widget renders itself too — bind its value with
mkWidget when you need it.
A DataFrame from the dataframe
package renders as the grid with no opt-in at all — the value is the cell:
-- cabal: build-depends: dataframe, text
import qualified DataFrame as D
df <- D.readCsv "penguins.csv"
dfThe instance is offered to any notebook whose cells declare the package, and
only to those: it is injected beside the prelude rather than inside it, so a
notebook that never asked for dataframe is untouched. Large frames are
capped at 1000 rows carried into the page, and the footer still reports the
frame's true height (first 1000 of 5000 rows).
For your own types, opt a record in once and any list of it renders the same way — field names as column headers:
import GHC.Generics (Generic)
data Reading = Reading { city :: String, temp :: Double }
deriving (Show, Generic, Tabular)
[Reading "Bulawayo" 27.5, Reading "Harare" 24.1] -- a tablederiving Tabular is the whole opt-in, and it is what separates a table from a
list: a type that has not opted in prints as it always did, so [1, 2, 3] is
still [1,2,3]. A type with no Show instance is unchanged too — it was never
printable.
What you get is a real table view, not a static <table>:
- typed columns — a header carries its name and inferred type (
#,abc,✓), and clicking it sorts ascending, then descending, then not at all - a distribution strip under each header — a histogram for numbers, the leading categories in proportion for everything else
- colour coding — numeric cells carry their place in the column's range as
background weight; a low-cardinality text column gets a stable colour per
category. The
colorbutton turns it off - search — free text over every cell, or a column expression such as
temp > 25 - selection — click for a current row, ctrl-click to add, shift-click for a range; the row header numbers the source rows and its corner clears
- resizable columns, a sticky header, and
statsfor per-column min / mean / max or unique counts
Only the rows in view are built, so scrolling a long table costs what a short one does. A table carries at most 1000 rows into the page and reports the rest as a count.
The older helpers still work, and stay the way to emit rich output from a cell whose last expression is not the thing you want shown:
| Helper | Output |
|---|---|
displayHtml |
HTML |
displayMarkdown |
Markdown |
displaySvg |
SVG |
displayLatex |
LaTeX |
displayJson |
JSON |
displayImage |
base64 image (takes a MIME type and the data) |
A plain print shows up as text. Rich output has to be the only thing the cell
prints.
displayMarkdown $ unlines
[ "# Analysis Results"
, ""
, "The computation found **42** as the answer."
, ""
, "| Metric | Value |"
, "|--------|-------|"
, "| Speed | Fast |"
, "| Memory | Low |"
]displayHtml $ unlines
[ "<h2>Hello from Sabela</h2>"
, "<p>This is <strong>rich HTML</strong> output.</p>"
, "<ul><li>Item one</li><li>Item two</li></ul>"
]Files from the notebook work-dir are served via /api/asset?path=<path>, and can be used in the HTML.
-- cabal: build-depends: text, granite
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T
import Granite.Svg
displaySvg $ T.unpack
(bars [("Q1",12),("Q2",18),("Q3",9),("Q4",15)] defPlot { plotTitle = "Sales" })Each helper prefixes its output with a MIME marker that the server strips before sending the result to the browser.
A widget is an HTML control (slider, dropdown, checkbox, text box, button) that lives in a cell's output and reruns the cell when you touch it. You write no JavaScript: Sabela renders the control and carries its value back to GHCi to rerun the cell.
Every widget is a Behavior a: a value that knows how to render itself and
sample its current value. The verb display does both: it draws the control
and returns the value:
c <- display (slider "celsius" (20 :: Int) (-40) 120)
let f = c * 9 `div` 5 + 32
displayHtml $ "<p><b>" ++ show c ++ " °C</b> = " ++ show f ++ " °F</p>"Drag the slider and the cell reruns with the new c. Any cell downstream that
uses c reruns too, because a widget value is an ordinary Haskell binding.
The full set:
| Widget | Returns |
|---|---|
slider name def lo hi |
the number, as you drag (debounced) |
dropdown name options def |
the chosen String |
checkbox name def |
a Bool |
textInput name def |
the current String |
button label name |
Maybe () (Just () once clicked) |
scatterSelect name points |
[Int], the indices of the lassoed points |
Behavior is Applicative, so you can combine widgets into one value:
area <- display (liftA2 (*) (slider "w" (10 :: Int) 1 100)
(slider "h" (10 :: Int) 1 100))
displayHtml $ "<p>Area: <b>" ++ show area ++ "</b></p>"scatterSelect draws an HTML5 canvas and returns the indices of the points you
circle. Hand those to a row filter and a downstream cell shows exactly the rows
you selected:
sel <- display (scatterSelect "districts" [(lon, lat) | (lon, lat) <- coords])
selThe Visualize panel builds charts by pointing and clicking, and writes them as ordinary typed dataframe code in a cell, so nothing it makes is locked to Sabela.
- Bring data in. Paste a link to a CSV or Parquet file in the Data tab, tick the files and press Load. Each becomes a typed table named after its file.
- Chart it. Pick a table in Visualize. The first chart is chosen from what the columns hold, not where they sit: a line over time when there is a date or a year, otherwise names or groups against the table's main measure; an id, a year or a column with one value is never proposed as a measure. Changing the chart type keeps the columns you placed and re-picks the rest, and says so when that changes how values are combined.
- Filter rows. Filter rows keeps or leaves out chosen values of a
column, or a range of numbers. Values are listed largest total first, which
puts rows that are totals of other rows (a "World" row among countries) at
the top. The cell reads
C.chart (gdp |> DT.filterBy (...) (DT.col @"...")). - Join two tables. Join two tables… proposes the columns to match on,
adds a second key when one alone would pair rows many to many, and shows
how many rows the result will have. A column both tables share is named
after its table on both sides (
Value_gdp,Value_population). - Save a chart as a component. Save chart as a component… turns the
chart into a function of its table, its columns and its title under
components/Components/. It is then listed under Chart components; click it to draw the same chart from another table. A component is built with the kernel: a package it needs goes in a-- cabal: build-depends:line in its own module (the package's cabal file is regenerated from the modules). If a component stops building, the kernel starts without components and a banner names the one at fault, with Open its code and Remove it.
Every action taken through the UI — loading data, adding or changing a chart, a join, saving a component — is one step, and edits typed into a cell become steps of their own. Undo, Redo and History in the toolbar (and Ctrl/Cmd+Z outside an editor) take a step back or bring it on again. Undoing a step puts back only what that step changed and keeps later work; if a cell it changed has been edited since, you are asked before anything is replaced. A component that fails to build when saved is undone automatically.
The steps are kept beside the notebook, in .sabela/history/ in the
workspace, so they survive a reload and a restart of the server. The folder
ignores itself in git.
Pick py from the language dropdown in a cell's gutter and that cell runs in a
persistent Python REPL instead of GHCi. Variables persist down the notebook, and
the same displayHtml / displayMarkdown helpers work. (You need python3 on
your PATH.)
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print([fib(i) for i in range(10)])The two languages run in separate processes, so they pass values through a bridge rather than shared memory. Export from Haskell:
exportBridge "names" (show names)and the value arrives in Python as the string _bridge_names:
import ast
names = ast.literal_eval(_bridge_names)It works the other way too: exportBridge("result", json.dumps(r)) in Python
surfaces as _bridge_result in Haskell, and exporting from Python reruns the
Haskell cells that read it. The usual move is to load and type-check data with
DataFrame in Haskell, ship it across as CSV, and let pandas or matplotlib take
over. examples/tutorial-python-integration.md and examples/matplotlib-demo.md
walk through it.
The bridge keeps Python in its own process. If you would rather call Python from inside a Haskell expression, with typed values instead of strings, inline-python works in a notebook with no setup beyond declaring it:
-- cabal: build-depends: inline-python
import Python.Inline
import Python.Inline.QQ
xs = [1 .. 10] :: [Int]
runPy (fromPy' @Int =<< [pye| sum(x * x for x in xs_hs) |])Sabela turns on QuasiQuotes and starts the interpreter for any notebook that
declares the package. You need the Python development files installed
(python3-dev on Debian and Ubuntu) so that pkg-config python3-embed resolves.
Python inside a multi-line quasiquote must be indented, because a line starting
in column 0 begins a new statement.
examples/python-bridge-vs-inline-python.md does the same jobs with the bridge
and with inline-python, side by side.
Which Python it uses. inline-python links the Python that pkg-config finds
when the package is first built, normally the system one. That choice is fixed
until the package is rebuilt. It is a separate interpreter from the one that runs
Python cells, so the two share no variables, and packages installed with
# pip: lines are not visible to it.
Using a virtual environment. A venv has no interpreter library of its own; it
is a site-packages directory on top of a base Python. So the embedded
interpreter can use any venv made from the same Python version it was linked
against. Create one and install what you need:
python3 -m venv ~/venvs/notebooks
~/venvs/notebooks/bin/pip install numpy pandasThen do one of the following.
-
Start Sabela with the venv on
PYTHONPATH. This applies to every notebook, and to Python cells as well:PYTHONPATH=~/venvs/notebooks/lib/python3.11/site-packages cabal run sabela -
Or add it from a cell, which affects only that notebook's embedded interpreter. The path must be absolute:
runPy [pymain| import site site.addsitedir("/home/you/venvs/notebooks/lib/python3.11/site-packages") |]
Replace python3.11 with the version your venv was made from. If the versions
differ, pure-Python packages may still import but compiled ones such as numpy
will not.
Sabela exposes its notebook over a small REST API at /api/ai/*, and siza is
a Claude Code skill that drives it. With your notebook open in the browser and
siza installed in a second terminal, Claude can list cells, read them, run them,
propose edits you approve in the UI, and use a try operation for
non-committing experiments against notebook context and candidate dependencies.
The plugin bundles siza mcp, an MCP server over the notebook, so Claude calls
typed tools rather than shell commands. Put the binary on your PATH, then install
the plugin from inside Claude Code:
cabal install exe:siza --overwrite-policy=always/plugin marketplace add /path/to/sabela/cli-skill
/plugin install siza
/reload-plugins
Then start Sabela (cabal run), open a notebook, and ask Claude things like
"what's in my notebook?", "run cell 3 and tell me what it prints", or
"add a cell that plots median income against house value." siza finds the
running server on its own: Sabela writes ~/.local/state/sabela/servers/<port>.json
on startup so the skill can read it.
On a shared or remote machine, gate the bridge with a token:
SABELA_AI_TOKEN=$(openssl rand -hex 16) cabal runClients then send Authorization: Bearer <token>; the rest of the UI stays
open. Full details are in cli-skill/README.md.
The siza binary also has a chat subcommand that drives your notebook with a
local Ollama model .
Siza is a harness that's integrated into both the Haskell package ecosystem and
GHC as a compiler. The harness has hooks that apply deterministic repair to code,
perform contextual package searches, and embed the reactive notebook semantics as
constraints for what the LLM can output.
Prerequisites: Ollama running with a model pulled (e.g.
ollama pull gpt-oss:20b), and a Sabela server up (cabal run). Then:
cabal run exe:siza -- chat # discovers the running server
cabal run exe:siza -- chat --model gemma4:latest --url http://localhost:3000| Flag | Default | Meaning |
|---|---|---|
--model |
gpt-oss:20b |
Ollama model tag (must match ollama list) |
--url |
discovered server | Sabela server to drive |
--timeout |
300 |
per-request wall-clock cap (seconds) |
--max-turns |
40 |
max harness turns per request |
--verbose |
off | stream the full audit (system prompt, thinking, tool JSON) |
Name resolution (finding library functions to import) uses a local Hoogle cache.
If the model reports it cannot find functions, build the cache once with
make search-cache from the repo.
A notebook isn't only for editing. Sabela serves the same notebook as a live
dashboard at /dashboard and a slideshow at /slideshow, and it can
export to a file you can hand off:
GET /api/export/… |
Output |
|---|---|
markdown |
the notebook as plain .md |
dashboard / slideshow |
a standalone HTML page with the notebook baked in |
haskell |
a runnable .hs cabal script, sliced to a cell's dependencies |
lhs |
literate Haskell |
reactive |
a headless reactive-banana program |
Since the source of truth is Markdown, the simplest export of all is just saving the file.
Drop this into examples/minimal.md for reactivity, Markdown output, and an
SVG plot in one file:
# A tiny Sabela notebook
```haskell
numbers = [1..10]
```
```haskell
squares = map (^ (2 :: Int)) numbers
```
```haskell
print squares
```
```haskell
displayMarkdown $ unlines
[ "# Summary"
, ""
, "Squares for " ++ show (head numbers) ++ " through " ++ show (last numbers) ++ "."
, ""
, "- Count: " ++ show (last numbers)
, "- Max: " ++ show (last squares)
]
```Edit numbers and the three cells below it update.
examples/CaliforniaHousing.md is a full end-to-end notebook on the California
housing dataset. It walks through:
- loading data with
DataFrame - inspecting rows and computing summaries
- categorical frequencies and histograms
- engineering derived features
- typed column references via Template Haskell
- scatter plots of the spatial structure
- correlations against the target variable
- training a Hasktorch linear-regression model
- evaluating predictions on held-out districts
If you'd rather start smaller, examples/Iris.md trains a decision tree on the
classic Iris set, and examples/grammar-of-graphics.md builds layered charts
with Granite's grammar-of-graphics API.
The lookup panel queries the live session for completions, :info, :type,
and :doc. Once a notebook has loaded its modules and defined its names, you can
inspect them from the same session you're running cells in, which is useful when
you're learning an API as you go.
Sabela's file explorer is rooted at the working directory, so you can open existing notebooks, create files and directories, and save back to disk from the UI. Because notebooks are plain Markdown, a layout like:
examples/
basics.md
plotting.md
CaliforniaHousing.md
is just files on disk and works naturally with Git and code review.
When a cell fails, Sabela captures GHCi's stderr and parses it into structured errors, with line and column information where GHCi provides it. Fixing a broken upstream cell repairs its dependents on the next rerun.
A few things that help:
- keep imports and
-- cabal:directives near the top - give complicated definitions their own cell
- prefer named helpers over deeply nested one-liners
- use
printfor debugging and thedisplay*helpers for presentation
Sabela keeps one long-lived GHCi process per notebook, started with
-ignore-dot-ghci plus the extensions and package environment from the
notebook's metadata. To run a cell it:
- parses the source as a script fragment
- renders it into GHCi script text
- sends those lines to the session
- writes a unique marker after them
- drains stdout until the marker appears
- collects stderr separately
- parses out MIME markers and error locations
- broadcasts the result to the frontend
The marker is the trick that lets one long-lived process serve a whole notebook while keeping each cell's output separate. Python cells work the same way against their own REPL.
Sabela is a young project with some rough edges. The constraints worth knowing about:
- each language runs in a single session for the notebook
- changing the package environment restarts that session
- the Haskell↔Python bridge passes values as strings, not live objects
Notebooks read best when you:
- put setup first: directives, extensions, imports, and small helpers up top
- give each step its own cell: loading, cleaning, feature engineering, plotting, modelling, interpretation
- name intermediate values instead of nesting everything in one expression
- avoid binding expensive values at the top level, to keep memory down
- write the prose as a document: explain what each step does and what its output means, so the notebook reads as well as it runs
