Skip to content
fijiPublic

About

LLM chatbot integration in Fiji

Resources

Stars

36 stars

Watchers

1 watching

Forks

Latest commit

 

History

669 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Fiji Large Language Model (LLM) Integration

Model Support Status: ChatGPT Claude Gemini Ollama

This project brings extensible, reproducible AI assistance into Fiji, helping scientists discover tools, build image analysis workflows, and connect with both local and external language models.

LLM Integration Overview

Parallel Integrated chat and MCP paths to LLM support in Fiji

Fiji-LLM was developed to help users access Fiji's capabilities through natural-language interaction, while allowing them to choose the AI model that best fits their needs.

Core Goals

  • Make Fiji More Accessible: Help scientists discover relevant tools, learn unfamiliar workflows, and create reusable scripts through guided natural-language interactions.

  • Enable Reproducible Agentic Workflows: Give AI agents structured access to Fiji’s application context and core capabilities, with an emphasis on generating familiar scripts and macros rather than de novo workflow formats.

  • Provide an Extensible AI Foundation: Establish shared extension points for agentic tools and model connectivity so that developers can add new capabilities without creating isolated or incompatible integrations.

  • Support Private and Equitable Model Access: Make local, open-weight models a first-class option while retaining flexible connectivity to external model providers and AI clients.

Key Architecture and Components

  • In-App Chat Interface: Provides scientists with guided AI assistance directly inside Fiji.

  • Model Context Protocol (MCP) Server: Exposes Fiji’s agentic tools to compatible external assistants, development environments, and other MCP clients.

  • Annotated Tool Registry: Uses the SciJava plugin framework to dynamically discover and register capabilities that developers expose to AI agents.

  • Extensible Model Engine: Separates model connectivity from agentic functionality, allowing new local or remote model providers to be added through plugins.

  • Context-Aware Analysis Tools: Give agents structured access to Fiji’s environment, including installed commands, open images, analysis metadata, the Script Editor, and macro recorder.

  • ImageJ Data Inspection: Provide structured access to common ImageJ data objects, including Results Tables and the ROI Manager.

  • Shared Fiji Guidance: Provide bounded, curated onboarding and workflow guidance to both integrated chat and external MCP clients without injecting the full documentation corpus into every request.

Table of Contents

See Also

Fiji Chat Quick Start

  1. Install Fiji: Download the Latest version from imagej.net/software/fiji

  2. Add the Fiji-chat Update Site:

    • See instructions on adding unlisted update sites.
    • Add the (currently unlisted) Fiji-chat site: https://sites.imagej.net/Fiji-chat/
    • Restart Fiji afterwards
  3. Open the chat: Run Help > Assistants > Fiji Chat... (shortcut: ctrl + 0)

    • The first time you run Fiji Chat... you will see a landing page where you select an AI Service and model.
    • Future Fiji Chat... runs will go right to chatting with your last selected service and model.
  4. Select a model:

    Option A: Local Models (Recommended for beginners)

    • These are open models which run on your machine.
    • Download and install Ollama now (no Fiji restart needed)
  • We recommend starting with the curated Gemma4 (Ollama) service, which offers XS, S, M, and L aliases for different hardware configurations.

    • The general Ollama service allows for full model exploration.
    • Click OK to start chatting. You will need to wait for the selected model to download (only on first chat with a model)

    Option B: Cloud Models

    • If you have an account with an AI service (Gemini, Claude, ChatGPT, etc.) you can use it with Fiji chat. Most services require paid subscriptions or credits for this function.
    • Select your provider, then choose an available model. Different models have different pricing schemes.
    • Click OK to start chatting. You will be prompted for an API key and provided with a link to your provider's key page (only on first chat with a remote provider)

    Want to switch later? Use the ⚙️ button in chat to change models and/or providers.

MCP Server

Fiji exposes its agent tools through a local Model Context Protocol (MCP) server. External AI clients can inspect images, run commands, edit scripts, and read Fiji guidance using your existing client subscription or local model. Tools marked with ToolScope.CHAT stay private to the integrated chat window and are not exposed over MCP.

Fiji runs its MCP server over localhost Streamable HTTP at http://localhost:9090/mcp by default. You can connect through the recommended fiji-mcp bundle or connect manually to an already-open Fiji window.

Recommended setup with MCPB and fiji-mcp

Use the standalone fiji-mcp/ entry point for most setups. It downloads Fiji-latest with a bundled JDK, enables the https://sites.imagej.net/Fiji-chat/ update site, and reuses that installation on later runs. When a client connects, fiji-mcp attaches to a running Fiji MCP server if one is open. Otherwise it starts Fiji on demand and forwards MCP messages directly to Fiji's Streamable HTTP server.

