Metadata-Version: 2.4
Name: napari-chat-assistant
Version: 2.5.0
Summary: Local AI and deterministic workbench for napari image-analysis workflows
Author: Wulin Teo
License-Expression: MIT
Project-URL: Homepage, https://github.com/wulinteousa2-hash/napari-chat-assistant
Project-URL: Repository, https://github.com/wulinteousa2-hash/napari-chat-assistant
Project-URL: Issues, https://github.com/wulinteousa2-hash/napari-chat-assistant/issues
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: napari
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Image Processing
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: matplotlib
Requires-Dist: markdown-it-py
Requires-Dist: napari
Requires-Dist: numpy
Requires-Dist: numcodecs
Requires-Dist: ome-zarr
Requires-Dist: qtpy
Requires-Dist: scipy
Requires-Dist: scikit-image
Requires-Dist: zarr
Provides-Extra: voice
Requires-Dist: faster-whisper; extra == "voice"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Dynamic: license-file

# napari-chat-assistant

[![License MIT](https://img.shields.io/pypi/l/napari-chat-assistant.svg?color=green)](https://github.com/wulinteousa2-hash/napari-chat-assistant/raw/main/LICENSE)
[![PyPI](https://img.shields.io/pypi/v/napari-chat-assistant.svg?color=green)](https://pypi.org/project/napari-chat-assistant)
[![Python Version](https://img.shields.io/pypi/pyversions/napari-chat-assistant.svg?color=green)](https://python.org)
[![napari hub](https://img.shields.io/endpoint?url=https://api.napari-hub.org/shields/napari-chat-assistant)](https://napari-hub.org/plugins/napari-chat-assistant)

Local, Ollama-powered AI and deterministic workbench for napari image-analysis workflows.

`napari-chat-assistant` adds a dock widget inside napari that understands the active viewer session, runs built-in image-analysis actions, generates executable napari Python code when a request goes beyond the current toolset, and lets users promote repeatable tasks into one-click shortcuts.

The goal is not to bolt a generic chatbot onto a viewer. The goal is to turn napari into a more practical analysis workspace for people who work with microscopy and other large multidimensional imaging datasets, especially users who want local AI help, reproducible workflows, direct control over their data, and fewer clicks per task.

## What's New In 2.5.0

Version `2.5.0` adds a shared tool executor and stronger checks on what counts as success.

- **Shared execution:** chat, Agent mode, deterministic workflows, Actions and Shortcuts use the same registered-tool lifecycle through compatible adapters.
- **Structured outcomes:** operation status, failure phase/code, output-layer references and phase timings are available independently of task verification. Computing an array alone does not establish that it was applied to the viewer.
- **Intent guards:** explanation-only, code-only and explicit no-execution requests block automatic tools. Requests such as "apply Gaussian denoising and explain the result" remain executable.
- **Honest verification:** completing only the binary-conversion part of a larger task cannot approve the whole task. Missing inputs and failed tools remain failures, including in Agent observations and local tool sequences.
- **Execution controls:** the shared executor checks cancellation before compute/apply, validates job/result tool identity, and prevents applying the same in-process invocation twice.

This adopts a minimal harness design within the existing Python plugin; Pi is not an installed dependency or integrated runtime. Automatic workflow learning is not implemented. The chat interface, independent Fast/Agent toggles, and generated-code review remain in place. See the [2.5.0 validation prompts](#validation-prompts-for-250) and [changelog](CHANGELOG.md).

## What's New In 2.4.0

Version `2.4.0` adds experimental workflow-loop support and clearer evidence about what reviewed Python actually did.

- **Agent mode**, off by default and independent of Fast mode: inspect a tool result and take another step, up to three model calls with a configurable 90-second default time budget.
- **Run Code outcomes:** distinguish verified binary conversion, already-binary/no-change results, verification failures, and results that remain unverified. Reports include the target and observed layer changes.
- **Reliable completion tracking:** background jobs remain pending until their apply callbacks finish. Retries and refinement retain the original bounded input reference.
- **Coding reliability:** code-generation/repair requests use a JSON schema, coding-specific sampling, validation, and explicit runtime bindings for separate QtConsole snippets.
- **Performance comparison:** telemetry reports separate Agent mode on/off and Fast mode settings, including model calls, tokens, inference time, and tool time.

Review generated Python before running it. Automatic checks are task-specific and bounded; failed code can leave partial changes. See [CHANGELOG.md](CHANGELOG.md) for detailed changes and limits, and the [system-design guide](docs/system-design.md) for the updated execution paths.

## What's New In 2.3.4

Version `2.3.4` adds a saved `Fast mode` toggle beside the model selector.

- On: disable reasoning where supported, or use the model's lowest reasoning level for quicker routine responses.
- Off: use the model's default reasoning behavior for complex coding and analysis.
- Changes apply to the next request, and the preference is remembered across sessions. Fast mode starts off.
- Models without reasoning controls keep their normal behavior.

In a small local test of `nemotron-cascade-2:30b` on NVIDIA GB10, disabling reasoning reduced median response time from 4.73 to 1.90 seconds across four brief-question requests per setting. This does not establish equivalent quality for complex tasks. See the [performance validation and reproduction steps](docs/local_chat_performance_2026-11-09.md).

## What's New In 2.3.3

Version `2.3.3` reduces prompt overhead for local models.

Quick feature summary:
- UI-help prompt facts are no longer appended to every model request
- model requests now use smaller prompt profiles for tool routing, code generation, and code repair
- code-heavy turns send much less prompt text to Ollama

## What's New In 2.3.1

Version `2.3.1` improves local-model performance diagnostics and reduces the live viewer context sent to Ollama.

Quick feature summary:
- Ollama prompt/generation metadata is now captured in local telemetry
- telemetry summaries now include tokenization and local-model throughput diagnostics
- the model request uses a compact viewer-context payload instead of verbose per-layer profiler evidence
- Telemetry Log views show newest records first
- `Copy Report` copies a shareable Markdown telemetry report to the clipboard

## What's New In 2.3.0

Version `2.3.0` adds an optional local `Voice Input` workflow for users who prefer speaking prompts instead of typing them.

This update was added in response to feedback from Ron DeSpain on image.sc:
- https://forum.image.sc/t/napari-chat-assistant-experimenting-with-a-local-chat-assistant-inside-napari-looking-for-feedback/120351/2

Quick feature summary:
- optional `Voice Input` entry under `Advanced`
- local microphone recording with input-device selection
- live green input-level meter during recording
- local transcription with [`faster-whisper`](https://github.com/SYSTRAN/faster-whisper)
- editable transcript preview before execution
- direct `Run` from the voice window without an extra prompt-send step
- reusable non-blocking voice window that stays open while you work in napari

Important:
- voice input is optional and is not required for the base plugin
- it requires [`faster-whisper`](https://github.com/SYSTRAN/faster-whisper) installed in the same Python environment as napari
- microphone support also depends on the Qt multimedia stack available in that same environment

For complete release history, see [CHANGELOG.md](CHANGELOG.md).

## Who It Is For

This plugin is built for:
- imaging core facility users
- researchers, staff scientists, and students working with imaging data
- teachers and educators running imaging demos or training sessions
- It is also designed for users who prefer to describe analysis goals in natural language instead of memorizing commands or writing scripts.

It is especially useful when you:
- inspect large 2D or 3D image data in napari
- move between interactive viewing, measurement, and Python-based analysis
- want a local open-weight model instead of a cloud service
- need to save, reuse, restore, and teach common imaging workflows
- want fast deterministic actions and one-click shortcuts for repeated tasks

## Why It Is Different

This plugin is built from practical imaging workflow needs, not from the idea of putting a generic chatbot beside a viewer.

It is designed around how work actually happens in napari:
- start from the data already open in the viewer
- inspect layers, objects, and regions of interest
- run the next analysis step through chat, actions, templates, shortcuts, or code
- review the result directly in the same session
- save useful workflows for later reuse

The assistant is grounded in the live napari session. It can inspect loaded layers, use ROI context, run built-in analysis actions, generate or refine viewer-bound Python when needed, and support deterministic one-click workflows through `Actions` and `Shortcuts`. The result is closer to an imaging workbench than a chat panel.

## Interaction Model

The plugin now supports a deliberate spectrum of interaction styles:
- `Prompt`: AI-first natural language requests
- `Code`: direct viewer-bound Python for users who want exact control
- `Templates`: reusable examples and built-in starting points
- `Actions`: deterministic built-in functions that can be run directly
- `Shortcuts`: user-defined one-click action buttons for repeated daily work

This is now a core design principle of the plugin: reduce how many clicks and how much time it takes for a user to complete a task.

## Interface Overview

![Interface overview](docs/interface-overview.png)

The main dock is organized into a small number of practical work areas:

1. `Connection and model controls`
   Select the local model, monitor status, and manage the backend connection.

2. `Layer Context`
   Review the active workspace layers and insert exact layer names into prompts or code.

3. `Library`
   Browse reusable `Prompts`, `Code`, `Templates`, and deterministic `Actions`.

4. `Shortcuts`
   Keep your most-used actions as one-click buttons for repeated work.

5. `Session`
   Save or restore workspace state and access activity, telemetry, and diagnostics.

6. `Chat`
   See the assistant transcript, generated code, and direct action feedback in one place.

7. `Prompt`
   Enter natural language requests or paste Python for `Run My Code` and `Refine My Code`.

## What You Can Do

Current workflows include:
- inspect the selected layer or named layers with structured summaries
- review live layer context and insert exact layer names into prompts or code
- run built-in tools for enhancement, thresholding, binary mask cleanup, measurement, projection, cropping, montage, presentation, and layer visibility control
- add non-destructive annotation overlays, including free text, particle labels, callout labels with leader lines, and boxed titles above the image
- use deterministic `Actions` for common workflows without depending on prompt phrasing
- build and save your own `Shortcuts` layouts for repeated one-click work
- inspect ROI context and measure or extract values from `Labels`, `Shapes`, and line-based workflows
- use interactive analysis widgets such as `ROI Intensity Analysis`, `Line Profile Analysis`, and `Group Comparison Statistics`
- access SAM2 setup, live preview, box prompting, points prompting, and mask refinement from the same workbench
- browse built-in prompt templates, code templates, and learning templates for plugin workflows, teaching, and model testing
- generate napari Python code when no built-in tool is the right fit
- paste and run your own viewer-bound Python from the prompt box with `Run My Code`
- repair or explain broken pasted Python with `Refine My Code`
- save, pin, tag, rename, and reuse prompts and code from the local Library
- use built-in synthetic data generators for repeatable testing, teaching, and workflow development
- learn from built-in content for microscopy, electron microscopy, imaging physics, quantitative imaging, statistics, academic prompting, and language support
- save and restore workspace state with a JSON manifest plus OME-Zarr assets for generated image and labels data
- use optional local `Voice Input` from `Advanced` for microphone recording, transcript review, and direct prompt execution

Example requests:
- `Inspect the selected layer`
- `Preview threshold on the selected image`
- `Apply gaussian blur to the selected image with sigma 1.2`
- `Remove small objects from the selected mask with min_size 64`
- `Run watershed on the selected mask`
- `Measure labels table for the selected labels layer`
- `Annotate template_blob_labels with particle 1 to 4`
- `Annotate template_blob_labels using publication-style callout labels with leader lines.`
- `Add title WT Group N=10 above the image on the left`
- `Inspect the current ROI`
- `Extract ROI values from the selected image using the current ROI`
- `Open ROI intensity analysis`
- `Initialize a SAM2 points prompt layer for the selected image`
- `Write napari code to plot object area by condition`

## Local-First By Design

The assistant runs on local open-weight models through Ollama:
- no API key required
- no cloud dependency
- no internet requirement during normal use
- no image data leaves your workstation

This makes it a better fit for research and facility environments where users want privacy, controllability, and local reproducibility.

## Installation

Requirements:
- Python 3.11+
- napari
- Ollama running locally
- one local Ollama model, such as `nemotron-cascade-2:30b`

Install Ollama and start the server:

macOS and Linux:

```bash
curl -fsSL https://ollama.com/install.sh | sh
ollama serve
```

Windows:
- download and install Ollama from `https://ollama.com/download/windows`
- start the Ollama application or service

```bash
ollama pull nemotron-cascade-2:30b
```

Optional model alternatives:

```bash
ollama pull gpt-oss:120b
ollama pull qwen3-coder-next:latest
ollama pull qwen3.5
ollama pull qwen2.5:7b
```

Install the plugin:

```bash
pip install napari-chat-assistant
```

Optional voice input support:

```bash
pip install faster-whisper
```

Install `faster-whisper` in the same Python environment that launches napari if you want to use `Advanced -> Voice Input`.

Development install:

```bash
git clone https://github.com/wulinteousa2-hash/napari-chat-assistant.git
cd napari-chat-assistant
pip install -e .
```

The plugin does not bundle Ollama or model weights. Larger models may require substantial RAM or VRAM.

## Usage

1. Start napari.
2. Open `Plugins -> Chat Assistant`.
3. Leave `Base URL` as `http://127.0.0.1:11434` unless your Ollama server is elsewhere.
4. Choose a model from the `Model` dropdown or type a model tag manually.
5. Use `Load` if you want to warm the selected model before the first request.
6. Start chatting, or use the Library for repeatable tasks and reusable code.

Use `Fast mode` beside the model selector for quicker routine responses. On disables reasoning where supported, or selects the model's lowest reasoning level. Off uses the model's default reasoning behavior and is useful for complex coding and analysis. The preference is saved and applies to the next request; models without reasoning controls keep their normal behavior.

### Experimental Agent Mode

`Agent mode` is a separate, saved toggle beside `Fast mode`. It starts off. With Agent mode off, chat keeps its existing routing and single model-call behavior. With it on, the model can choose a tool, read a compact observation and refreshed layer context, and choose another action, up to **three model calls per request**. Manual code review and local help/follow-up shortcuts keep their existing behavior; Agent mode bypasses the predefined workflow router when a request reaches that router.

The loop automatically permits inspection, intensity/mask summaries, viewer controls, Gaussian denoising, threshold preview, and histogram plotting. It checks existing user-intent constraints before execution. Other tools stop the loop with an explanation; generated Python is staged for the existing validation and `Run Code` review flow and is never automatically executed by the loop.

The default time budget is **90 seconds**, adjustable from 10 to 600 seconds in `Connection` → `Agent time budget`. `Stop` cancels the loop and prevents further steps or application of late background results. Already applied results remain. In-flight model requests or tools may continue computing until they return or their connection times out; this is not a hard GPU/process kill or a rollback. The loop also stops on repeated consecutive tool actions, invalid/truncated responses, or a model-call limit and displays the available results and stop reason. A final model reply is not independent verification that the task succeeded.

To compare performance:

1. Enable optional telemetry in `Session` → `Telemetry`.
2. Run the same prompt with Agent mode off, then on. Keep the model, Fast mode setting, starting layers, and model loading/cache conditions comparable. Restore any tool-created outputs or viewer changes before repeating a trial.
3. Open the telemetry report and inspect **Agent Mode Comparison**. It separates models and Fast mode settings and reports run counts, median total time, model calls, input/output tokens, inference wall time, and tool time. Agent cancellations and limits remain in the results; local shortcuts and older logs without mode instrumentation are excluded.

Agent runs show a step indicator and a final timing summary even when telemetry is disabled. Multiple calls usually add latency; use this experimental mode to evaluate whether observing intermediate tool results improves your tasks enough to justify that time.

### Validation Prompts For 2.5.0

The existing examples below and Agent performance-comparison procedure above remain available. These additional checks exercise the shared executor, intent guards, and result verification.

**Setup:** load an image and a Labels layer, such as `density` and `labels`. Duplicate the Labels layer and select the duplicate for tests that edit data. Keep an untouched original or reload it before each destructive test. Use ordinary NumPy data with at most 1,000,000 elements for binary verification; larger/lazy/custom arrays remain unverified. Keep Fast mode unchanged across comparisons, and enable optional telemetry under `Session` → `Telemetry` if you want to inspect execution metadata. A model timeout or step limit means the trial is incomplete.

**1. Explanation-only guard — Agent mode on or off**

```text
Only explain how to convert nonzero values in the selected Labels layer to 1. Do not execute anything or change any layer.
```

Expected: an explanation, or a blocked-tool message if the model attempts an action. No tool should execute and no layer should change.

**2. Shared tool execution — Agent mode on, Labels layer selected**

```text
Use inspect_selected_layer to inspect the selected Labels layer. Report its name, shape, dtype, and available mask statistics. Do not modify any layer.
```

Expected: actual inspection activity and a report for the selected layer, with no edits. The telemetry tool observation should contain a `tool_execution` outcome with `status: succeeded`, execution ID and phase timings. `task_verified: false` is expected for a generic tool outcome; operation completion is separate from scientific verification. A text-only reply without tool activity does not exercise the executor. Agent requests receive compact outcome facts; the full metadata stays in telemetry.

**3. Verified binary conversion — Agent mode off, duplicate Labels layer selected**

```text
Write Python code to convert all nonzero values in the selected Labels layer to 1. Preserve original dtype.
```

Review the Python, then click `Run Code`. Expected: **Verified binary conversion** or **No change needed** if the input is already binary. The bounded check verifies foreground 1, background 0, original shape and dtype. Confirm that the original layer stayed untouched; colors alone do not prove array correctness.

**4. Partial-task protection — restore the duplicate before testing**

```text
Write Python code to convert the selected mask to binary and remove small objects.
```

Review the Python, then click `Run Code`. Expected: the overall result remains **unverified**, even if both operations appear to work, because the current binary verifier cannot prove the additional cleanup requirement. Code that performs only binary conversion must not approve the entire task or promote it as a verified success.

**5. Missing-input failure — separate empty viewer, Agent mode on or off**

```text
Use gaussian_denoise to denoise the selected image with sigma 1.
```

Expected: a clarification or a missing-image error, with no output layer. If a tool was attempted, telemetry should record a rejected/failed operation rather than a successful tool run. A clarification alone does not exercise the failure path. Reload your image before continuing with normal examples.

These are manual acceptance checks, not a guarantee of model accuracy on every request. The executor's cancellation and duplicate-application safeguards also have automated regression coverage. Each newly submitted request is a new invocation; submitting the same prompt twice is not a duplicate-application test.

The assistant works best when prompts describe a concrete action. If you already have Python code, paste it into the Prompt box and use `Run My Code`. If pasted code fails or needs adaptation to the current viewer, use `Refine My Code`.

For code you plan to paste into napari's separate QtConsole, say `napari console` or `QtConsole` in the request. Those snippets bind their own selected layer and import the names they use; plugin-only helper variables are not assumed. Code-generation and repair requests use structured JSON output and coding-specific sampling settings, then pass through local Python validation. Review generated code before running it; structured output does not guarantee that its algorithm is correct.

Run Code now separates runtime completion from verification of the requested result. For an explicit request such as “Convert nonzero values in the selected Labels layer to 1 and preserve the original dtype,” it checks foreground/background values, shape, and dtype, then reports the target, changed-value count, and label values before/after. An already-binary mask reports **no change needed**; a wrong result reports **verification failed**. Switching away from that request's target requires reviewing the target before execution.

Retries, `Refine My Code`, and resubmitting the same failed binary-conversion goal keep the original input reference. A failed attempt that destroys background pixels cannot pass the next check simply because the modified array now contains only ones. Failed code may have left partial changes: restore or reload the source if needed before retrying; this feature does not automatically roll changes back. Composite tasks and additional changes to other layers require review rather than a narrow binary-conversion success claim.

Other code reports observed layer changes and **finished, unverified** unless a task-specific rule applies. Exact array checks are limited to ordinary NumPy arrays with at most one million elements each and a 16 MiB snapshot budget per before/after capture. Large/lazy/custom data is not loaded just to verify a result. These checks inspect layer data and a small set of layer properties, not every possible file, widget, or scientific output.

Code that uses `run_in_background` remains pending until every background computation and apply callback finishes. Failures are reported as failures with potentially partial changes; launching work is not counted as completion. Only a locally verified task result automatically promotes its pending memory items to approved. Telemetry reports separate Python runtime completion from checked task outcomes.

### Optional Voice Input

`Advanced -> Voice Input` opens a small reusable voice window for users who want a local speech-to-text path inside napari.

The flow is:
- choose the microphone input device
- start and stop recording
- watch the live input-level meter to confirm the mic is active
- review and edit the transcript
- press `Run` or hit `Enter` to execute it directly

This feature is intentionally optional and advanced. It depends on [`faster-whisper`](https://github.com/SYSTRAN/faster-whisper) being installed in the same Python environment as napari.

Examples:
- `Inspect the selected layer`
- `Preview threshold on em_2d_snr_mid`
- `Apply gaussian denoise to em_2d_snr_low with sigma 1.2`
- `Fill holes in mask_messy_2d`
- `Remove small objects from mask_messy_2d with min_size 64`
- `Measure labels table for rgb_cells_2d_labels`
- `Annotate template_blob_labels with publication-style callout labels`
- `Create a max intensity projection from em_3d_snr_mid along axis 0`
- `Crop em_2d_snr_high to the bounding box of em_2d_mask with padding 8`
- `Extract ROI values from em_2d_snr_mid using em_2d_mask`
- `Prepare this viewer for image review`
- `Undo last workflow`

## Core Workflow

1. Open your image or volume in napari.
2. Use `Layer Context` to inspect loaded layers or insert exact layer names into the Prompt box.
3. Ask for a concrete action, or browse `Actions` when you want deterministic execution.
4. Use `Templates` for reusable prompt/code examples and `Shortcuts` for repeated one-click workflows.
5. Use generated code, `Run My Code`, or `Refine My Code` when a task needs custom Python.
6. Save useful prompts, code snippets, workspace state, and shortcut layouts for later reuse.

This keeps inspection, analysis, code review, and workflow reuse close to the current napari session.

## Synthetic Data Templates

Use the Library `Templates > Code Templates > Data Setup` area or built-in code snippets to load repeatable synthetic datasets.

Current built-in synthetic generators include:
- Synthetic 2D SNR Sweep Gray
- Synthetic 3D SNR Sweep Gray
- Synthetic 2D SNR Sweep RGB
- Synthetic 3D SNR Sweep RGB
- messy masks 2D/3D

These create named layers so you can test built-in tools quickly without hunting for sample data. Labels layers from these synthetic datasets can also be used as ROIs for ROI inspection and value extraction.

## Feature Summary

Built-in workflows include:
- layer inspection and live layer-context insertion
- Quick Controls for fit view, zoom, 2D/3D mode, axes, scale bar, tooltips, overlays, grid view, and layer visibility
- enhancement, thresholding, mask cleanup, connected components, labels measurement, projection, cropping, montage, and presentation helpers
- ROI inspection and value extraction from `Labels`, `Shapes`, and line-based workflows
- annotation overlays, including free text, particle labels, callouts, and boxed titles
- workspace save/restore with a JSON manifest plus OME-Zarr assets for generated image and labels data
- deterministic `Actions`, reusable `Templates`, and user-defined `Shortcuts`
- optional advanced workflows such as Voice Input and SAM2

### Code generation workflows

When a request is not covered by a built-in tool, the assistant can return napari Python code instead of forcing the wrong tool.

Generated code can be:
- copied to the clipboard
- reviewed in chat
- executed from the plugin
- repaired or explained in place when you use `Refine My Code` on pasted or failed user code

You can also paste your own Python directly into the Prompt box and run it from the plugin with `Run My Code`, without switching to QtConsole.

Use assistant-generated code when you want a reusable script or need custom logic beyond the current built-in tools.

Use `Run My Code` when you already have Python you want to test quickly inside the current napari session.

Use `Refine My Code` when your own code fails validation, errors at runtime, or needs adjustment to the current napari viewer state.

## Library, Actions, And Shortcuts

The Library stores repeatable prompts, code snippets, templates, and deterministic actions.

Useful behavior:
- single click loads a prompt or code snippet into the editor
- double click sends a prompt or runs a code snippet
- templates can be previewed, loaded, or run
- actions can be previewed, run, or added to `Shortcuts`
- saved and recent prompts/code can be renamed, tagged, pinned, or cleared
- shortcuts can be arranged, saved, loaded, and reused across sessions

This is now part of the core product direction: keep AI available, but let mature workflows become fast, button-driven, and reusable.

## Optional Integrations

If `napari-nd2-spectral-ome-zarr` is installed, the assistant can open:
- the ND2-to-OME-Zarr export widget
- the Spectral Viewer widget
- the Spectral Analysis widget

This lets chat act as an entry point for Nikon ND2 conversion and spectral workflows without rebuilding those UIs inside this plugin.

Install links:
- GitHub: `https://github.com/wulinteousa2-hash/napari-nd2-spectral-ome-zarr`
- napari Hub: `https://napari-hub.org/plugins/napari-nd2-spectral-ome-zarr.html`

### Experimental SAM2

Behavior:
- SAM2 is accessed from `Advanced`, not from the main toolbar
- `SAM2 Setup` is always available from `Advanced`
- `SAM2 Live` stays disabled until the backend is configured and passes readiness checks
- the rest of the assistant remains usable even if SAM2 is not configured

Current setup expects:
- a working Python environment that already includes the dependencies required by SAM2
- an external SAM2 project path
- a valid checkpoint path
- a valid config path

`napari-chat-assistant` now ships its own bundled SAM2 adapter in
`napari_chat_assistant.integrations.sam2_adapter`, so users only need the SAM2 repo,
checkpoint, and config files in the normal places.

The `SAM2 Setup` dialog now includes:
- `Auto Detect` to scan common local clone locations and fill likely project, checkpoint, and config paths
- `Setup Help` for short setup commands and field tips

Minimal install:

```bash
git clone https://github.com/facebookresearch/sam2.git && cd sam2
pip install -e .
```

Typical setup flow:
1. Start napari from the environment that contains your SAM2 dependencies.
2. Open `Plugins -> Chat Assistant`.
3. Open `Advanced -> SAM2 Setup`.
4. Click `Auto Detect` first.
5. Confirm or edit the SAM2 project path, checkpoint path, config path, and device.
6. Click `Test`.
7. Save the settings.
8. Open `Advanced -> SAM2 Live` when the backend reports ready.

## How It Works

The assistant is designed to operate within constrained napari workflows rather than as a general-purpose chatbot.

The current strategy is:
1. resolve the request's intent, viewer context, and applicable local shortcuts or predefined workflows
2. execute matched local operations without a model call when possible
3. otherwise assemble the relevant prompt profile, compact layer context, and bounded session context for Ollama
4. in normal mode, handle one model response as a reply, registered-tool action, or pending code proposal
5. in Agent mode, execute only allowlisted automatic tools and pass compact observations plus refreshed context into the next bounded model call
6. stage generated Python for review, preflight it again on Run Code, and report observed effects separately from task-specific verification
7. keep background executions pending until their compute/apply steps settle, and record runtime, checked outcome, and feedback information separately

This keeps the assistant more grounded than a plain chat interface and makes common operations more reliable.

Current viewer state and explicit user clarification remain the primary source of truth. Session memory is selective and secondary, not a full transcript memory system.

## Local Model Choices

For a broader list of models tested during development, see [docs/tested_models.md](docs/tested_models.md).

`nemotron-cascade-2:30b` remains the plugin's default tag. Other models exercised during development include `gpt-oss:120b`, `qwen3-coder-next:latest`, `qwen3.5:latest`, and `qwen2.5:7b`. These observations do not establish a current quality or speed ranking.

The November 2026 coding self-check used the exact locally installed tag `qwen3.8:27b-q8_0`; that environment-specific tag is not an installation requirement or a guarantee of availability in the public model library. See the [raw self-check evidence](docs/qwen_coding_self_check_2026-11-25.json). Choose a model that fits your hardware, and compare it on your actual prompts with the same reasoning, context, and loading settings.

## Current Limitations

- the dataset profiler is still Phase 1 and remains strongest on already-loaded napari layers rather than reader- or file-format-specific workflows
- TIFF vs OME-Zarr adapter behavior is not implemented yet
- ND2 and Zeiss reader-aware adapters are not implemented in this plugin
- the tool registry is in progress; some tools are now registry-backed, but the migration is not complete yet
- session memory is selective and bounded; it is not full conversation memory
- layer identity fields are not yet unified across all compact-context, memory, and telemetry paths; some layer-bound approved memory can be omitted from model requests
- Agent mode is experimental, uses an automatic-tool allowlist, and does not establish general unattended workflow reliability
- Python runs inside napari with normal Python builtins; compatibility validation is not a security sandbox
- task verification is limited to recognized postconditions and bounded data checks; partial data changes are not automatically rolled back
- model output can still be inconsistent, especially when falling back to generated code
- some requests still miss built-in tools and fall through to code generation when a stronger built-in workflow would be preferable
- generated code can still fail if the model invents incorrect napari APIs or unsupported imports
- no image attachment or multimodal input pipeline yet
- performance optimization for very large 2D/3D datasets is still in progress
- hard native crashes in Qt/C-extension code may not be captured cleanly by the plugin crash log even when normal plugin errors are logged

Most reliable current workflow:
- use built-in tools for common layer inspection and mask/image actions
- trust current viewer context and current layer profiles over any remembered prior turn
- use the Library for repeated prompts, demo packs, and reusable code
- use generated code when you want explicit review and control
- use `Run My Code` when you already have working Python and want to test it directly inside napari

For demo and education workflows:
- ask for code that uses the current napari `viewer`
- avoid prompts that create a second `napari.Viewer()` or call `napari.run()`
- prefer docked widgets over unmanaged popup windows for histogram or SNR teaching tools

## Troubleshooting

### Ollama not running

If `Test` fails after restarting your computer, Ollama is usually not running yet.

Start it in a terminal:

```bash
ollama serve
```

Then return to the plugin and click `Test` again.

### Pulling a model

Model downloads are intentionally handled outside the plugin.

To try a different model:
- browse tags at `https://ollama.com/search`
- type the tag into the plugin `Model` field if needed
- pull it in a terminal, for example:

```bash
ollama pull nemotron-cascade-2:30b
```

Then use `Test` to refresh the plugin state.

### Logs and crash logs

The plugin writes two local log files:
- `~/.napari-chat-assistant/assistant.log`
- `~/.napari-chat-assistant/crash.log`

Use these together with the terminal traceback when diagnosing crashes or unclear UI failures.

### Local model telemetry

If telemetry is enabled, the plugin writes lightweight local model events to:
- `~/.napari-chat-assistant/model_telemetry.jsonl`

Telemetry is opt-in from `Session -> Telemetry` and includes summary, log, and reset controls for advanced users.

Generated code is also preflight-validated before execution for common dtype mistakes, unsupported napari imports, and unavailable `viewer.*` APIs. When validation blocks execution, the code remains visible and copyable for review or regeneration.

## Release

This package is published to PyPI so napari Hub can discover it.

For maintainer release instructions and PyPI publishing setup, see [RELEASING.md](RELEASING.md).

## Development

Build a release artifact:

```bash
python -m build
```

## License

MIT.
