Skip to content

About

AI-powered image description generator for Immich that analyzes photos with Ollama models and updates database metadata

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

Immich Analyze

AI-powered image description generator for Immich photo management system

This is a fork of timasoft/immich-analyze, maintained independently at upmcplanetracker/immich-analyze. Changes made here are not sent upstream, and upstream releases are not tracked. Please report problems with this fork in this repository, not to the original author.

Thank you

Immich Analyze was created by timasoft, who designed and built the application this fork is based on: the AI backends, host failover, operating modes, prompt enrichment and much more. Thank you for building it and for releasing it as free software. The original project, with its own releases, lives in the upstream repository.

How this fork was made

I am in no way a programmer, and I don't understand Rust at all. The changes in this fork were 100% coded by Claude (Anthropic's AI). I take no credit for the code, so please review it with that in mind.

What this fork changes

Compared with upstream 0.6.1 (modified November 2026). For the current version see the tags; immich-analyze --version reports the one you are running.

Multiple API keys

  • An asset owned by the second or a later user is no longer skipped as "not found" after only the first key was tried. An asset is missing only when every key says so.
  • Requests go to the asset owner's key first, then the others.
  • One key failing to list assets no longer stops the other keys, and assets visible to several keys are processed once.
  • Logs name each key's user (key #1 (Eric)) when the key has the optional user.read permission.
  • With several keys, every per-asset log line starts with the owner (Skipped: [Eric] 944b...), and the end-of-batch statistics add one line per key.

Reliability

  • Immich connection failures are reported as such instead of as AI host failures.
  • Monitor and combined modes retry transient failures with exponential backoff (IMMICH_ANALYZE_MONITOR_RETRY_ATTEMPTS, default 5).
  • Monitor mode honors the concurrency limit, so a slow AI backend no longer builds an unbounded queue.
  • The monitor's first poll no longer lists the whole library a second time at startup.
  • The overwrite check reads each asset once instead of three times.

Logging and progress

  • Every log line has a local timestamp (from TZ) and a level.
  • Batch processing checks whether an asset needs analysis before downloading its thumbnail, so skipped assets are no longer downloaded.
  • Skipped assets now count toward the number done. Previously they were subtracted from the total, which made the counter and ETA misleading.

Defaults and options

  • The default rendition sent to the AI service is now thumbnail (was preview).
  • Tags in enriched prompts are filtered and limited to 300 characters by default (see Tag limiting).
  • Russian localization and language selection are removed: no --lang, no IMMICH_ANALYZE_LANG.

Container and project

  • Image published to ghcr.io/upmcplanetracker/immich-analyze (amd64 only) by a manually started workflow.
  • Smaller Dockerfile without unused OpenSSL packages, with cached dependency builds, a fixed non-root user (UID 10001) and a health check that passes when the health server is disabled.
  • The entry point warns about invalid numeric settings instead of silently ignoring them.
  • Nix support is removed; the project builds with plain cargo.

Overview

Immich Analyze automatically generates detailed descriptions for images in your Immich library using AI vision models via Ollama, llama.cpp server, or OpenRouter. This enhances search capabilities and organization by providing semantic understanding of image content.

The application uses the Immich API (requires IMMICH_API_URL + IMMICH_API_KEY; supports multiple comma-separated keys for multi-user setups)

Features

  • AI-powered image analysis using Ollama, llama.cpp server, or OpenRouter with vision-capable models
  • Multiple operation modes: batch processing, API monitoring, or combined mode
  • Multi-host support with automatic failover for AI service endpoints
  • Immich API integration
  • Concurrent processing with configurable parallelism
  • Configurable retry logic with exponential backoff and jitter between attempts
  • Per-host circuit breakers: failing hosts are paused instead of hammered, HTTP 429 Retry-After is honored, and only one probe request goes out when a host comes back
  • Podman and Docker container support
  • Prompt enrichment: optionally enrich AI prompts with asset metadata (EXIF, location, camera info, people with ages, tags, resolution, MIME type)
  • Selective description updates: use --preserve-human with any overwrite policy to preserve human-written text outside [AI]...[/AI] blocks; use --overwrite-policy missing-ai to process only assets without existing AI blocks
  • Timestamped logging via env_logger (configure with RUST_LOG environment variable)
  • Wait for Immich to become available on startup (configurable timeout)
  • Startup model existence check against the configured AI hosts (skippable via --no-preflight-model-check / IMMICH_ANALYZE_PREFLIGHT_MODEL_CHECK=false). When enabled, any host that does not serve the configured model is blacklisted for the current run and will not be used until the app is restarted; a missing model on all hosts aborts startup

