Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Image Generation & Vision

OpenCrabs supports image generation (text-to-image and img2img) and vision analysis (image-to-text). Vision works through two paths, pick whichever fits your provider setup.

Vision: Two Paths

Path A: vision_model on Your Active Provider (Preferred)

Set vision_model = "<model>" inside the provider block you’re already using. Works for every built-in and custom provider. No second API key needed, the agent calls analyze_image against the vision model on the same provider endpoint.

# keys.toml
[providers.openrouter]
api_key = "sk-or-..."

# config.toml
[providers.openrouter]
model = "anthropic/claude-sonnet-4"
vision_model = "google/gemini-2.5-flash"   # ← any vision-capable model on the same endpoint

When a user sends an image and the chat model can’t handle it natively, the agent routes the image through vision_model, gets a text description back, and replies with that context.

Example: User sends an image while you’re on MiniMax M2.5 (no native vision). The agent calls the vision tool, which sends the image to MiniMax-Text-01 (or any model you set), gets the description, and M2.5 replies using that context.

Why this is preferred:

  • Single API key, single billing account
  • Works on any OpenAI-compatible endpoint (OpenRouter, Ollama, LM Studio, vLLM, Groq, custom)
  • No extra onboarding step: just add one line to your existing provider block

Path B: Gemini Global Fallback

Use this only when your active provider has no vision-capable model. Gemini acts as a dedicated vision+image backend, independent of your chat provider.

# keys.toml
[image]
api_key = "AIza..."    # ← MUST go here. See gotcha below.

# config.toml
[image.generation]
enabled = true
model = "gemini-3.1-flash-image-preview"

[image.vision]
enabled = true
model = "gemini-3.1-flash-image-preview"

Get a free API key from aistudio.google.com. Configure interactively with /onboard:image.

⚠️ Gotcha: #[serde(skip)] on [image.vision] api_key

The api_key field under [image.vision] in config.toml is silently ignored: it’s marked #[serde(skip)] in the source. Always put the Gemini key in keys.toml under [image], never in config.toml. If vision reports as unavailable despite a key being set, this is almost always the cause.

Diagnostic: Why Is Vision Unavailable?

is_vision_available logs the exact reason at INFO level with target=vision. Search your daily log:

grep 'target=vision' ~/.opencrabs/logs/opencrabs.$(date -u +%Y-%m-%d)

Common causes surfaced:

  • Missing vision_model on active provider (the only field actually required since v0.3.64)
  • Missing api_key for that provider
  • Missing Gemini [image] api_key in keys.toml
  • Key placed in config.toml where #[serde(skip)] drops it

v0.3.64 change: setting vision_model on your active provider is now sufficient to enable vision. The enabled flag under [image.vision] is no longer required. The vision roll-through tries each provider endpoint and falls back to Gemini last.

Geração de imagens: duas rotas

A geração é um caminho diferente da visão. A visão transforma uma imagem em texto; a geração transforma um prompt numa imagem. A ferramenta generate_image é registada pela rota que resolver primeiro, e a geração nunca precisa de uma chave Gemini quando o teu próprio provider a consegue servir.

Rota A: generation_model num provider (preferida)

Define generation_model dentro de um bloco de provider que já usas. O modelo é o modelo de imagem desse provider, e o endpoint vem do mesmo base_url do tráfego de chat:

# config.toml
[providers.openrouter]
model = "anthropic/"
vision_model = "google/gemini-2.5-flash"
generation_model = "black-forest-labs/flux-1.1-pro"   # ← drives generate_image

Funciona para todos os providers integrados e custom. O protocolo é escolhido pelo endpoint em vez de adivinhado: um host Gemini usa a API Gemini, tudo o resto usa /v1/images/generations com autenticação Bearer. Por isso um provider compatível com [OI] que sirva imagens só precisa do campo.

O provider integrado OpenCrabs serve imagens no dia 0

O provider integrado não é só texto. O bloco que vem de origem já nomeia um modelo de imagem:

# config.toml
[providers.opencrabs]
enabled = false                              # onboarding turns this on when you pick OpenCrabs
default_model = "deepseek-v4.1-flash"
models = ["deepseek-v4.1-flash"]
vision_model = "deepseek-v4.1-flash"
generation_model = "gemini-2.5-flash-image"  # served only on /v1/images/generations
stt_model = "qwen3.8-omni-flash"

Há três coisas nesse bloco que vale a pena saber, porque cada uma parece um bug se não souberes:

  • gemini-2.5-flash-image não está em models. É servido só na rota de imagens, nunca como modelo de chat, por isso /models nunca o vai oferecer e listá-lo ali comprava-te um pedido de chat falhado.
  • context_window é ignorado neste provider. O endpoint é gratuito e fixo em 200k, por isso um valor aqui não muda nada.
  • enabled = false é a omissão de origem. O onboarding liga-a e escreve o token de instalação em keys.toml em [providers.opencrabs] api_key. Virar enabled à mão sem esse token deixa-te com um provider sem credencial.

