Spring › Spring-AI

Parsing receipts and audio meetings with Spring AI and Gemini

Use Spring AI 2.0.1 Media and Gemini native multimodal models to parse receipt images and meeting audio directly into Kotlin DTOs without OCR or STT.

Parsing receipts and audio meetings with Spring AI and Gemini

Turning receipt photos or recorded meetings into structured database records used to mean chaining separate OCR or speech-to-text services in front of an LLM. That adds latency, extra infrastructure, and compounding transcription errors. This post shows how to combine Spring AI 2.0.1’s Media abstraction with Google Gemini’s native multimodal models and structured output to parse images and audio into Kotlin DTOs in a single API call.

Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, Jackson 3 (tools.jackson), and gemini-3.5-flash-lite.


Dedicated OCR/STT pipelines vs. native multimodal

Traditional document and audio extraction pipelines flatten raw media into plain text before the LLM ever sees it. With receipts, flattening loses the visual row alignment between item names, quantities, and unit prices. With audio, flattening drops speaker cadence and pauses.

flowchart TD
    Upload["Multipart upload (receipt image or meeting audio)"] --> Normalize["MediaFile MIME validation & normalization"]
    Normalize --> Media["Spring AI Media attachment"]
    Media --> Gemini["Single Gemini generateContent call"]
    Gemini --> DTO["Structured Kotlin DTO (Receipt / MeetingMinutes)"]

Trade-offs: dedicated engines vs. native multimodal

DimensionDedicated OCR / STT + LLMGemini native multimodal
InfrastructureSeparate OCR/STT containers or cloud APIsSingle Gemini API key
Layout & audio nuanceLost when flattened to raw textPreserved in model attention
Error propagationOCR/STT mistakes compound in LLM stepSingle end-to-end extraction
High-volume unit costLower at massive scale with self-hosted modelsHigher per-minute audio or high-res image
Payload size limitFlexible streaming / chunking20 MB inline limit (File API needed above that)

When not to use inline native multimodal: Don’t push multi-hour recordings or 4K video inline through Spring MVC—they exceed Gemini’s 20 MB inline payload cap and tie up servlet memory. Also skip multimodal LLMs when you only need exact word-level timestamps with strict deterministic billing at millions of audio minutes per month; a dedicated streaming STT engine is cheaper and more predictable there.


Project setup and upload limits

The complete runnable module is in spring-ai-examples (multimodal).

build.gradle.kts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
plugins {
    kotlin("jvm") version "2.3.21"
    kotlin("plugin.spring") version "2.3.21"
    id("org.springframework.boot") version "4.1.1"
    id("io.spring.dependency-management") version "1.1.7"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
    implementation("tools.jackson.module:jackson-module-kotlin")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}

application.yaml

Gemini caps inline Base64 requests at 20 MB. Because Base64 inflates binary size by roughly 33%, a 15 MB raw upload expands right up to that 20 MB ceiling. Cap Spring’s multipart upload limit at 15 MB so oversized files fail fast at the HTTP boundary:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server:
  port: 8086

spring:
  application:
    name: multimodal
  servlet:
    multipart:
      # Cap raw uploads at 15 MB to stay under Gemini's 20 MB inline Base64 limit
      max-file-size: 15MB
      max-request-size: 15MB
  ai:
    google:
      genai:
        api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY:demo-key}
        chat:
          model: gemini-3.5-flash-lite

Normalizing MIME types with MediaFile

Spring AI’s org.springframework.ai.content.Media lets you attach binary payloads directly to a user message. In practice, browsers, curl, and mobile SDKs send non-canonical Content-Type headers that Gemini rejects with 400 INVALID_ARGUMENT: Unsupported MIME type:

  • MP3 audio arrives as audio/mpeg, while Gemini expects audio/mp3.
  • WAV audio arrives as audio/x-wav, audio/wave, or audio/vnd.wave, while Gemini expects audio/wav.
  • JPEG images sometimes arrive as image/jpg instead of image/jpeg.
  • Generic clients send application/octet-stream, requiring fallback inference from the file extension.

I wrapped validation and alias normalization inside a small MediaFile helper before constructing Spring AI’s Media:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package io.github.cmsong111.multimodal.support

import org.springframework.ai.content.Media
import org.springframework.util.MimeType
import org.springframework.web.multipart.MultipartFile