Prerequisites

  • Immich instance with an API endpoint and API key
  • AI service running a vision-capable model:
    • Ollama server (e.g., qwen3-vl:4b-thinking-q4_K_M), OR
    • llama.cpp server with OpenAI-compatible API endpoint, OR
    • OpenRouter cloud API (OpenAI-compatible endpoint)

Installation

Images are published for linux/amd64 as ghcr.io/upmcplanetracker/immich-analyze. To build one yourself instead:

git clone https://github.com/upmcplanetracker/immich-analyze
cd immich-analyze
# --format docker keeps the image's HEALTHCHECK
podman build --format docker -t localhost/immich-analyze:latest .

Rootless Podman with Quadlet (Recommended)

  1. Create the environment file, readable only by you, since it holds API keys:

    mkdir -p ~/immich-analyze ~/.config/containers/systemd
    install -m 600 /dev/null ~/immich-analyze/immich-analyze.env

    ~/immich-analyze/immich-analyze.env (no quotes around values):

    IMMICH_API_URL=http://immich-server:2283
    IMMICH_API_KEY=user1_key,user2_key
    IMMICH_ANALYZE_INTERFACE=ollama
    IMMICH_ANALYZE_HOSTS=http://ollama:11434
    IMMICH_ANALYZE_MODE=combined
    IMMICH_ANALYZE_MAX_CONCURRENT=1
    TZ=America/New_York
  2. Create ~/.config/containers/systemd/immich-analyze.container:

    [Unit]
    Description=Immich Analyze
    Wants=network-online.target
    After=network-online.target
    
    [Container]
    ContainerName=immich-analyze
    Image=ghcr.io/upmcplanetracker/immich-analyze:latest
    EnvironmentFile=%h/immich-analyze/immich-analyze.env
    # Join the network your Immich and AI containers use, for example:
    # Network=immich.network
    NoNewPrivileges=true
    DropCapability=all
    HealthCmd=curl -fsS http://127.0.0.1:3000/health
    HealthInterval=30s
    
    [Service]
    Restart=always
    TimeoutStartSec=900
    
    [Install]
    WantedBy=default.target
  3. Start it:

    loginctl enable-linger "$USER"   # keep user services running after logout
    systemctl --user daemon-reload
    systemctl --user start immich-analyze.service
    journalctl --user -u immich-analyze.service -f

The health check reports unhealthy after 120 seconds without activity. In batch mode with a slow model this can happen while an image is still being analyzed.

Docker Compose

To integrate Immich Analyze into your Immich setup, use the following docker-compose.yaml file:

services:
  # Optional: Ollama service (you can use external Ollama or llama.cpp server instead)
  # This section is optional - remove it if you want to use external AI service
  ollama:
    image: ollama/ollama:latest
    container_name: ollama
    restart: unless-stopped
    ports:
      - "11434:11434"
    volumes:
      - ./ollama:/root/.ollama
    # Optional: GPU acceleration for NVIDIA cards
    # deploy:
    #   resources:
    #     reservations:
    #       devices:
    #         - driver: nvidia
    #           count: 1
    #           capabilities: [gpu]

  immich-analyze:
    image: ghcr.io/upmcplanetracker/immich-analyze:latest
    container_name: immich-analyze
    restart: unless-stopped
    volumes:
      - /etc/localtime:/etc/localtime:ro
    env_file:
      - .env
    environment:
      # AI service configuration
      - IMMICH_ANALYZE_INTERFACE=ollama  # or "llamacpp" or "openrouter"
      - IMMICH_ANALYZE_HOSTS=http://ollama:11434
      # For llama.cpp server with authentication:
      # - IMMICH_ANALYZE_INTERFACE=llamacpp
      # - IMMICH_ANALYZE_HOSTS=http://llamacpp-server:8080
      # - IMMICH_ANALYZE_API_KEY=your-api-key-here
      # For OpenRouter (host defaults to https://openrouter.ai/api):
      # - IMMICH_ANALYZE_INTERFACE=openrouter
      # - IMMICH_ANALYZE_API_KEY=sk-or-xxx
      # Or use multiple hosts with automatic failover:
      # - IMMICH_ANALYZE_HOSTS=http://primary:11434,http://backup:11434
    depends_on:
      # Comment the next line if using external AI service
      - ollama