When fiji-mcp starts Fiji itself, closing the client sends a graceful File > Quit shutdown request so Fiji can prompt about unsaved changes. Agents also receive four supervisor tools outside Fiji's JVM:

  • fiji_app_status reports ownership mode (managed, attached, or stopped), installation path, port, port mode, PID, and tool count.
  • fiji_app_restart gracefully quits and relaunches a managed Fiji instance, then reconnects the MCP session. Pass an optional port (1-65535) or auto_port: true to restart Fiji on a different or OS-assigned free port. Use it after applying updates, enabling update sites, or changing ports.
  • fiji_app_shutdown requests a graceful File > Quit shutdown for a managed Fiji instance.
  • fiji_headless_run runs a script or CLI arguments in an isolated headless Fiji subprocess without disturbing the interactive Fiji window.

Install as an MCPB bundle (desktop clients)

  1. Build fiji-mcp.mcpb from fiji-mcp/ (cd fiji-mcp && npm install && npm run mcpb:pack), or download a release .mcpb archive.
  2. Open fiji-mcp.mcpb in an MCPB-compatible client such as Claude Desktop.
  3. Leave the optional settings blank to use a managed Fiji installation, enable Prefer Existing Local Fiji Installation to search standard OS paths, or enter an existing Fiji folder or macOS Fiji.app path. Set Fiji MCP Port to choose a specific port, or enable Automatically Choose a Free Port to run an isolated Fiji instance without attaching to port 9090.

Claude Desktop runs .mcpb bundles with its built-in Node.js runtime, so you do not need Node.js, Java, or Fiji preinstalled. The first run downloads 540 to 675 MB of Fiji-latest and runs Fiji's updater. If your client times out on a slow first download, retry after the cached archive finishes.

Run through npx (IDE and CLI clients)

Use npx if your client configures stdio MCP servers instead of .mcpb bundles. This path requires Node.js 20 or newer.

  1. Optionally pre-provision Fiji in a terminal to watch download progress:
    npx -y @fiji/fiji-mcp setup
  2. Register npx -y @fiji/fiji-mcp as a stdio MCP server in your client's MCP configuration.

See fiji-mcp/README.md for CLI flags, environment variables, and client configuration snippets. See doc/MCPB_TESTING.md for the end-to-end validation checklist.

Manual connection to a running Fiji