class MediaFile(
    val name: String,
    val mimeType: MimeType,
    val bytes: ByteArray,
) {

    fun toMedia(): Media {
        return Media.builder()
            .mimeType(mimeType)
            .data(bytes)
            .name(name)
            .build()
    }

    companion object {
        val SUPPORTED_IMAGE_TYPES = setOf("image/png", "image/jpeg", "image/webp", "image/heic", "image/heif")
        val SUPPORTED_AUDIO_TYPES = setOf("audio/wav", "audio/mp3", "audio/aiff", "audio/aac", "audio/ogg", "audio/flac")

        private val ALIASES = mapOf(
            "image/jpg" to "image/jpeg",
            "audio/mpeg" to "audio/mp3",
            "audio/x-wav" to "audio/wav",
            "audio/wave" to "audio/wav",
            "audio/vnd.wave" to "audio/wav",
            "audio/x-aiff" to "audio/aiff",
            "audio/x-flac" to "audio/flac",
            "audio/x-aac" to "audio/aac",
        )

        private val EXTENSIONS = mapOf(
            "png" to "image/png", "jpg" to "image/jpeg", "jpeg" to "image/jpeg",
            "webp" to "image/webp", "heic" to "image/heic", "heif" to "image/heif",
            "wav" to "audio/wav", "mp3" to "audio/mp3", "aiff" to "audio/aiff",
            "aac" to "audio/aac", "ogg" to "audio/ogg", "flac" to "audio/flac",
        )

        fun image(file: MultipartFile): MediaFile = of(file, SUPPORTED_IMAGE_TYPES)
        fun audio(file: MultipartFile): MediaFile = of(file, SUPPORTED_AUDIO_TYPES)

        fun of(file: MultipartFile, supportedTypes: Set<String>): MediaFile {
            if (file.isEmpty) {
                throw UnsupportedMediaException("Empty files cannot be processed.")
            }
            val name = file.originalFilename ?: "upload"
            val mimeType = resolveMimeType(file.contentType, name)
            if (mimeType == null || mimeType !in supportedTypes) {
                throw UnsupportedMediaException(
                    "Unsupported file format: ${file.contentType ?: name} (supported: ${supportedTypes.joinToString()})"
                )
            }
            return MediaFile(name, MimeType.valueOf(mimeType), file.bytes)
        }

        fun resolveMimeType(contentType: String?, fileName: String): String? {
            val declared = contentType?.substringBefore(';')?.trim()?.lowercase()
            if (!declared.isNullOrBlank() && declared != "application/octet-stream") {
                return ALIASES[declared] ?: declared
            }
            return EXTENSIONS[fileName.substringAfterLast('.', "").lowercase()]
        }
    }
}

class UnsupportedMediaException(message: String) : RuntimeException(message)

Debug log showing inbound MIME normalization from audio/mpeg to audio/mp3 and 415 rejection Figure 1. Inbound MIME normalization (audio/mpeg → audio/mp3) and 415 Unsupported Media Type rejection for invalid formats.


Receipt vision analysis and audio meeting summaries

With MediaFile handling format hygiene, both vision and audio extraction follow the same ChatClient pattern: attach .media(file.toMedia()) inside .user { ... } and bind the output with .entity(...) (or pair it with the native schema approach from enforcing Gemini JSON output with Spring AI BeanOutputConverter).

Receipt DTO and service method

@JsonPropertyDescription gives the model clear field-level hints for nullable timestamps and integer currency values:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package io.github.cmsong111.multimodal.dto

import com.fasterxml.jackson.annotation.JsonPropertyDescription

data class Receipt(
    @field:JsonPropertyDescription("Merchant or store name")
    val storeName: String,

    @field:JsonPropertyDescription("Purchase timestamp in ISO-8601 (e.g., 2026-10-11T12:30:00), or null if absent")
    val purchasedAt: String?,

    @field:JsonPropertyDescription("Purchased line items")
    val items: List<ReceiptItem>,

    @field:JsonPropertyDescription("Final total amount as an integer")
    val totalAmount: Long,

    @field:JsonPropertyDescription("ISO-4217 currency code (e.g., KRW, USD)")
    val currency: String,
)