Important notes about configuration:

  • You must provide API credentials (IMMICH_API_URL, IMMICH_API_KEY) for Immich API access
  • The ollama service is optional - you can remove it and use an external Ollama, llama.cpp server, or OpenRouter instead
  • Set IMMICH_ANALYZE_INTERFACE to ollama (default), llamacpp, or openrouter depending on your backend
  • If using external service, modify IMMICH_ANALYZE_HOSTS to point to your server(s)
  • For llama.cpp server, provide IMMICH_ANALYZE_API_KEY if authentication is enabled
  • For OpenRouter, provide IMMICH_ANALYZE_API_KEY (starts with sk-or-); the host defaults to https://openrouter.ai/api
  • After adding the Ollama service, you need to pull the model manually by executing:
    docker exec -it ollama ollama pull qwen3-vl:4b-thinking-q4_K_M
  • For GPU acceleration with NVIDIA cards, uncomment the deploy section and ensure you have NVIDIA Container Toolkit installed

Make sure to:

  1. Add the service(s) to your existing docker-compose.yml file
  2. Add the required environment variables to your .env file

After adding the service, run:

docker-compose up -d immich-analyze
# If using internal Ollama service:
# docker-compose up -d ollama

From Source

Needs a current stable Rust toolchain (rustup) and a C compiler.

cargo install --locked --git https://github.com/upmcplanetracker/immich-analyze
IMMICH_API_URL=http://localhost:2283 IMMICH_API_KEY=your_key immich-analyze --combined

Configuration

Environment Variables (Container)

Immich API Access Configuration

Variable Description Default Required For
IMMICH_API_URL Immich API base URL - Required
IMMICH_API_KEY Immich API authentication key(s) (comma-separated for multi-user setups) - Required

AI Service Configuration

Variable Description Default
IMMICH_ANALYZE_INTERFACE AI service interface type (ollama, llamacpp, or openrouter) ollama
IMMICH_ANALYZE_HOSTS Comma-separated AI service host URLs http://localhost:11434 (https://openrouter.ai/api on openrouter)
IMMICH_ANALYZE_API_KEY API key for llama.cpp server or OpenRouter authentication (none)
IMMICH_ANALYZE_MODEL_NAME Model name for image analysis qwen3-vl:4b-thinking-q4_K_M
IMMICH_ANALYZE_PROMPT Prompt for generating image descriptions See below
IMMICH_ANALYZE_ENRICH_PROMPT Enable prompt enrichment with asset metadata false
IMMICH_ANALYZE_LIMIT_TAGS With prompt enrichment: maximum characters of tag text in the prompt, see Tag limiting. 0 disables filtering and the limit 300
IMMICH_ANALYZE_API_POLL_INTERVAL API poll interval in seconds 10
IMMICH_ANALYZE_MONITOR_RETRY_ATTEMPTS Monitor/combined mode: retries for an asset that failed with a transient error (Immich or AI host unreachable, 5xx, timeout), with exponential backoff from the poll interval up to 1 hour. 0 disables retries 5

Application Settings