Cadeia de providers para geração

generate_image percorre uma cadeia, tal como a visão (#1672):

  1. O provider atual da sessão, se tiver generation_model.
  2. A lista [providers.fallback] generation, por ordem.
  3. A secção global Gemini [image.generation], por último.
# config.toml
[providers.fallback]
generation = ["openrouter", "qwen-image"]   # provider section names, tried in order

Cada entrada é um nome de provider (a chave de uma secção [providers.<name>] ou [providers.custom.<name>]). O modelo é o generation_model desse provider; os endpoints são derivados do bloco do provider e nunca adivinhados.

A flag enabled em [image.generation] controla SÓ o fallback global Gemini. Uma rota de provider regista generate_image mesmo com ela desligada. É esse o objetivo do #1672: um modelo de imagem num provider que já pagas funciona sem uma segunda chave Gemini e sem ligar o fallback.

Rota B: Gemini como backend dedicado de imagens

Quando nenhum provider da tua lista serve imagens, usa a secção global Gemini descrita em Path B acima. Trata a entrada de visão e a saída de imagem num só pedido, e é a única perna que a flag [image.generation] enabled controla.

Qual estou a usar?

Uma geração bem-sucedida não diz que rota usou; o resultado é só o caminho do ficheiro guardado. A cadeia é visível quando falha, porque cada candidato é tentado e o erro agregado lista-os por ordem como backend(model).

All 2 image generation candidates failed - openai(flux-1.1-pro): 404 ... | gemini(gemini-2.5-flash-image): 400 ...

Por isso o diagnóstico é: gera uma vez, e lê o erro se voltar vazio. Uma perna gemini(...) depois de uma perna openai(...) significa que a tua rota de provider foi tentada primeiro e não funcionou. Se a ferramenta responder com a dica de configuração, nenhuma rota resolveu de todo:

Image generation is not configured. Options: `/image gemini <GOOGLE_AI_KEY>` for Gemini,
or set `generation_model = "<model>"` on a provider section ...

Agent Tools

When vision or image generation is enabled, these tools become available:

ToolDescrição
generate_imageGenerate an image from a text prompt: saves to ~/.opencrabs/images/; walks a provider chain with vision parity, so generation falls back the same way vision does (v0.5.4, #1672)
analyze_imageAnalyze an image file or URL via the active vision path (Path A provider or Gemini fallback)

Example prompts:

  • “Generate a pixel art crab logo”: agent calls generate_image, returns file path
  • “What’s in this image: /tmp/screenshot.png”, agent calls analyze_image

img2img: Edit Images with Context

generate_image accepts an optional image parameter (local file path or HTTPS URL). When provided, the model modifies, restyles, or composites onto that image instead of generating from scratch.

User: "Make this logo darker and add a border"
Agent: generate_image(prompt="dark background with thin white border", image="/tmp/logo.png")
  • Via Gemini: a imagem de entrada segue como uma parte inlineData ao lado do prompt.
  • Via compatível com OpenAI: o pedido passa de /images/generations para /images/edits, com uma parte image[] por imagem de entrada. Qualquer modelo nesse endpoint que aceite edições consegue reestilizar ou compor.

Use cases: replace elements, restyle photos, composite logos onto backgrounds, modify user-uploaded images in-place.

Incoming Images from Channels

When a user sends an image from any channel, it arrives as <<IMG:/tmp/path>> in the message. The file is already downloaded, the agent can:

  • See it directly (if the chat model supports vision natively)
  • Pass the path to analyze_image for vision processing
  • Use the path in bash commands or any tool that accepts file paths
  • Reference it in replies with <<IMG:path>> to forward to channels

analyze_video: Frame-Extraction Fallback (v0.3.36)

The analyze_video tool sends the full video to Gemini’s video API for multimodal analysis. When that fails (network error, upload timeout, unsupported format), the agent falls back to ffmpeg frame extraction:

  1. Extract frames at 1 fps via ffmpeg
  2. Cap at 30 frames (one frame per second for the first 30 seconds)
  3. Send each frame to Gemini vision via analyze_image
  4. Combine per-frame descriptions into a chronological summary

This means analyze_video works even when the video API is unreachable, as long as ffmpeg is installed and at least one vision path (Path A or Path B) is configured. The fallback activates automatically. No user configuration needed.

Model Choices

  • Path A: any vision-capable model on your active provider. On OpenRouter: google/gemini-2.5-flash, anthropic/claude-sonnet-4, openai/gpt-4o. On Ollama: llava, bakllava. On custom endpoints: whatever the server offers.
  • Path B: gemini-3.1-flash-image-preview handles both vision input and image output in a single request.