data class ReceiptItem(
    @field:JsonPropertyDescription("Item name")
    val name: String,

    @field:JsonPropertyDescription("Quantity")
    val quantity: Int,

    @field:JsonPropertyDescription("Unit price")
    val unitPrice: Long,

    @field:JsonPropertyDescription("Line total (quantity * unitPrice)")
    val amount: Long,
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fun analyzeReceipt(image: MediaFile): Receipt {
    return chatClient.prompt()
        .user { user ->
            user.text(
                """
                Extract the store name, purchase timestamp, line items (name, quantity, unit price, amount),
                total amount, and currency from the attached receipt image.
                Return all monetary amounts as plain integers without currency symbols or commas.
                """.trimIndent()
            ).media(image.toMedia())
        }
        .call()
        .entity(Receipt::class.java)
        ?: throw IllegalStateException("Receipt analysis returned an empty result.")
}

Meeting audio DTO and service method

For recorded meetings, Gemini processes the audio stream directly and returns structured summaries, decisions, and action items in one round trip:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package io.github.cmsong111.multimodal.dto

import com.fasterxml.jackson.annotation.JsonPropertyDescription

data class MeetingMinutes(
    @field:JsonPropertyDescription("One-line title describing the meeting topic")
    val title: String,

    @field:JsonPropertyDescription("Concise summary in 3 sentences or fewer")
    val summary: String,

    @field:JsonPropertyDescription("Speakers or mentioned participant names")
    val participants: List<String>,

    @field:JsonPropertyDescription("Key decisions made during the meeting")
    val decisions: List<String>,

    @field:JsonPropertyDescription("Follow-up action items")
    val actionItems: List<ActionItem>,
)

data class ActionItem(
    @field:JsonPropertyDescription("Owner name, or null if unspecified")
    val owner: String?,

    @field:JsonPropertyDescription("Task to complete")
    val task: String,

    @field:JsonPropertyDescription("Due date as stated (e.g., by Wednesday), or null if unspecified")
    val dueDate: String?,
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fun summarizeMeeting(audio: MediaFile): MeetingMinutes {
    return chatClient.prompt()
        .user { user ->
            user.text(
                """
                Listen to the attached meeting recording and produce structured meeting minutes.
                Extract a concise summary, participants, key decisions, and action items with owners and due dates.
                """.trimIndent()
            ).media(audio.toMedia())
        }
        .call()
        .entity(MeetingMinutes::class.java)
        ?: throw IllegalStateException("Meeting summary returned an empty result.")
}

Multipart controller

Expose the endpoints with @RequestPart and map UnsupportedMediaException to 415 Unsupported Media Type:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package io.github.cmsong111.multimodal.controller

import io.github.cmsong111.multimodal.dto.MeetingMinutes
import io.github.cmsong111.multimodal.dto.Receipt
import io.github.cmsong111.multimodal.service.MultimodalService
import io.github.cmsong111.multimodal.support.MediaFile
import io.github.cmsong111.multimodal.support.UnsupportedMediaException
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile

@RestController
@RequestMapping("/api/multimodal")
class MultimodalController(
    private val multimodalService: MultimodalService
) {

    @PostMapping("/describe", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
    fun describe(
        @RequestPart file: MultipartFile,
        @RequestParam(defaultValue = "Describe this image in detail.") question: String,
    ): Map<String, String> {
        return mapOf("result" to multimodalService.describeImage(MediaFile.image(file), question))
    }

    @PostMapping("/receipt", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
    fun receipt(@RequestPart file: MultipartFile): Receipt {
        return multimodalService.analyzeReceipt(MediaFile.image(file))
    }

    @PostMapping("/meeting", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
    fun meeting(@RequestPart file: MultipartFile): MeetingMinutes {
        return multimodalService.summarizeMeeting(MediaFile.audio(file))
    }

    @ExceptionHandler(UnsupportedMediaException::class)
    fun handleUnsupportedMedia(e: UnsupportedMediaException): ResponseEntity<Map<String, String?>> {
        return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body(mapOf("error" to e.message))
    }
}

Verification with Gradle and curl

I verified the module with mock unit tests (FakeChatModel) and live integration tests using a Java2D-rendered receipt PNG and a recorded meeting WAV sample:

1
./gradlew :multimodal:test

Console output showing Spring AI Gemini multimodal receipt and audio tests passing Figure 2. Integration test console output confirming receipt image parsing and meeting audio summarization.

Testing the /api/multimodal/meeting endpoint directly with curl:

1
2
curl -s -X POST -F "file=@multimodal/src/test/resources/samples/meeting.wav" \
  http://localhost:8086/api/multimodal/meeting | jq .

cURL JSON output from uploading a meeting audio file to the multimodal endpoint Figure 3. Structured MeetingMinutes JSON returned directly from an uploaded WAV recording.


Payload sizing, cost control, and checklist

Sending raw binaries inline is fast to build, but production media uploads need three guardrails:

Inline Media attachments are Base64-encoded into Gemini’s inlineData field, adding ~33% overhead. Any raw upload larger than 15 MB risks hitting the 20 MB API limit and failing with 400 INVALID_ARGUMENT. For long recordings or high-bitrate video, upload through the Google AI File API and pass the file URI instead.

  • Downscale smartphone photos before sending: A raw 4000×3000 receipt photo (~8 MB) doesn’t read any better than a 1200–1600 px resized copy, but resizing cuts upload time and image token spend by more than 70%.
  • Transcode audio to 16 kHz mono: Speech understanding doesn’t benefit from 48 kHz stereo WAV files. Converting to 16 kHz mono MP3 or Opus fits a full hour of audio under 10 MB so it stays within inline limits.
  • Sanitize untrusted user uploads: Validate actual MIME types (and consider magic-byte checks for public endpoints), and pair public multimodal endpoints with Gemini safety settings and guardrails.

Pre-deploy checklist

  • Cap spring.servlet.multipart.max-file-size at 15 MB for inline Gemini Media calls.
  • Normalize browser and OS MIME aliases (audio/mpeg → audio/mp3, image/jpg → image/jpeg) before calling Gemini.
  • Resize large receipt images (1200–1600 px longest edge) and downsample audio to 16 kHz mono to cut latency and tokens.
  • Switch to the Google AI File API whenever raw files can exceed 15 MB.

The complete source code for this walkthrough is in cmsong111/spring-ai-examples/multimodal.

This post is licensed under CC BY 4.0 by the author.