Clerk Module API Reference
Experimental
The Clerk module is experimental: its features, API and saved formats may change between releases, without deprecation.
The clerk module is the backend for Clerk, Celldega's AI tool for exploring and
interpreting its visualizations. It isn't an MCP server: it's the prompts, actions and
lookups that let Claude read and drive linked Celldega widgets and consult outside tools
(Enrichr, PubMed). It talks to Claude through the local claude CLI (kernel-side, no API
key) and reasons from the evidence Celldega gathers: the linked views, and the lookups
it asks for (ranked markers, Enrichr, PubMed). The paired widget is
celldega.viz.Clerk; lay it out beside
linked views with dega.viz.spatial_clustergram(..., clerk=True).
See the Clerk guide for a walkthrough and code snippets.
Clerk -- Celldega's AI tool for exploring and interpreting its visualizations.
.. warning:: Experimental. Clerk is a proof of concept: its features, API and saved formats may change between releases, without deprecation.
Not an MCP server: the prompts, actions and lookups that let Claude read and drive linked Celldega widgets and consult outside tools (Enrichr, PubMed).
This is the backend module (analysis, prompt building, data structures). The paired
visualization lives at celldega.viz.Clerk. Keeping the two separate mirrors the
rest of the library: dega.clerk does the reasoning/data work, dega.viz.Clerk
renders it.
Clerk talks to Claude via the local claude CLI (kernel-side, no API key). It reasons
from evidence that Celldega gathers -- the linked views' state, a Landscape screenshot,
lookups it asks for, and free-text context. A conversation continues in one CLI session:
follow-up rounds and later questions resume it and send only what changed, so the
conversation so far is read from the API's cache.
Example::
import celldega as dega
answer = dega.clerk.ask(
"What cell type is this?",
gene_list=["CD3D", "CD8A", "CD2"],
info="Cluster 5, Xenium lung",
)
ClerkBackendError
Bases: RuntimeError
Raised when the claude CLI is unavailable or returns an error.
Session
One CLI conversation: a question and its follow-up rounds.
The first call starts it (--session-id) with the full prompt; each later call
resumes it (--resume) and sends only what is new (lookup results, views that
changed). The API caches the conversation so far, so a follow-up round re-reads it
at about a tenth of the price instead of paying for all of it again; in a test, a
follow-up round on a 34k-token prompt cost $0.008 instead of $0.12.
The CLI saves the transcript (under ~/.claude/projects) so it can be resumed;
close deletes it and the working directory. Transcripts left behind by a
crashed kernel are removed the next time a Session starts.
close()
Delete the saved transcript and the working directory.
totals(since=0)
Tokens and the CLI's cost estimate summed over the calls so far (from call
number since: a session can carry several questions).
actions_help(*, clustergram, landscape=False, yearbook=False, anndata='')
How Clerk can look things up, and change the linked Clustergram / Landscape /
Yearbook (anndata: a description of the cells it can select from, or "").
ask(question, gene_list=None, enrichr_terms=None, info='', image_b64=None, model='', timeout=DEFAULT_TIMEOUT, effort='', history=None, clustergram_state=None, notes=None, enrich_state=None, yearbook_state=None, actions_help=None, lookups=None, landscape_state=None, neighborhoods=None, session=None, briefing='', history_questions=None, history_chars=None)
Build the prompt from evidence (and earlier turns) and run the model.
With a Session, this starts it; continue with follow_up.
build_follow_up(notes=None, lookups=None, clustergram_state=None, landscape_state=None, neighborhoods=None, enrich_state=None, yearbook_state=None, has_image=False)
The message for a follow-up round: only what is new since the last message.
build_next_question(question, *, unchanged=None, since='', gene_list=None, enrichr_terms=None, clustergram_state=None, landscape_state=None, neighborhoods=None, enrich_state=None, yearbook_state=None, has_image=False, notes=None, actions_help=None)
The message for a new question in a conversation that continues one session.
Clerk already has the earlier questions, its answers and the evidence it was shown
in the session, so this carries only what changed since: the views whose state
differs from what Clerk last saw (unchanged names the others), the selected
genes or Enrichr terms if they changed, and since (what happened in the panel
between questions, e.g. labels Clerk applied or an analysis that ran).
build_prompt(question, gene_list=None, enrichr_terms=None, info='', has_image=False, history=None, clustergram_state=None, notes=None, enrich_state=None, yearbook_state=None, actions_help=None, lookups=None, landscape_state=None, neighborhoods=None, briefing='', history_questions=None, history_chars=None)
Assemble the prompt for one question from the gathered evidence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The user's free-form question. |
required |
gene_list
|
list[str] | None
|
Marker / differentially expressed genes for the cluster. |
None
|
enrichr_terms
|
list[dict] | None
|
Pre-fetched Enrichr results, each a dict with at least
|
None
|
info
|
str
|
Any extra free-text context (dataset, cluster id, notes). |
''
|
has_image
|
bool
|
Whether a Landscape raster is attached to the message. |
False
|
history
|
list[dict] | None
|
Earlier turns, |
None
|
clustergram_state
|
dict | None
|
A Clustergram snapshot ( |
None
|
notes
|
list[str] | None
|
Short notes about the evidence, e.g. that a linked view didn't reply. |
None
|
enrich_state
|
dict | None
|
An Enrich snapshot ( |
None
|
yearbook_state
|
dict | None
|
A Yearbook snapshot's observed state (its query, page and
cells); see |
None
|
actions_help
|
str | None
|
How Clerk may change the linked views (e.g.
|
None
|
lookups
|
list[str] | None
|
Results of lookups Clerk asked for (markers, Enrichr, PubMed). |
None
|
landscape_state
|
dict | None
|
A Landscape snapshot ( |
None
|
neighborhoods
|
list[dict] | None
|
Drawn neighborhoods ( |
None
|
briefing
|
str
|
Earlier work the scientist chose to share (Markdown), e.g. from an
exported Clerk record; capped at |
''
|
history_questions
|
int | None
|
How many recent questions of |
None
|
history_chars
|
int | None
|
Character budget for |
None
|
claude_auth_status(timeout=15)
Report whether the local claude CLI is logged in, without a model call.
Runs claude auth status --json. Account details such as the email address and
organization are deliberately dropped so they don't end up in notebook output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Seconds before the check gives up. |
15
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
|
dict
|
the CLI reports them, or |
claude_available()
Return True if the claude CLI is on PATH.
describe_anndata(adata, *, max_columns=24, max_categories=40, max_genes=300)
Describe an AnnData's cells for selecting them: its size, its genes (all of
them up to max_genes), whether its values look like counts, and each obs
column with its categories or numeric range ("" without an AnnData).
extract_actions(answer)
Split an answer into its text and any celldega-actions block.
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
str
|
|
dict | None
|
|
|
str | None
|
an optional |
|
tuple[str, dict | None, str | None]
|
malformed block. |
extract_findings(answer)
Split an answer into its text and any celldega-findings block.
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
str
|
|
dict | None
|
(e.g. |
extract_views(answer)
Split an answer into its text and any celldega-views block.
A view is what Clerk wants to show for a point it makes: {"caption": ...,
"landscape": {...}, "clustergram": {...}} with apply_state settings (see
VIEW_KEYS). The answer cites it as [Fig 1A](view:1A); nothing changes
until the scientist clicks. Invalid views are dropped and reported.
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
str
|
|
dict | None
|
|
follow_up(session, *, notes=None, lookups=None, clustergram_state=None, landscape_state=None, neighborhoods=None, enrich_state=None, yearbook_state=None, image_b64=None, model='', timeout=DEFAULT_TIMEOUT, effort='')
Continue a started Session with only what is new (see build_follow_up).
format_clustergram_state(state, *, max_value_rows=25, max_value_cols=20)
Render a Clustergram snapshot (Clustergram.latest_state) as compact text.
Lists the visible rows and columns with their attributes, the order, marker level,
dendrogram groups and selection, plus a capped table of values (and dot sizes).
Returns "" for an empty snapshot.
format_enrich_state(state, *, max_genes=12)
Render an Enrich snapshot (Enrich.latest_state) as compact text.
Returns "" when there is nothing to report (no gene list).
format_landscape_state(state, neighborhoods=None)
Render a Landscape snapshot (Landscape.latest_state) and drawn neighborhoods
(Landscape.neighborhood_summary()) as compact text.
format_yearbook_state(state, *, max_cells=30)
Render a Yearbook snapshot (its query, page and the cells shown) as short text.
A Yearbook is a grid of portraits of single cells, chosen by a query (a cluster's cells, ranked by a gene's expression when one is given), a page at a time.
next_question(session, question, *, image_b64=None, model='', timeout=DEFAULT_TIMEOUT, effort='', **evidence)
Ask a new question in a started Session, sending only what changed
(see build_next_question).
resolve_dendrogram_groups(views, clustergram_state)
Pin each view's dendrogram_group to the Clustergram state Clerk saw.
Clerk names a group as listed in the Clustergram snapshot, e.g.
{"dendrogram_group": {"axis": "col", "name": "39"}}. Group names depend on
the dendrogram cut, so the view keeps that cut and selects the group by its
members (by name when the snapshot lists only some of them). Groups the
snapshot doesn't show are dropped from the view and reported.
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[dict | None, list[str]]
|
|
run_claude(prompt, image_b64=None, model='', timeout=DEFAULT_TIMEOUT, effort='', session=None)
Call the claude CLI (no tools) and return the answer text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The fully-assembled prompt (see |
required |
image_b64
|
str | None
|
Optional base64 PNG payload (no |
None
|
model
|
str
|
Optional model alias or id (e.g. |
''
|
timeout
|
int
|
Seconds before the subprocess is killed. |
DEFAULT_TIMEOUT
|
effort
|
str
|
Reasoning effort ( |
''
|
session
|
Session | None
|
Optional |
None
|
run_turn(answer=None, *, max_rounds=6, pending_actions=None)
Interpret a reply, perform bounded evidence rounds, or emit resumable pause.
apply returns {changes: [...], reads: {...}} only after completion, or
{error: message}. observe receives that result and returns host evidence;
follow_up receives that evidence and returns the next model reply string.
A pause carries actions which can start a new invocation via pending_actions.