Variable Description Default
IMMICH_ANALYZE_MODE Operating mode: monitor, combined, or batch combined
IMMICH_ANALYZE_OVERWRITE_EXISTING If true, overwrite existing descriptions (alias for --overwrite-policy all) false
IMMICH_ANALYZE_OVERWRITE_POLICY Overwrite policy: none (skip any with description), all (process everything), missing-ai (process only if no [AI]...[/AI] block). Overrides IMMICH_ANALYZE_OVERWRITE_EXISTING none
IMMICH_ANALYZE_PRESERVE_HUMAN If true, preserve human text outside [AI]...[/AI] blocks by only replacing the AI block. Incompatible with --disable-ai-wrapper false
IMMICH_ANALYZE_THUMBNAIL_SIZE Which Immich thumbnail rendition to analyze: thumbnail (lower resolution, faster), preview (higher resolution, slower) or fullsize (highest resolution, slowest) thumbnail
IMMICH_ANALYZE_MAX_IMAGE_SIZE Downscale images whose longest edge exceeds this many pixels before sending them to the AI service (preserves aspect ratio). 0 disables downscaling 0
IMMICH_ANALYZE_MAX_CONCURRENT Max concurrent AI requests 4
IMMICH_ANALYZE_UNAVAILABLE_DURATION Circuit breaker cooldown in seconds after a host first trips; doubles on each further trip 60
IMMICH_ANALYZE_BREAKER_FAILURE_THRESHOLD Consecutive failures (5xx, timeout, connection error) that open a host's circuit breaker. HTTP 429 never counts 3
IMMICH_ANALYZE_BREAKER_MAX_COOLDOWN Upper limit in seconds for breaker cooldowns, 429 pauses, Retry-After values and retry backoff 600
IMMICH_ANALYZE_TIMEOUT AI request timeout in seconds 300
IMMICH_ANALYZE_DISABLE_AI_WRAPPER If true, disable [AI]...[/AI] wrapper, storing description as plain text. Incompatible with --preserve-human. When combined with missing-ai overwrite policy, every asset will be re-analyzed (no [AI] tag to detect) false
IMMICH_ANALYZE_NO_FINAL_OUTPUT If true, disable final output with analysis results and statistics after batch processing false
IMMICH_ANALYZE_MAX_RETRIES Maximum retry attempts (0 = infinite) 0
IMMICH_ANALYZE_RETRY_DELAY_SECONDS Initial delay between retry cycles in seconds; doubles each cycle (with jitter) up to the max cooldown. Also the first pause after a 429 without Retry-After 5
IMMICH_ANALYZE_HEALTH_PORT Port for health check HTTP server (0 to disable) 3000
IMMICH_ANALYZE_WAIT_FOR_IMMICH Wait for Immich to become available on startup true
IMMICH_ANALYZE_WAIT_TIMEOUT Maximum time in seconds to wait for Immich (0 = no limit) 120
IMMICH_ANALYZE_WAIT_RETRY_INTERVAL Interval in seconds between retry attempts when waiting 5
IMMICH_ANALYZE_PREFLIGHT_MODEL_CHECK Verify on startup that the configured model is served by at least one of the AI hosts true
RUST_LOG Logging level (error, warn, info, debug, trace) info
TZ Time zone for log timestamps, e.g. America/New_York UTC

Default prompt: Create a detailed description for the image for proper image search functionality. In the response, provide only the description without introductory words. Also specify the image format (Wallpaper, Screenshot, Drawing, City photo, Selfie, etc.). The format must be correct. If in doubt, name the most likely option and don't think too long.

Backwards Compatibility: The deprecated IMMICH_ANALYZE_OLLAMA_HOSTS variable is still used when IMMICH_ANALYZE_HOSTS is not set.

Command Line Arguments

Usage: immich-analyze [OPTIONS]

