Ollama: Multimodal Models
Multimodal Models give AI eyes — see an image, describe it in words, everything at a glance.
💡 Tip: Multimodal Models (such as llava, minicpm-v) are 2-3x larger than text-only Models, and image processing requires additional vision encoder computation, so GPU acceleration is strongly recommended. In CPU-only environments, Multimodal Model Inference speed may be too slow to be practical (1-3 tok/s). A GPU with 8GB+ VRAM is the basic requirement for running Multimodal Models smoothly.
📋 Prerequisites: You need to master the following first
- Lesson 4: Model Management
1. What You Will Learn
- Multimodal Model architecture: Vision Encoder + Language Decoder
- CLI image input methods
- REST API Multimodal calls: images field
- Practical scenarios: product description, Bug analysis, OCR assistance
- Alice's UI screenshot analysis scenario
2. A Real Story from a SaaS Founder
ℹ️ Info: Currently, the Multimodal Models supported by Ollama are primarily the LLaVA series (llava, llava-llama3, minicpm-v, etc.). Visual understanding capability doesn't match GPT-4V, but is already practical enough for UI screenshot analysis, OCR assistance, and product description scenarios.
💡 Tip: For Multimodal Models, we recommend using
llava:13b over llava:7b — the 13B version's visual understanding is significantly improved, especially in scenarios requiring detail description (e.g., UI element positions, chart data). 7B is suited for simple classification; 13B is suited for description and analysis.
(1) The Pain Point: Too Many User Feedback Screenshots to Review
Alice's GlobalShop e-commerce team receives 50+ user feedback items daily, each with a UI screenshot. Manually analyzing screenshots and writing feedback reports is too time-consuming. Alice wants to automate this process.
(2) The Solution: Vision Model Auto-Analyzes Screenshots
Using the LLaVA Model to automatically analyze UI screenshots and generate structured feedback reports:
BASH
ollama run llava "What UI issues do you see in this image?" /path/to/screenshot.png
3. Multimodal Model Architecture
⚠️ Warning: Multimodal Models (such as llava) are 2-3x larger than text-only Models and image processing consumes more VRAM. A GPU with 8GB VRAM may only handle low-resolution images; high-resolution images may cause OOM (out of memory). Test with small images first.
(1) Vision-Language Model (VLM) Principles
flowchart TD
A[Image Input] --> B[Vision Encoder<br/>CLIP/ViT]
B --> C[Image Embeddings]
D[Text Input] --> E[Text Tokenizer]
E --> F[Text Embeddings]
C --> G[Projection Layer]
F --> G
G --> H[Language Model<br/>LLaMA/Mistral]
H --> I[Text Output]
| Component | Function | Model Example |
|---|---|---|
| Vision Encoder | Extract image features | CLIP ViT-L/14 |
| Projection Layer | Align visual and language spaces | MLP adapter |
| Language Model | Generate text description | LLaMA 2 / Mistral |
(2) Available Multimodal Model Comparison
| Model | Parameters | Size | Strengths | Image Types |
|---|---|---|---|---|
| llava | 7B | 4.7 GB | General image description | Photos/screenshots/documents |
| llava-llama3 | 8B | 5.5 GB | Stronger reasoning + vision | Complex scene understanding |
| llava:13b | 13B | 7.4 GB | Higher accuracy | Detail recognition |
| minicpm-v | 8B | 5.2 GB | OCR + Chinese | Documents/tables |
| bakllava | 7B | 4.7 GB | Lightweight and fast | Simple images |
▶ Example 1: Pull and Run LLaVA
BASH
# Pull the multimodal model
ollama pull llava
# Basic image description (CLI with file path)
ollama run llava "Describe this image in detail" /path/to/photo.jpg
# Without image: text-only mode
ollama run llava "What is machine learning?"
Output:
TEXT
I'm a helpful AI assistant running locally on your machine...
4. CLI Image Input Methods
(1) Two Image Input Methods
⚠️ Note: Images are automatically scaled to the Model's maximum supported resolution (typically 336×336 or 448×448 pixels) before being fed into the Model. Very high-resolution original image details may be lost in this process. If you need the Model to recognize small text or details in an image, crop the image to the key area first rather than sending the entire high-resolution image.
| Method | Syntax | Use Case |
|---|---|---|
| File path | ollama run llava "prompt" /path/to/image.jpg |
Local images, simplest |
| Interactive | Use .image command in conversation |
Dynamic image input |
(2) Supported Image Formats
| Format | Extension | Max Size | Notes |
|---|---|---|---|
| JPEG | .jpg/.jpeg | Within limits | Best for photos |
| PNG | .png | Within limits | Screenshots/text content |
| WebP | .webp | Within limits | Web images |
| GIF | .gif | First frame only | No animation support |
⚠️ Note: Images are scaled to the Model's supported resolution (typically 336×336 or 448×448 pixels). Very high-resolution image details may be lost.
▶ Example 2: CLI Multimodal Interaction
BASH
# Start interactive session with image
ollama run llava
>>> .image /path/to/product-photo.jpg
>>> What product is shown and what are its key features?
# Output: The image shows a pair of premium wireless headphones...
# Key features include:
# 1. Over-ear design with memory foam cushions
# 2. Active noise cancellation
# 3. USB-C charging port visible on the left ear cup
>>> .image /path/to/chart.png
>>> Summarize the data trends shown in this chart
# Output: The chart displays quarterly revenue from 2023-2024...
Output:
TEXT
I'm a helpful AI assistant running locally on your machine...
5. REST API Multimodal Calls
(1) API Request Format
Both /api/chat and /api/generate support the images field, passing Base64-encoded images:
| Field | Type | Description |
|---|---|---|
| images | list[string] | Base64-encoded image list |
| Each image | string | Without data:image/... prefix |
▶ Example 3: REST API Base64 Image Call
BASH
# Convert image to Base64 and call API
IMAGE_BASE64=$(base64 -w 0 /path/to/photo.jpg)
curl http://localhost:11434/api/chat -d "{
\"model\": \"llava\",
\"messages\": [{
\"role\": \"user\",
\"content\": \"Describe this image\",
\"images\": [\"$IMAGE_BASE64\"]
}],
\"stream\": false
}"
Output:
TEXT
{"status":"ok","data":{}}
▶ Example 4: Python SDK Multimodal Call
PYTHON
import ollama
import base64
from pathlib import Path
def analyze_image(image_path: str, prompt: str, model: str = "llava") -> str:
"""Analyze an image using a multimodal model."""
# Read and encode image
image_data = base64.b64encode(
Path(image_path).read_bytes()
).decode("utf-8")
response = ollama.chat(
model=model,
messages=[{
"role": "user",
"content": prompt,
"images": [image_data]
}],
stream=False
)
return response["message"]["content"]
# Usage
result = analyze_image(
"/path/to/screenshot.png",
"List all UI issues you can identify in this screenshot"
)
print(result)
Output:
TEXT
# Function defined successfully
6. Practical Scenarios
(1) Scenario Comparison
| Scenario | Input | Recommended Model | Prompt Example |
|---|---|---|---|
| Product description | Product photo | llava | "Describe this product for an e-commerce listing" |
| Bug analysis | UI screenshot | llava-llama3 | "What UI bugs are visible in this screenshot?" |
| OCR assistance | Document scan | minicpm-v | "Extract all text from this document image" |
| Chart interpretation | Data chart | llava | "Summarize the trends in this data chart" |
| Safety review | Content image | llava | "Does this image contain any unsafe content?" |
▶ Example 5: Alice's UI Screenshot Analysis
PYTHON
import ollama
import base64
from pathlib import Path
import json
def analyze_ui_screenshot(image_path: str) -> dict:
"""Analyze a UI screenshot and return structured feedback."""
image_data = base64.b64encode(
Path(image_path).read_bytes()
).decode("utf-8")
system_prompt = """You are a UI/UX expert reviewing application screenshots.
Analyze the screenshot and provide feedback in this JSON format:
{
"issues": [{"type": "layout|color|text|accessibility", "description": "...", "severity": "high|medium|low"}],
"summary": "Brief overall assessment"
}"""
response = ollama.chat(
model="llava-llama3",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": "Review this UI screenshot for issues",
"images": [image_data]}
],
stream=False,
format="json",
options={"temperature": 0.3}
)
try:
return json.loads(response["message"]["content"])
except json.JSONDecodeError:
return {"raw": response["message"]["content"]}
# Usage
feedback = analyze_ui_screenshot("/path/to/app-screenshot.png")
print(json.dumps(feedback, indent=2))
Output:
TEXT
# Function defined successfully
7. Comprehensive Example: Multimodal Customer Service Assistant System
PYTHON
# ============================================
# Comprehensive: Multimodal customer service
# Image analysis + text chat for e-commerce
# ============================================
import ollama
import base64
from pathlib import Path
from dataclasses import dataclass
from typing import Optional
@dataclass
class MultimodalSupport:
chat_model: str = "qwen2.5"
vision_model: str = "llava"
temperature: float = 0.3
def handle_product_query(
self, image_path: str, question: str
) -> str:
"""Answer product questions using image + text."""
image_data = base64.b64encode(
Path(image_path).read_bytes()
).decode("utf-8")
response = ollama.chat(
model=self.vision_model,
messages=[{
"role": "user",
"content": f"Answer this question about the product shown: {question}",
"images": [image_data]
}],
stream=False,
options={"temperature": self.temperature}
)
return response["message"]["content"]
def handle_damage_report(
self, image_path: str, order_id: str
) -> str:
"""Process a damage report with photo evidence."""
image_data = base64.b64encode(
Path(image_path).read_bytes()
).decode("utf-8")
# Step 1: Analyze damage from image
damage_desc = ollama.chat(
model=self.vision_model,
messages=[{
"role": "user",
"content": "Describe the damage visible in this product photo. Be specific about the type and severity.",
"images": [image_data]
}],
stream=False,
options={"temperature": 0.2}
)["message"]["content"]
# Step 2: Generate response using chat model
response = ollama.chat(
model=self.chat_model,
messages=[
{"role": "system", "content": "You are an e-commerce customer service agent handling damage reports."},
{"role": "user", "content": f"Order {order_id} has damage: {damage_desc}. Generate a polite response acknowledging the damage and explaining the refund/replacement process."}
],
stream=False,
options={"temperature": self.temperature}
)
return response["message"]["content"]
def extract_text_from_image(
self, image_path: str
) -> str:
"""OCR-like text extraction from document images."""
image_data = base64.b64encode(
Path(image_path).read_bytes()
).decode("utf-8")
response = ollama.chat(
model="minicpm-v",
messages=[{
"role": "user",
"content": "Extract all visible text from this image. Preserve the original layout and formatting.",
"images": [image_data]
}],
stream=False,
options={"temperature": 0.1}
)
return response["message"]["content"]
# Usage
if __name__ == "__main__":
service = MultimodalSupport()
print("=== Damage Report ===")
# print(service.handle_damage_report("damaged_item.jpg", "#12345"))
print("=== Product Query ===")
# print(service.handle_product_query("headphones.jpg", "Does this have noise cancellation?"))
print("=== OCR Extraction ===")
# print(service.extract_text_from_image("receipt.png"))
❓ FAQ
Q Can Multimodal Models and text-only Models be used interchangeably?
A No. Multimodal Models process images + text; text-only Models only process text. Multimodal Models can handle text-only input without images, but text-only Models cannot process images.
Q Does image resolution affect Inference speed?
A Yes. Higher-resolution images encode more tokens, increasing Inference time. Ollama automatically scales to the Model's maximum supported resolution — no manual adjustment needed.
Q Can a single image have multiple questions?
A Yes. List multiple questions in the prompt and the Model will answer them one by one. However, we recommend focusing on 1-2 questions per call for more accurate responses.
Q How good is llava's Chinese capability?
A llava is primarily English-oriented. For Chinese image description, we recommend minicpm-v or qwen2.5-vl (if available). Using Chinese prompts will yield Chinese responses.
Q Can video be processed?
A Currently Ollama Multimodal only supports static images. Video requires extracting key frames as images first, then analyzing frame by frame. GIF only processes the first frame.
Q Base64-encoded images are too large, what should I do?
A Compress images to a reasonable resolution first (e.g., within 1024px). JPEG quality set to 80 is usually sufficient. Avoid sending 10MB+ originals.
📖 Summary
- Multimodal Model = Vision Encoder + Projection Layer + Language Model, enabling image-text understanding
- The llava series is Ollama's primary vision Model, supporting photos/screenshots/documents
- CLI uses file paths for image input; API uses Base64-encoded images field
- Practical scenarios: product description, Bug analysis, OCR assistance, chart interpretation
- Python SDK passes Base64 image data via the images list
- Alice automated UI screenshot analysis with llava, reducing each from 10 minutes to 5 seconds
📝 Exercises
- Basic (Difficulty ⭐): Pull the llava Model, use the CLI to analyze a product photo and describe its features.
- Intermediate (Difficulty ⭐⭐): Use the Python SDK to implement image + text multi-turn dialogue — first analyze the image content, then ask follow-up questions based on the analysis.
- Advanced (Difficulty ⭐⭐⭐): Build an automated UI screenshot review tool for Alice: input a screenshot, output a structured JSON Bug report (type, description, severity), and auto-classify and archive.