UserMessage payloads and exposes dedicated model interfaces for media generation and transcription.1. Multimodal Architecture & The Media Abstraction
-
UserMessageDual Payload: Alongside its primarytextprompt string,UserMessageholds an optionalList<Media>collection representing non-text attachments sent simultaneously to the model. -
The
MediaObject: Encapsulates any binary or referenced media asset by pairing:-
MIME Type (
MimeType): Explicitly identifies the format (such asimage/png,image/jpeg,audio/mp3,audio/wav,video/mp4, orapplication/pdf). -
Data Source: Accepts either a Spring
Resource(classpath file, local file, byte array, or uploadedMultipartFile) or a remoteURI/ URL pointing to the asset.
-
-
Fluent
ChatClientAttachment: ThroughChatClient, developers attach media resources directly inside the.user()prompt specification alongside natural-language instructions, allowing the underlyingChatModelto serialize the payload into the provider’s native multimodal wire format (base64 data blocks or file URIs).
2. Core Multimodal Capabilities & Model APIs
| Modality / Capability | Spring AI API / Abstraction | Core Functionality & Use Cases |
| Multimodal Understanding (Vision, Audio, Video, PDF) | ChatClient / ChatModel with Media attachments |
Sends images, audio clips, video files, or multi-page PDFs alongside text prompts for visual Q&A, OCR/receipt extraction, chart interpretation, UI-to-code analysis, or document summarization. |
| Image Generation (Text-to-Image) | ImageModel (ImagePrompt, ImageResponse, ImageOptions) |
Generates images from natural-language descriptions with configurable resolution, aspect ratio, quality (hd / standard), style, and output format (URL or base64 bytes). |
| Speech-to-Text (Audio Transcription) | TranscriptionModel (AudioTranscriptionPrompt, AudioTranscriptionResponse) |
Converts spoken audio files (MP3, WAV, M4A, WebM) into accurate text transcripts with configurable language hints, temperature, and response formats (JSON, SRT, VTT). |
| Text-to-Speech (Speech Synthesis) | TextToSpeechModel (TextToSpeechPrompt, TextToSpeechResponse) |
Synthesizes natural-sounding spoken audio streams (byte[] or reactive Flux<byte[]>) from text with selectable voices, playback speed, and audio codecs. |
3. Provider Multimodal Support Matrix
-
Google Gemini (Google GenAI & Vertex AI): Offers native any-to-text multimodality—accepting text, images, audio files, video streams, and PDF documents directly inside
UserMessageMediaattachments—alongside Imagen/Gemini image generation and multimodal embeddings. -
Anthropic Claude: Supports high-precision vision analysis (images, diagrams, screenshots) and native PDF document understanding directly within
ChatClientuser messages, paired with Structured Output mapping (.entity()). -
OpenAI & Azure OpenAI: Provides broad end-to-end coverage across GPT vision inputs, audio-enabled chat models, dedicated
ImageModel(DALL-E / GPT Image),TranscriptionModel(Whisper / GPT-4o Transcribe), andTextToSpeechModel. -
Ollama (Local Multimodal Models): Enables running open-weight vision models (such as Llama Vision, Gemma 3, Qwen-VL, or LLaVA) locally on private hardware for offline image analysis without external cloud costs.
4. Combining Multimodality with Structured Outputs & RAG
-
Multimodal-to-POJO Extraction: Pairing
Mediaattachments withChatClient.call().entity(...)enables automated document processing pipelines—for example, passing a scanned invoice image or PDF receipt and receiving a strongly typed Java record containing vendor name, line items, tax, and total amount. -
Multimodal RAG Pipelines: Enterprise knowledge bases frequently contain charts, architectural diagrams, and scanned forms alongside text. Spring AI supports multimodal RAG either by generating rich text descriptions of visual assets during ETL ingestion or by using multimodal embedding models (such as Vertex AI Multimodal Embeddings) to index both text and images in the same vector space.
5. Production Best Practices
-
Optimize Media Size & Resolution Before Transmission: High-resolution images and uncompressed audio files consume significant tokens, increase upload latency, and risk hitting provider payload size limits; resize images and compress audio streams before wrapping them in
Mediaobjects. -
Validate MIME Types Strictly: Always verify incoming file headers rather than trusting file extensions alone so unsupported formats are rejected gracefully before invoking paid model APIs.
-
Prefer Provider File APIs for Large Video & Audio Assets: When processing long videos or multi-hour audio recordings (particularly with Google Gemini), upload media via provider file storage references (
URI) rather than inline base64 payloads to avoid memory spikes in your Spring Boot JVM. -
Remember Conversation Memory Trade-Offs: Storing raw binary image or audio bytes inside persistent
ChatMemoryquickly bloats database storage and re-sends heavy media tokens on every subsequent turn; persist text summaries or file references instead of raw binary blobs across multi-turn sessions.
Hands-on Experiment: AI Image and Document Understanding System using Spring AI Multimodal Processing
Aim: To build a Spring Boot application that uses Spring AI to understand images, documents and audio recordings, and to answer questions about them.
Description: The application is an upload-based understanding system. A user uploads an image (for example an invoice or a photo), a document (PDF or text) or an audio recording (for example a meeting), and optionally types a question. For images, the picture and question go to the vision model together. For documents, the text is extracted in Java and the model summarizes it or answers from it. For audio, the speech is transcribed first and the model then summarizes the transcript. Every result is stored in MySQL, and the user can ask follow-up questions about any stored document or recording.
Software / Tools Required
- JDK 17
- Spring Boot 3.x
- Maven
- MySQL 8.x
- IDE (IntelliJ IDEA / Eclipse / VS Code)
- Postman
- An OpenAI API key (environment variable
OPENAI_API_KEY) - Sample files: one image (png/jpg), one PDF or text file, one short audio file (mp3/wav/m4a)
Steps
- Generate the project using Spring Initializr
- Add the Spring AI BOM, the PDFBox dependency and the other dependencies in
pom.xml - Configure MySQL, file upload limits, the chat model and the transcription model in
application.properties - Create the entity
AnalysisRecord - Create the repository
- Create
ImageAnalysisService - Create
DocumentAnalysisService - Create
AudioAnalysisService - Create
AnalysisHistoryServicefor history and follow-up questions - Create the REST controller
- Run the application and test with Postman
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
| Field | Value |
|---|---|
| Project | Maven |
| Language | Java |
| Spring Boot | 3.4.x (Spring AI 1.0 needs 3.4.x) |
| Group | com.example |
| Artifact | multimodal-understanding-system |
| Packaging | Jar |
| Java | 17 |
| Dependencies | Spring Web, Spring Data JPA, MySQL Driver, OpenAI (Spring AI) |
PDFBox is not in Initializr. It is added manually in pom.xml, as in the zip.
Step 2: Project Structure
multimodal-understanding-system
├── pom.xml
├── README.md
└── src/main
├── java/com/example/multimodal
│ ├── MultimodalApplication.java
│ ├── entity
│ │ └── AnalysisRecord.java
│ ├── repository
│ │ └── AnalysisRecordRepository.java
│ ├── service
│ │ ├── ImageAnalysisService.java
│ │ ├── DocumentAnalysisService.java
│ │ ├── AudioAnalysisService.java
│ │ └── AnalysisHistoryService.java
│ └── controller
│ └── MultimodalController.java
└── resources/application.properties
Step 3: Github Link:
Step 4: Download the application from above github link, then test the below CURD operations
Running the Application
- Start MySQL. The database
multimodal_dbis created automatically. - Set the key:
export OPENAI_API_KEY=sk-...(Windows:setx OPENAI_API_KEY "sk-...", then reopen the terminal). - Run
mvn spring-boot:run, or runMultimodalApplicationfrom your IDE. - The app starts at
http://localhost:8080. Test with Postman using Body, then form-data, and set thefilekey type to File.
URLs and Request Payloads
Upload endpoints (Postman form-data)
| # | Method | URL | form-data fields | What to check |
|---|---|---|---|---|
| 1 | POST | /api/image/analyze |
file = a photo (png, jpg, webp, gif) |
Description of the image, since no question is given |
| 2 | POST | /api/image/analyze |
file = an invoice or receipt image, question = What is the total amount? |
Answer read from the picture |
| 3 | POST | /api/document/analyze |
file = a PDF or txt file |
Default summary and key names, dates, amounts |
| 4 | POST | /api/document/analyze |
file = a PDF, question = List all deadlines |
Answer only from the document |
| 5 | POST | /api/audio/analyze |
file = an mp3, wav or m4a file |
Transcript stored, with a summary and action items |
| 6 | POST | /api/audio/analyze |
file = an audio file, question = Who agreed to do what? |
Answer from the transcript |
Follow-up questions (JSON body)
| # | Method | URL | Payload | What to check |
|---|---|---|---|---|
| 7 | POST | /api/analyses/{id}/ask |
{ "question": "Who is responsible for the budget?" } |
Use the id of a document or audio analysis from the earlier responses |
| 8 | POST | /api/analyses/{id}/ask |
{ "question": "What colour is the logo?" } |
Use an image id. It returns 400 because images must be uploaded again with the new question |
History
| # | Method | URL | What to check |
|---|---|---|---|
| 9 | GET | /api/analyses |
All analyses, newest first |
| 10 | GET | /api/analyses?type=AUDIO |
Filter by IMAGE, DOCUMENT or AUDIO |
| 11 | GET | /api/analyses/{id} |
One record with the extracted text or transcript and the result |
Error cases to try
| # | Request | Expected result |
|---|---|---|
| 12 | /api/image/analyze with a PDF file |
400, only png, jpg, jpeg, gif and webp are supported |
| 13 | /api/document/analyze with a scanned PDF (only pictures) |
422, no readable text; upload a page as an image instead |
| 14 | /api/audio/analyze with an unsupported file such as .txt |
400, lists the supported audio formats |
Keep audio files short while testing (under a few minutes), because transcription is billed by audio length. Audio files must be under 25 MB, and the app limits uploads to 20 MB.