If you prefer not to install fiji-mcp, connect any Streamable HTTP MCP client directly to a running Fiji instance.

  1. Install Fiji and add the Fiji-chat update site as described in Fiji Chat Quick Start.
  2. Open Fiji and run Help > Assistants > Manage Fiji MCP Server....
  3. Change Port Configuration from 9090 if another local service uses that port. This setting maps to preference key sc.fiji.mcp.port. Launch-time overrides (-Dsc.fiji.mcp.port or FIJI_MCP_PORT, including 0 or auto for an OS-assigned free port) take precedence without modifying saved preferences and display as read-only in this dialog.
  4. Click Start Server if the server is not running.
  5. Enable Launch MCP on Startup if you want Fiji to start the server whenever Fiji opens. This setting maps to preference key sc.fiji.mcp.launchOnStartup and displays as read-only when overridden by -Dsc.fiji.mcp.launchOnStartup or FIJI_MCP_LAUNCH_ON_STARTUP.
  6. Open the Copy: menu to copy Server URL (http://localhost:9090/mcp), VS Code Config, or Claude Code Command, then paste the configuration into your client.

Click View Tools... in the dialog to inspect the tools exposed by the running server.

When using a manual HTTP connection, start Fiji before connecting your client. After updating plugins or revising tools, refresh your client's tool cache (for example, run MCP: Reset Tool Caches in VS Code) and reconnect.

Choosing between MCPB and manual connection

Aspect MCPB and fiji-mcp (recommended) Manual HTTP connection
Fiji and Fiji-chat setup Automated on first run and reused afterward. You install Fiji and add Fiji-chat manually.
Starting and stopping Fiji Launches Fiji on demand, attaches if already open, and sends graceful File > Quit on exit for managed instances. You open and close Fiji yourself. Tool calls fail while Fiji is closed.
Restarting for updates and headless runs Provides fiji_app_restart, fiji_app_shutdown, and fiji_headless_run. Not available. Restart Fiji manually and run headless CLI commands separately.
Extra components Requires the .mcpb bundle, or Node.js 20 or newer for npx, and downloads 540 to 675 MB on first managed setup. No wrapper package or Node.js required. Connects straight to http://localhost:9090/mcp.
Existing custom Fiji installations Supported through the optional Fiji path setting or Prefer Existing Local Fiji Installation auto-discovery. Checks for Java 17+ compatibility and never modifies your installation without opt-in. Uses your active Fiji window and installed update sites directly.

Bundled agent and workflow skills

This repository includes an MCP agent definition and workflow skills in .github/ for clients that discover project-scoped customizations, such as VS Code:

To use these customizations outside this repository in VS Code, symlink them to your user-level discovery paths, or copy them when symlinks are unavailable:

  • .github/agents/fiji-mcp.agent.md to <VS Code user profile>/prompts/fiji-mcp.agent.md
  • .github/skills/<skill-name>/ to ~/.copilot/skills/<skill-name>/

User Guide

Basic Concepts

AI Service Providers - Companies that provide cloud-based access to trained language models.

Models - Specific language models offered by a provider (e.g., GPT-4o, Claude 3.5 Sonnet). Different models have different capabilities and costs.

Tokens - The unit of operation within an LLM: messages to and from the chatbot are encoded as a series of "tokens". Longer messages require more tokens. Importantly, any actions taken by the LLM in response to your message will use tokens. (such as editing a script or running a command)

API Keys - Credentials that authenticate you with an AI service provider. Often require per-token pay-as-you-go or a subscription plan.

Conversations - Your chat history with an AI assistant, independent of model. Conversations are saved locally and loaded when Fiji starts, so you can continue working where you left off. Each conversation has a stable UUID identity and an optional display name; new conversations initially show their UUID and can be named once by the assistant from their history. In long conversations, the model may not "see" the whole chat history.

Context Items - Information you can attach to chat message that helps the assistant understand your Fiji environment. For example, you could attach an open image or script.

Image rendering is kept separate from persisted context metadata. The reusable ImageRenderingService captures the current displayed plane and display state, creates a bounded PNG ImageContent payload, and returns its image metadata separately. Optional ROI drawing uses the image's ImageJ ROI.

Supported AI Providers

Model Support

These badges are updated by the provider health workflow when one or more provider health statuses change. Diagnostic details and the check timestamp may change between runs without creating a provider-status commit. Badge colors indicate whether provider documentation needs review or could not be checked; Ollama is always shown in green because it is a local provider.

Google (Gemini)

  • Note: Gemini is currently the only supported provider that provides API Keys at no charge.
  • Using a "free" API Key is subject to Google's rate limits and availability. It is suitable for testing and assessment, but not regular use.
  • Getting an API Key:
    1. Visit aistudio.google.com/app/apikey
    2. Click Create API key and copy it

Ollama (Local Models Only)

  • Note: Ollama is a general gateway to pretrained models. Using local models bypasses the need for API keys or token considerations. However, running a local LLM can require significant resources (RAM, GPU, hard drive, power).
  • Models typically come in varieants (7b, 20b, etc...), indicating the number of model parameters (in billions). More parameters means a better ability to conceptualize solutions, but also more resource use.-
  • Fiji-chat is intended for use with models that support Tool Use.
  • Vision support is reported for the selected model when Ollama provides it; use a model whose capabilities include vision to attach images.
  • When a model is only partially loaded into GPU memory, Fiji reports that performance may be very slow and suggests trying a smaller model.
  • Installation:
    1. Download and install Ollama
    2. (Optionally) Use the ollama UI or command line tool to download a model of interest.
    3. When you can start a new chat you can choose from compatible models, which will be downloaded as needed.
  • Recommended model(s):
    • Gemma4 - Depending on your available video memory, select small (8GB), medium (16GB), or large (24GB or more).

Anthropic (Claude)

OpenAI (ChatGPT)

  • Getting an API Key:
    1. Create an account at platform.openai.com
    2. Go to Account settings > API keys (or click here)
    3. Click Create new secret key and copy it

General Work Flow

  1. Launch the Chat: Run Help > Assistants > Fiji Chat...
  2. Select a Provider: Choose your preferred AI service
  3. Select a Model: Pick a specific model. If an API Key is required and not found, you will be prompted automatically.
  4. Start Chatting: Type your question or request in the input box
  5. Attach Context (optional): Use the context buttons to provide relevant information from your Fiji environment

You don't need to attach something just so the assistant knows it exists: each message tells it the names of open scripts and images, and it can read them with its tools when relevant. Attach an item when you want the assistant to focus on it.

While the assistant works, an animated status line shows how long it has been working and which tool, if any, is running. When the assistant thinks or uses tools, its reply begins with a collapsed summary such as "Thought and used 2 tools (12s)"; click it to see the thinking text and each tool call's arguments, outcome, and result. This record is saved with the conversation, so it is still available when you reopen the conversation later.

You can use Help > Assistants > Manage API Keys... to manage your key(s) at any time.

Using Tools

The benefit of having an assistant integrated into Fiji is that it can perform actions, beyond just conversation:

Tool Design Best Practice - Keep tool responses focused on information that changes what the assistant should do next. Omit optional empty, default, and failure-only fields unless their absence would hide actionable state. Include a boolean only when its false value carries real information; use field presence as meaningful, and retain counts or status fields when they explain an empty or unsuccessful result. Successful multi-stage operations may include a recommended_tools array only when a concrete next step is available. Put detailed diagnostics and recovery context on the failure path rather than in every successful response.

Script Writing - Ask the assistant to write scripts in Python, Groovy, JavaScript, or other SciJava-compatible languages. Describe the context of your analysis task and the assistant can generate executable scripts.

Script Editing - Attach scripts as context and ask the assistant to improve, debug, or adapt them for your specific needs.

Macro Recording - Ask the assistant for help creating ImageJ macros for guidance to relevant commands and plugins. The assistant can inspect the current recorder state and buffer with fiji_macro_recorder_state.

Script and Macro Execution - Run non-.ijm scripts with fiji_script_run, and poll a running or dialog-paused run with fiji_script_run_status. Run an active .ijm script with fiji_macro_run, which executes it through the visible Script Editor and returns output, errors, ImageJ and SciJava logs, environment impact, and a status. The initial call waits up to 30 seconds; a longer operation returns status: "running", wait_expired: true, completed: false, elapsed time, and a run_id for polling. Wait expiry does not indicate a script error, and the operation continues running. If a script or macro pauses for a visible dialog, inspect the returned run_id with the corresponding status tool, then use fiji_ui_dialog_respond with the exact title and button, or fiji_ui_dialog_close with the exact title to close it.

Command Execution - Use fiji_image_activate to select a different image when needed, then use fiji_command_search to find a command_id and call fiji_command_run; command execution itself does not select an image. The result includes the command status, a run_id, and an optional changes-only environment_impact report covering opened, closed, or changed images, active-image changes, bounded SHA-256 pixel fingerprints, Results table changes, visible dialogs, and ImageJ and SciJava log deltas. A modal dialog returns status: "blocked_by_dialog"; respond or close it, then poll fiji_command_run_status with the run_id. A command still running after the initial wait returns status: "running" with wait_expired: true; it is not cancelled. Empty fields are omitted. Live environment snapshots defer pixel hashing; large samples and lazy images report inconclusive pixel comparisons explicitly.

ImageJ Data Inspection - Use fiji_results_read to inspect Results Table headings and numeric rows, and fiji_rois_read to inspect ROI Manager availability, ROI summaries, and bounding boxes. Use fiji_rois_read_details with an ROI index when exact shape and polygon coordinates are needed. Use fiji_rois_select to select a manager entry and restore it to the active image; this may change the active stack position. The read and details tools are read-only.

UI Inspection and Vision - Use fiji_ui_windows_read to list visible AWT and Swing windows, then fiji_ui_controls_read with an exact window title to inspect supported controls and their state. Omit window_title to inspect the active window, or pass window_title: "" plus the exact class to target a blank-titled window; ambiguous matches fail. Use fiji_ui_screenshot for offscreen rendering of the whole window; it does not request focus or include overlapping windows, and repaints visible AWT Canvas children into the window image. Some native or accelerated components, including ImageJ GenericDialogs, may still render incompletely. Use fiji_ui_screen_capture when actual screen pixels are needed; it may include occluding windows, requests best-effort focus when the target is not active, and reports focus_requested and focus_restored. Both tools respect the pixel-sharing privacy setting. Tool responses omit optional empty, default, and failure-only fields unless their absence would hide actionable state.

System Information - Use fiji_system_read to inspect ImageJ 1.x and application versions, Java and operating system details, JVM memory information, and active update sites. Use fiji_system_list_update_sites to inspect update sites from the local db.xml.gz. It returns active sites only by default; pass active_only: false to include inactive sites, and pass name_filter for a case-insensitive substring match on site names.

General Information - Describe your image analysis goals and discuss options available in your Fiji environment.

Tips for Better Results

  • Be Specific: Describe your task in detail. Include what you're trying to analyze, what tools you've already tried, and what's not working.
  • Provide Context: Use the context buttons to share relevant images, open scripts, or previous conversation history.
  • Iterate: LLM responses aren't always perfect on the first try. Review the output, provide feedback, and ask follow-up questions.

Getting Help

A help button ( ? ) in the chat window provides in-app explanations of the UI and how to use each feature.

For questions, bug reports, and feature requests, visit the Image.sc Forum. The Fiji community is active there and happy to help!

Debug Logging

To see what the assistant is doing under the hood, start Fiji with debug logging enabled for this component:

./fiji -Dscijava.log.level:sc.fiji.llm=debug

Each model API call is then logged with its duration, finish reason, token usage, and requested tool calls, along with each tool call's arguments, outcome, and a summary of its result. Use trace instead of debug to also log the full thinking text, response text, and tool results.

Developers: Adding Functionality

This project provides langchain4j integration to the SciJava plugin framework. There are several key points of extension:

Determine which AI Services are available in chat. Providers can also customize default request parameters for the selected model when a provider API requires model-specific settings.

Provide a mapping from the Fiji application environment to ContextItems, facilitating deeper understanding by the LLM. Context items can override getTooltipText() to explain what the attachment menu's active-item action will attach.

These plugins contain methods annotated with langchain4j's @Tool annotation. New tools enable code to be run by the AI assistants.

Tool Best Practices

When adding an AiToolPlugin:

  • Use scoped tool names. Give every @Tool an explicit lower-case snake_case name following the fiji_<scope>_<operation> pattern, such as fiji_script_read_content. The scope prevents collisions between plugins. Preserve an existing name when modifying a tool and use the exact name consistently in descriptions, errors, and recommendations.

  • Choose the exposure scope. Tools normally use the default ANY scope. Use ToolScope.CHAT for tools that support the integrated chat but must not be exposed through the external MCP server.

  • Choose useful parameter names. Use @P(name = ..., value = ...) to give each parameter a descriptive, stable snake_case name and a short description, even when the Java parameter uses camelCase: @P(name = "image_id", value = "Image ID from fiji_image_list"). Always set name: @P("image_id") sets only the description, so the LLM would see the parameter as arg0. Mark optional parameters required = false and use boxed types (Integer, Boolean) for them, since the model may omit them. Put units, indexing conventions, source-tool links, defaults, and other parameter-specific constraints in the @P(value = ...) description.

  • Keep descriptions at the right level. Put each tool's action, preconditions, safety restrictions, related tools, and return value in its @Tool(value = { ... }) description. Shared Fiji workflow guidance belongs in the curated AgentGuide plugins and should be exposed through guidance tools rather than duplicated in each plugin.

  • Return structured results. Text tools should return valid JSON strings for every success and error result, using the shared helpers in AbstractAiToolPlugin. A multimodal tool may instead return LangChain4j Content, such as ImageContent; the MCP bridge preserves supported text and image content blocks for external clients.

Integration Testing

mvn test runs the fast unit tests (*Test). mvn verify also runs the automated Maven integration tests (*IT), which start the MCP server or other heavy resources.

Live script and macro integration tests should be run by the developer as-needed, e.g. after major tool changes.

For a live run, create a task-specific agent, i.e. via the VS Code MCP agent definition, then give it the checklist in doc/INTEGRATION_TESTS.md. The agent should execute the workflow against a running Fiji instance through the Fiji MCP tools and report the observed results, failures, and any cases that require manual interaction.

Keep this dedicated live-test session separate from the general coding agent so integration tests are run deliberately.

Related human-facing evaluation material:

Keep the integration test document, technical summary, README, and relevant VS Code agent files in sync when public tools or APIs are added, removed, renamed, or behavior changes.

For developing chatbots in particular UI environments.

An MCP (Model Context Protocol) server exposes registered AiToolPlugin implementations via local HTTP, except for tools using the CHAT scope. Those chat-only tools remain available to the integrated assistant.

Development Philosophy

This repository is developed with assistance from AI coding tools; all changes are reviewed by human contributors.

Frequently Asked Questions

Q: What information is shared with AI assistants?

A: Nothing is shared proactively. The LLM can use tools to query information about your Fiji installation and inspect image data and GUI elements when needed. With local models, this information stays on your computer. When using a hosted model, the chat includes an AI vision toggle to control whether image data is shared with the model. Even with AI vision disabled, the model can still request basic image metadata through tools to support analysis.

Q: How does Fiji LLM get its information?

A: Each individual LLM has a baseline "knowledge" that is frozen in time based on when it was trained. To obtain current information, LLMs can use tools (such as web searches). We provide a core set of tools to help connected LLMs gather information related to Fiji use.

About

LLM chatbot integration in Fiji

Resources

Stars

36 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages