Metadata-Version: 2.4
Name: spine-assistant
Version: 0.1.0.post1
Summary: Natural-language-to-script assistant for the SPINE neuronal simulator
Author: Zachary M. Miksis, Gillian Queisser
Maintainer-email: "Zachary M. Miksis" <miksis@temple.edu>
License-Expression: LGPL-3.0-or-later
Keywords: neuroscience,simulation,SPINE,assistant,code generation
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: COPYING
License-File: COPYING.LESSER
Requires-Dist: numpy>=2.2.4
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.40; extra == "anthropic"
Provides-Extra: mcp
Requires-Dist: mcp>=1.0; extra == "mcp"
Dynamic: license-file

# spine-assistant

Turns a short JSON specification of an experiment into a runnable SPINE script. An LLM can write the specification from a sentence. The script comes from a template, so the model never writes SPINE code.

By default it talks to a local [Ollama](https://ollama.com) model: no API key, no cost, nothing leaves your machine. A hosted provider (Anthropic) is optional.

## Installation

```bash
pip install spine-assistant
```

This installs the `spine-assistant` command (Python ≥ 3.10, NumPy). Extras:

```bash
pip install "spine-assistant[anthropic]"    # hosted Claude backend
pip install "spine-assistant[mcp]"          # MCP server
```

`pipx install spine-assistant` installs the command into its own environment. Running the generated scripts needs SPINE (`pip install spine-neuro`). The SPINE User Guide has a chapter on the assistant: <https://zacharymiksis.com/research/software/>.

Start the web UI with `spine-assistant serve`.

## How it works

```
  natural language ──▶ [ LLM ] ──▶ spec.json ──▶ [ validate ] ──▶ [ render ] ──▶ script.py
   (a human sentence)  llm.py      constrained     physics/API      template     runnable
                       (Claude,     JSON object     checks           (no free-    SPINE code
                        structured                   │               form codegen)
                        outputs)                     └─ on failure, the errors are
                                                        fed back to the model
                                                        (validate → repair loop)
```

The model fills a typed spec. Structured outputs constrain its response to the schema. Validation errors go back to it for up to `--max-repair` rounds before the spec reaches the renderer.

Before each call, the most similar request/spec pairs from `dataset/` are retrieved by TF-IDF (`retrieval.py`) and shown to the model as few-shot examples. `generate --examples N` sets how many; 0 disables them.

### What the validator checks

- Method names, argument names and the calcium-first model structure are fixed in `render.py`.
- `IP3R` in a mechanism list enables `IP3`, with a warning. SPINE builds the IP3 receptor from `model['IP3']` and has no `IP3R` flag.
- Ionic currents or VDCC without voltage coupling, `dt >= T`, stimulus nodes out of range, and a large `dt` on a stiff Na⁺ membrane without the implicit solver are errors.
- A concentration outside the µmol/µm³ range is rejected with a unit reminder.
- A `network` without connections becomes a single neuron. A spec without a recording gets the calcium field and the soma.
- Every generated script carries an `Assumptions` block: calcium solved, source-default kinetics, units.

## Usage

```bash
# The JSON Schema an LLM targets:
spine-assistant schema

# The example specs ship with the package:
SPECS=$(python -c "import spine_assistant, pathlib; print(pathlib.Path(spine_assistant.__file__).parent / 'specs')")

# Check and explain a spec:
spine-assistant validate "$SPECS/active_ap.json"
spine-assistant explain  "$SPECS/calcium_wave.json"

# Render a script from a hand-written spec:
spine-assistant build "$SPECS/calcium_wave.json" -o run.py
python run.py

# The local web UI:
spine-assistant serve         # opens http://127.0.0.1:8765

# One-shot from the terminal (local Ollama model by default):
spine-assistant generate \
  "a calcium wave triggered by a synapse at the tip of a 100um dendrite" \
  -o run.py --spec-out run.spec.json
```

`$SPECS/_invalid_demo.json` is broken on purpose. Run `validate` on it to see every check fire.

### Web UI

`spine-assistant serve` starts a local page (standard library only). Type an experiment or dictate it with the browser's Web Speech API. The page shows the interpretation, any warnings and the generated script. The script box is editable, and Copy, Download and Run use what it shows. Everything runs on `127.0.0.1`; with the default Ollama provider nothing leaves your machine.

- **📄 Load request…** reads a `.txt` or `.md` request into the box, like `generate --file`.
- **🧩 Build from spec…** renders a script from a saved `.json` spec without a model, like `build`. It posts to `/api/build`, which only validates and renders.

The **AI model** field lists the models found on the selected backend (Ollama `/api/tags` or the OpenAI-compatible `/models`). You can type any name, and `↻` detects again. If the server is down, the field takes free text.

The `launchers/` folder of the source archive (Zenodo, DOI [10.5281/zenodo.24226059](https://doi.org/10.5281/zenodo.24226059)) holds double-click shortcuts, `SPINE Assistant.command` for macOS and Linux and `SPINE Assistant.bat` for Windows. They start `serve` and open the browser, and need Python and the package installed (see `launchers/README.md`).

**Running scripts.** A generated script is shown but not run. **▶ Run this script** appears below it. A click asks for confirmation (with an option to stop asking for the session), then runs the script in a temporary directory. A terminal panel streams the command, the solver output, the exit status, the output files and a `.zip` of the results. The server refuses `/api/run` until the confirmation arms it.

```bash
spine-assistant serve                          # Run asks to confirm before executing
spine-assistant serve --allow-run              # pre-confirm at launch (container, automation)
spine-assistant serve --no-run                 # Run disabled
spine-assistant serve --provider anthropic     # Claude instead of Ollama
```

## MCP server

`spine-assistant mcp` exposes the pipeline as [MCP](https://modelcontextprotocol.io) tools, so the model of an MCP host (LM Studio, Claude Desktop) can call them. The host's model writes the spec. The tools validate and render it.

```bash
pip install "spine-assistant[mcp]"
spine-assistant mcp --install-lmstudio   # adds 'spine' to LM Studio's mcp.json (backs it up)
```

Restart LM Studio afterward. If the command cannot find LM Studio's config, it prints the block to paste. `spine-assistant mcp --check` verifies the install, and `--config` prints the config.

Tools: `validate_spine_spec`, `render_spine_script` (spec to script, no model), `build_spine_channel` (a catalog channel class) and `build_spine_custom_channel` (a channel from your own Hodgkin–Huxley gate kinetics). Resources: `spine://catalog`, `spine://schema`, `spine://reference` and `spine://guide`.

`spine://guide` tells the host's model that channels outside the named catalog are supported. The classic HH currents (fast Na⁺, delayed rectifier Kd, leak) come from a spec's `currents` field, voltage-gated calcium channels from `vdcc_type` and `vdcc_extra`, named channels from `catalog_channels`, and anything else from `build_spine_custom_channel` or `custom_channels`. SPINE needs no `.mod` files and no NEURON.

**Units.** Papers quote mV, ms and per-cm². SPINE uses V, s and per-µm². An `E_rev` above 1 V is read as millivolts and converted to volts. An out-of-scale `g_max` or a `tau` above a second raises a warning with the conversion (`E_rev`, `tau`: ÷1000; rates: ×1000; `g_max`: S/cm² → ÷1e8).

Run `spine-assistant mcp` only from the host. A stdio server has no output and waits for a client. Use `--check` to test it.

Configure LM Studio (Program → Edit `mcp.json`) or Claude Desktop with absolute paths. The host does not inherit your shell `PATH`, which matters in a conda or venv environment:

```json
{ "mcpServers": {
    "spine": { "command": "/full/path/to/env/bin/spine-assistant", "args": ["mcp"] }
} }
```

Find the path with `which spine-assistant`, or launch through the interpreter: `"command": "/full/path/to/python", "args": ["-m", "spine_assistant", "mcp"]`. The `mcp` package must be installed in that environment; `spine-assistant mcp --check` prints which python it uses.

The server exposes no code-execution tool. It returns the script, and you run it.

## Docker

The `docker/Dockerfile` of the source archive (Zenodo, DOI [10.5281/zenodo.24226059](https://doi.org/10.5281/zenodo.24226059)) builds an image with SPINE, the assistant and the web UI, and runs the whole loop in the container: no local Python, no model download, no GPU. It defaults to Claude, which keeps the image small.

```bash
# from the top folder of the source archive:
docker build -f tools/spine_assistant/docker/Dockerfile -t spine-assistant .
docker run --rm -e ANTHROPIC_API_KEY=sk-ant-... -p 8765:8765 spine-assistant
# open http://127.0.0.1:8765
```

For a fully local setup, run Ollama on the host and point the container at it:
`docker run -e SPINE_PROVIDER=ollama -e OLLAMA_HOST=http://host.docker.internal:11434 -p 8765:8765 spine-assistant`.

## `generate`

`generate` turns a sentence into a spec, validates it (repairing up to `--max-repair` times) and renders the script. It prints the interpretation and warnings to stderr, so you can check the model's reading before running the code.

- The default provider is `ollama`: install Ollama and run `ollama pull qwen2.5`, the default model. It follows the spec schema better than `llama3.1`. `generate` and `serve` then work with no key. With no server reachable they exit with a message and code 2.
- `--provider openai` targets any OpenAI-compatible server: LM Studio (default, `http://localhost:1234/v1`), llama.cpp's `server`, Jan, vLLM, or hosted OpenAI and OpenRouter. Set `OPENAI_BASE_URL` to retarget, and `OPENAI_API_KEY` for hosted servers. LM Studio serves the loaded model, so `--model` is optional there.
- `--provider anthropic` uses the hosted API with `ANTHROPIC_API_KEY` or an `ant auth login` profile. `--model` overrides any default.
- Model size sets speed. Thin laptop: a 3B model (`--model llama3.2:3b` or `qwen2.5:3b`). Desktop: `qwen2.5` (7B, the default) or `qwen2.5:14b`. Workstation: `qwen2.5:32b`. No local compute: Claude. If a local model is too slow, use a smaller size or another provider.
- `python -m spine_assistant.test_llm_offline` runs the pipeline against stubs with no key and no model: LLM wiring with a forced repair, kinetics-safety rejection, a custom-channel render and the web pipeline.

## Custom channels and kinetics

Rate formulas are data. A formula is parsed to an AST, checked against a whitelist (arithmetic and a fixed set of math functions over the declared variables), sanity-checked numerically on a grid, and rewritten into the generated channel class. Imports, attribute access, calls to unknown names and comprehensions are rejected before rendering.

- `custom_channels` render a `ChannelModel` subclass: ohmic `compute_current` and `conductance` in volts, and gates with kinetics in mV and µmol·µm⁻³ that return `(x_inf, tau_seconds)`. A calcium-activated channel (SK, BK) is a gate whose `x_inf` depends on `C`; see `specs/custom_sk_channel.json`.
- `custom_mechanisms` render a `PMFluxMechanism` or `ERFluxMechanism` subclass that returns an unsigned magnitude. The `sign` field routes it (+1 influx, −1 efflux).

The generated script's assumptions block and the model's system prompt state the units.

## Files

The package holds the modules below. `docker/`, `launchers/` and `../pyproject.toml` are in the source archive only.

| File | Role |
|------|------|
| `schema.py`   | Allowed vocabulary, defaults and the JSON Schema an LLM targets |
| `validate.py` | Physics and API consistency checks: errors, warnings, assumptions |
| `render.py`   | Deterministic spec → SPINE script; the only place code is emitted |
| `kinetics.py` | AST-whitelist compiler for custom rate and flux expressions |
| `explain.py`  | Plain-language summary of a spec |
| `llm.py`      | Natural language → spec: Ollama, OpenAI-compatible servers (LM Studio) or Claude; structured outputs, repair loop, few-shot examples |
| `retrieval.py`| TF-IDF retrieval over `dataset/` for the few-shot examples |
| `webapp.py`   | Local web UI and run loop (`http.server`, Web Speech API) |
| `mcp_server.py` | The MCP server |
| `cli.py`      | `generate`, `serve`, `build`, `validate`, `explain`, `schema`, `mcp` |
| `docker/`     | Dockerfile that runs the whole loop in a container |
| `launchers/`  | Double-click shortcuts (`.command`, `.bat`) that open the web UI |
| `dataset/`    | Validated request → spec corpus for few-shot retrieval and fine-tuning; `build_dataset.py` authors and verifies it |
| `test_llm_offline.py` | Offline stub tests: wiring, kinetics safety, custom channel, web app, run loop |
| `specs/`      | Example specs, including a custom-channel demo and an invalid one |
| `../pyproject.toml` | The installable package and the `spine-assistant` entry point (in `tools/`) |

## Limits

- No GPU batch backend. Networks and single neurons render for the serial and MPI CPU path (`solve` detects `mpirun`). The batched `backend='gpu'` path needs batch channel methods and a device-partitioned neuron list, so it is not generated. Custom channels and mechanisms render for the serial and MPI path only.
- Smooth kinetics only. The expression grammar is arithmetic plus standard functions (exp, log, sqrt, tanh, …). Piecewise rate laws are not expressible; use a smooth approximation or write the channel by hand.