Options:
  -m, --monitor
          Enable API monitoring mode
  -c, --combined
          Enable combined mode: process existing images then monitor for new ones
  -o, --overwrite-existing
          Overwrite existing asset descriptions (process all assets regardless of existing descriptions) (same as --overwrite-policy all)
  -O, --overwrite-policy <OVERWRITE_POLICY>
          Overwrite policy [default: none]: none (skip any with description), all (process everything), missing-ai (process only if no [AI]...[/AI] block). Takes precedence over --overwrite-existing [possible values: none, all, missing-ai]
  -p, --preserve-human
          When overwriting or adding, preserve human-entered text by only replacing the [AI]...[/AI] block
      --immich-api-url <IMMICH_API_URL>
          Immich API base URL (required) [env: IMMICH_API_URL=]
      --immich-api-keys <IMMICH_API_KEYS>
          Immich API authentication key(s) (required). Provide multiple keys comma-separated for multi-user setups [env: IMMICH_API_KEY]
      --api-poll-interval <API_POLL_INTERVAL>
          API poll interval in seconds [default: 10]
      --monitor-retry-attempts <MONITOR_RETRY_ATTEMPTS>
          Monitor mode: how many times to retry an asset that failed with a transient error (Immich or AI host unreachable, 5xx, timeout), with exponential backoff. 0 disables retries [env: IMMICH_ANALYZE_MONITOR_RETRY_ATTEMPTS=] [default: 5]
      --thumbnail-size <THUMBNAIL_SIZE>
          Which Immich thumbnail rendition to analyze: thumbnail (lower resolution, faster; the default), preview (higher resolution, slower analysis) or fullsize (highest resolution, slowest) [default: thumbnail] [possible values: preview, thumbnail, fullsize]
      --max-image-size <MAX_IMAGE_SIZE>
          Downscale images whose longest edge exceeds this many pixels before sending them to the AI service (preserves aspect ratio). 0 disables downscaling [default: 0]
      --model-name <MODEL_NAME>
          Model name for image analysis [default: qwen3-vl:4b-thinking-q4_K_M]
      --interface <INTERFACE>
          AI service interface type [default: ollama] [possible values: ollama, llamacpp, openrouter]
      --hosts <HOSTS>
          Host URLs (Ollama, llama.cpp server, or OpenRouter) [default: http://localhost:11434]
      --api-key <API_KEY>
          API key for authentication (llama.cpp server or OpenRouter) [env: IMMICH_ANALYZE_API_KEY]
      --no-preflight-model-check
          Disable the startup model existence check against the configured AI hosts
      --max-concurrent <MAX_CONCURRENT>
          Maximum number of concurrent requests [default: 4]
      --unavailable-duration <UNAVAILABLE_DURATION>
          Circuit breaker cooldown in seconds after a host first trips; doubles on each further trip up to --breaker-max-cooldown [default: 60]
      --breaker-failure-threshold <BREAKER_FAILURE_THRESHOLD>
          Consecutive failures (5xx, timeout, connection error) that open a host's circuit breaker. HTTP 429 never counts: it only pauses the host for Retry-After [default: 3]
      --breaker-max-cooldown <BREAKER_MAX_COOLDOWN>
          Upper limit in seconds for circuit breaker cooldowns, 429 pauses, Retry-After values and the backoff between retry cycles [default: 600]
      --timeout <TIMEOUT>
          HTTP request timeout in seconds [default: 300]
      --prompt <PROMPT>
          Prompt for generating image description [default: "Create a detailed description for the image for proper image search functionality. In the response, provide only the description without introductory words. Also specify the image format (Wallpaper, Screenshot, Drawing, City photo, Selfie, etc.). The format must be correct. If in doubt, name the most likely option and don't think too long."]
      --max-retries <MAX_RETRIES>
          Maximum number of retry attempts (0 = infinite) [default: 0]
      --retry-delay-seconds <RETRY_DELAY_SECONDS>
          Initial delay between retry cycles in seconds; doubles on each cycle (with jitter) up to --breaker-max-cooldown. Also the first pause after a 429 without Retry-After [default: 5]
      --enrich-prompt
          Enable prompt enrichment with asset metadata (date, location, camera info)
      --limit-tags <LIMIT_TAGS>
          With --enrich-prompt: maximum characters of tag text added to the prompt. Tags that are entirely a date (2024-03-15, 2024/March) are dropped first. 0 disables filtering and the limit [env: IMMICH_ANALYZE_LIMIT_TAGS=] [default: 300]
      --disable-ai-wrapper
          Disable [AI]...[/AI] wrapper around AI-generated description
      --no-final-output
          Disable final output with analysis results and statistics after batch processing
      --no-wait-for-immich
          Disable waiting for Immich to become available on startup
      --wait-timeout <WAIT_TIMEOUT>
          Maximum time in seconds to wait for Immich to become available (0 = no limit) [default: 120]
      --wait-retry-interval <WAIT_RETRY_INTERVAL>
          Interval in seconds between retry attempts when waiting for Immich [default: 5]
      --health-port <HEALTH_PORT>
          Port for health check HTTP server (0 to disable) [default: 3000]
  -h, --help
          Print help (see more with '--help')
  -V, --version
          Print version

Note: IMMICH_API_URL and IMMICH_API_KEY are read from environment variables by clap - no need to pass them as command-line arguments. IMMICH_API_KEY supports multiple comma-separated keys for multi-user setups.

Usage Examples

Basic Batch Processing via Immich API

IMMICH_API_URL=http://immich:2283 \
IMMICH_API_KEY=your_api_key \
immich-analyze \
  --interface ollama \
  --hosts "http://ollama-server:11434"

Multi-User Batch Processing (Multiple API Keys)

IMMICH_API_URL=http://immich:2283 \
IMMICH_API_KEY=user1_key,user2_key,user3_key \
immich-analyze \
  --interface ollama \
  --hosts "http://ollama-server:11434"

How multiple keys are used:

  • Each key lists its own assets. Assets visible to several keys (partner sharing) are processed once.

  • Reads and writes for an asset go to its owner's key first, then the other keys. The owner's key is learned from the listing and from the first successful write for each user.

  • An asset counts as missing only if every key answers "not found".

  • If one key's listing fails (expired key, missing permission), it is logged as Immich key #N: asset listing failed and the other keys keep working.

  • Startup logs one line per key: Immich key #2: 1038 assets listed (...). If a key shows 0 assets, check that key's permissions.

  • Partner/shared access is read-only in Immich. Assets whose owner has no key configured here can't get a description; they show up as failed writes.

  • Per-asset log lines name the owner before the asset ID, using the key's user name (or key #N without user.read): Finished processing: [Melissa] 82e3b430-.... An asset whose owner has no key here is labelled with the first key that listed it.

  • The statistics printed after the batch pass end with a per-key breakdown:

    Per Immich key:
      Eric: 1204 successful, 2 failed, 21664 skipped, 0 blocked (22870 total)
      Melissa: 86990 successful, 167 failed, 0 skipped, 0 blocked (87157 total)
    

    It is part of the final output, so --no-final-output turns it off too. Monitor mode has no end of run and prints no summary.

Combined Mode with API Access and llama.cpp

IMMICH_API_URL=http://immich:2283 \
IMMICH_API_KEY=your_api_key \
IMMICH_ANALYZE_API_KEY=your-llamacpp-api-key \
immich-analyze \
  --combined \
  --interface llamacpp \
  --hosts "http://llamacpp-primary:8080,http://llamacpp-secondary:8080" \
  --api-poll-interval 30

Monitor Mode with Infinite Retries

IMMICH_API_URL=http://immich:2283 \
IMMICH_API_KEY=your_api_key \
immich-analyze \
  --interface ollama \
  --hosts "http://ollama:11434" \
  --monitor

Batch Processing with Prompt Enrichment

IMMICH_API_URL=http://immich:2283 \
IMMICH_API_KEY=your_api_key \
immich-analyze \
  --interface ollama \
  --hosts "http://ollama-server:11434" \
  --enrich-prompt

Batch Processing with Limited Retries

IMMICH_API_URL=http://immich:2283 \
IMMICH_API_KEY=your_api_key \
immich-analyze \
  --interface llamacpp \
  --hosts "http://llamacpp-server:8080" \
  --max-retries 5 \
  --retry-delay-seconds 15

Batch Processing Without Final Results Output

IMMICH_API_URL=http://immich:2283 \
IMMICH_API_KEY=your_api_key \
immich-analyze \
  --interface ollama \
  --hosts "http://ollama-server:11434" \
  --no-final-output

Tag limiting

Assets with very many tags can make an enriched prompt so long that the AI backend truncates it. With IMMICH_ANALYZE_ENRICH_PROMPT=true, the Tags: line is therefore limited (IMMICH_ANALYZE_LIMIT_TAGS / --limit-tags, default 300):

  1. Tags that are entirely a date are dropped: YYYY-MM-DD (2024-03-15) and YYYY/MonthName (2024/March, full English month name). Tags such as Summer 2024 are kept.
  2. Whole tags are added in their existing order while they fit. The limit counts characters, including the , separators but not the Tags: label. A tag that does not fit is skipped, never cut.
  3. If no tag remains, the Tags: line is left out.

Set it to 0 to send every tag. Only the prompt changes: tags stored in Immich are not modified, and the existing description is not limited. RUST_LOG=debug logs how many tags were dropped for each asset.

Logging

Every line has a timestamp (local time from TZ, UTC if unset) and a level:

2026-11-28 16:40:12.345 -05:00 INFO   Monitoring mode activated
2026-11-28 16:40:13.002 -05:00 INFO  Immich key #1: 4210 assets listed (4210 new, 0 also visible to an earlier key)
2026-11-28 16:40:13.120 -05:00 INFO      Skipped: [Eric] 944b4553-bba4-427d-9429-9ca94a76858f
2026-11-28 16:41:02.877 -05:00 WARN  Asset 6f1c... failed, retry 1/5 in 10s: Failed to connect to Immich ...

RUST_LOG filters all of it (default info). RUST_LOG=debug adds the module name and per-key request details (which key got which HTTP status for each asset). API keys are never logged.

Enable Debug Logging

IMMICH_API_URL=http://immich:2283 \
IMMICH_API_KEY=your_api_key \
RUST_LOG=debug \
immich-analyze \
  --combined \
  --interface ollama \
  --hosts "http://ollama-server:11434"

Model Recommendations

For Ollama:

  • qwen3-vl:4b-thinking-q4_K_M (Default) - Good balance of speed and accuracy
  • qwen3-vl:30b-a3b-thinking-q4_K_M - Higher accuracy for complex images
  • qwen3-vl:2b-instruct-q4_K_M - Faster processing for simpler descriptions

For llama.cpp Server:

  • Any GGUF vision model served via llama.cpp's OpenAI-compatible API
  • Recommended: qwen3-vl-4b-instruct-q4_k_m.gguf or similar quantized variants

For OpenRouter:

  • Any vision-capable model available on OpenRouter
  • The host defaults to https://openrouter.ai/api; supply your API key via IMMICH_ANALYZE_API_KEY or --api-key

Install Ollama models using:

ollama pull qwen3-vl:4b-thinking-q4_K_M

Architecture

The application integrates with your Immich instance by analyzing Immich thumbnail renditions and storing generated descriptions. It supports multiple operation modes:

  • Batch Mode: Process all existing images in your library
  • Monitor Mode: Automatically process new images as they're added to Immich
  • Combined Mode: Process existing images in background while simultaneously monitoring for new additions

Immich API

  • Uses Immich REST API for all data operations
  • No direct database or filesystem access required
  • Polls Immich API for new assets at configurable interval (--api-poll-interval)
  • Requires IMMICH_API_URL and IMMICH_API_KEY environment variables (supports multiple comma-separated keys)

Required API Key Permissions

The API key used must have the following permissions enabled in the Immich admin panel:

Endpoint Method Permission Purpose
/api/search/metadata POST asset.read List/search assets for batch processing
/api/assets/{id}/thumbnail GET asset.view (+ asset.download on fullsize) Download thumbnail images for AI analysis
/api/assets/{id} PUT asset.update Write generated descriptions back to assets
/api/assets/{id} GET asset.read Check asset existence and read metadata
/api/users/me GET user.read (optional) Show each key's owner name in logs (key #1 (Eric)); without it logs show the key number only

Note: Ensure all three permissions (asset.read, asset.view, asset.update) are enabled.

Core Features

  • Automatic retry logic with multiple AI service hosts and automatic failover
    • Configurable maximum retry attempts (--max-retries, 0 = infinite)
    • Exponential backoff with jitter between retry cycles, starting at --retry-delay-seconds and capped at --breaker-max-cooldown
    • Smart error classification: only retryable errors (5xx HTTP, timeouts, host unavailable) trigger retries
    • Non-retryable errors (invalid UUID, empty response, JSON parsing) fail immediately
    • Permanent provider rejections (e.g. a content-policy block returning {"error":{"code":400,"message":"...PROHIBITED_CONTENT..."}}) fail immediately, surface the provider's actual reason in the log, and are recorded as an [AI] IMMICH-ANALYZE:BLOCKED: <reason> [/AI] marker description so they are not re-attempted on subsequent runs
  • Per-host circuit breakers (see Circuit breakers and rate limits)

Circuit breakers and rate limits

Every AI host has its own circuit breaker, shared by all concurrent workers:

Response Effect
5xx, timeout, connection error Counts as a failure. After --breaker-failure-threshold consecutive failures (default 3) the breaker opens for --unavailable-duration seconds, doubling on each further trip (with up to 10 % jitter) up to --breaker-max-cooldown.
HTTP 429 Never counts toward the threshold. The host is paused for the Retry-After value (seconds or HTTP date, capped at --breaker-max-cooldown), or without one for --retry-delay-seconds, doubling on consecutive 429s.
Success Resets the failure count; closes the breaker after a probe.
4xx other than 429, unusable 200 body Not a host-health signal: the breaker is unchanged.

When a pause ends the breaker is half-open: exactly one probe request is sent while the other workers wait. A successful probe closes the breaker and wakes them; a failed one reopens it with a longer cooldown. If every host is paused, workers wait for the earliest one to come back instead of sending requests anyway, which matters most with a single host such as a LiteLLM proxy. Waiting keeps the health endpoint reporting healthy, because the process is deliberately holding back, not hung.

Tuning for a shared local GPU (Ollama, llama.cpp, or a LiteLLM proxy in front of them). Timeouts count as failures, and --timeout covers the time a request spends queued in the model server, not just inference. If Ollama runs one request at a time (OLLAMA_NUM_PARALLEL=1) and other apps share it, a photo can wait minutes behind someone else's request. Two settings avoid false trips:

  • IMMICH_ANALYZE_MAX_CONCURRENT=1: extra workers only queue inside the model server and burn their timeout budget there.
  • IMMICH_ANALYZE_TIMEOUT: set it to your worst-case single analysis plus the longest request another app can put ahead of it (e.g. 900). Make sure any proxy in between (LiteLLM's request timeout) is at least as long, or the proxy's error counts as the failure instead.

With hosted providers (OpenRouter) the defaults are fine; their limits come back as 429s, which only pause the host.

Each state change is logged once:

WARN  Circuit breaker for http://litellm:4000 opened (trip 1), pausing requests for 63s
INFO  http://litellm:4000 rate limited (429, Retry-After 10s), pausing requests for 10s
INFO  Circuit breaker for http://litellm:4000 is half-open, sending one probe request
INFO  Circuit breaker for http://litellm:4000 closed, host is healthy again
  • Prompt enrichment: optionally enrich AI prompts with asset metadata (EXIF metadata, location, camera info, recognized people with ages, tags, resolution, MIME type) via the Immich API for more detailed descriptions
  • Selective description preservation: when using --preserve-human, only the [AI]...[/AI] block in the description is replaced, preserving any human-written text outside this block. If no [AI]...[/AI] block exists, the AI-generated block is appended to the existing description
  • Overwrite policies: use --overwrite-policy all to process everything, --overwrite-policy none to skip existing (default), or --overwrite-policy missing-ai to skip only assets with an existing [AI]...[/AI] block (processes human-only and empty descriptions)
  • Structured, timestamped logging via env_logger for easier debugging and monitoring

Troubleshooting

Enable verbose logging

Set the RUST_LOG environment variable to see detailed logs:

RUST_LOG=debug immich-analyze --combined ...

Check AI service status

  • For Ollama: systemctl status ollama or curl http://localhost:11434/api/tags
  • For llama.cpp: curl http://localhost:8080/health

API Mode Issues

  • Verify IMMICH_API_URL is reachable: curl $IMMICH_API_URL/api/server/ping
  • Verify API key has sufficient permissions in Immich admin panel
  • Check Immich server logs for authentication errors

Slow analysis on local vision backends

By default immich-analyze sends the Immich thumbnail rendition (Immich's default thumbnail size is 250 px) to the AI service, which keeps request payloads and vision-encoding time small on local backends such as Ollama or llama.cpp.

If descriptions miss detail, switch to the preview rendition — ideally combined with --max-image-size so a high Immich preview-size doesn't produce huge payloads:

immich-analyze --thumbnail-size preview --max-image-size 1024 ...
# or via env var in Docker:
# IMMICH_ANALYZE_THUMBNAIL_SIZE=preview
# IMMICH_ANALYZE_MAX_IMAGE_SIZE=1024

Previews give the model more detail but are slower to encode; fullsize is rarely worth it for descriptions.

Downscale the image locally before sending it (works with any rendition):

immich-analyze --max-image-size 1024 ...
# or via env var in Docker:
# IMMICH_ANALYZE_MAX_IMAGE_SIZE=1024

Permanent provider rejections (content-policy / blocked content)

Remote providers sometimes permanently reject an image — for example returning {"error":{"code":400,"message":"...PROHIBITED_CONTENT..."}}. immich-analyze treats these as non-retryable: the request is not retried, and the asset is recorded as permanently blocked so later batch/monitor runs skip it instead of repeatedly paying for the same rejected request.

To re-attempt blocked assets, run with --overwrite-policy all (not recommended because it will reanalyze ALL photos and overwrite their descriptions), or clear the marker descriptions in Immich.

Development

cargo fmt --all --check
cargo clippy --all-targets -- -Dwarnings
cargo test
tests/entrypoint_test.sh

To publish an image, push a v* tag, then run the Docker (manual, amd64) workflow from the Actions tab.

License

GPL-3.0-or-later, the same license as the original project.

About

AI-powered image description generator for Immich that analyzes photos with Ollama models and updates database metadata

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages