Implementation:Ollama Ollama Imagegen Dispatch
| Knowledge Sources | |
|---|---|
| Domains | Image Generation, Server |
| Last Updated | 2025-02-15 00:00 GMT |
Overview
Dispatches image generation requests by detecting model type, loading appropriate models, and routing HTTP requests to image or LLM handlers.
Description
The imagegen.go file defines the ImageModel interface for image generation and the server struct that serves as the central request dispatcher. The loadImageModel function detects model type via DetectModelType (checking model_index.json for pipeline class) and creates the appropriate model instance (Flux2 or ZImage). The handleImageCompletion function serializes generation via a mutex, sets up streaming NDJSON responses with progress callbacks, invokes GenerateImage, encodes results as base64 PNG, and cleans up MLX memory. The file bridges Ollama's model detection system with the specific image generation pipelines.
Usage
Used by the imagegen HTTP server to dispatch /completion requests to either image generation or LLM handlers based on model mode.
Code Reference
Source Location
- Repository: Ollama
- File: x/imagegen/imagegen.go
- Lines: 1-134
Signature
type ImageModel interface {
GenerateImage(ctx context.Context, prompt string, width, height int32, steps int, seed int64, progress func(step, total int)) (*mlx.Array, error)
}
func (s *server) loadImageModel() error
func (s *server) handleImageCompletion(w http.ResponseWriter, r *http.Request, req Request)
Import
import "github.com/ollama/ollama/x/imagegen"
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| req | Request | Yes | HTTP request with prompt, dimensions, steps, seed |
Outputs
| Name | Type | Description |
|---|---|---|
| NDJSON stream | Response | Streaming progress updates followed by base64 image |
Usage Examples
// The dispatch happens automatically in the server:
// POST /completion with {"prompt": "a cat", "width": 1024, "height": 1024}
//
// Response stream:
// {"step": 1, "total": 8}
// {"step": 2, "total": 8}
// ...
// {"image": "<base64 PNG>", "done": true}