Spring › Spring-AI

Preserving Gemini Search Grounding metadata with the GenAI SDK

Spring AI 2.0.1 drops Gemini Search Grounding metadata during ChatResponse mapping. Bypass it behind a domain interface using the official Google GenAI SDK.

Preserving Gemini Search Grounding metadata with the GenAI SDK

Spring AI 2.0.1’s generic ChatResponse mapping strips out Gemini’s groundingMetadata, dropping the verified web source URLs (groundingChunks) and search queries my pipeline needed to block hallucinated links. Here is how I bypassed ChatModel behind a clean domain interface using the official Google GenAI Java SDK (com.google.genai.Client) and split search from JSON structuring into a two-step pipeline.

Tested with Spring Boot, Kotlin, Spring AI 2.0.1, com.google.genai:google-genai, and gemini-3.5-flash-lite.


While building a legal precedent collection backend (demo-backend-server), I wrote a daily batch job (judgment-discovery-job) to scan news coverage from the past 7 days for notable lower-court rulings.

Fresh rulings rarely appear in official court portals on the day they are handed down; news outlets report them days or weeks earlier. Using an LLM with web search to extract case numbers, courts, ruling dates, and core issues made sense—until I looked closely at hallucination risk. Left unchecked, a model will invent a plausible case number, fabricate a court name, or synthesize a dead news URL right inside its markdown summary.

I enforced three strict rules before writing any production code:

  1. Require Google Search Grounding: The model must answer from live Google Search results, not from parametric memory.
  2. Never trust links inside model prose: Markdown links like [Article](https://...) written by the model can be fabricated and are never persisted as sources.
  3. Persist only engine-verified groundingChunks: Only URLs returned in Gemini’s groundingMetadata.groundingChunks become DiscoverySource records. If zero verified chunks come back, reject the candidate immediately.
flowchart TD
    A["Batch trigger (past 7 days)"] --> B["Gemini Search Grounding"]
    B --> C{"groundingChunks present?"}
    C -->|"No verified sources"| D["Reject candidate (rollback)"]
    C -->|"Verified news URLs found"| E["JSON Schema structuring call"]
    E --> F["Save candidate (awaiting admin review)"]

What Spring AI 2.0.1 drops during response mapping

I started with spring-ai-starter-model-google-genai:2.0.1 and a standard ChatModel bean:

1
2
3
4
5
6
7
val prompt = Prompt(
    "Search and summarize major court rulings reported in the news over the past 7 days.",
    GoogleGenAiChatOptions.builder()
        .model("gemini-3.5-flash-lite")
        .build()
)
val chatResponse: ChatResponse = chatModel.call(prompt)

With Google Search enabled, chatResponse.result.output.text returned a clean summary. The moment I tried to extract the grounding sources from the response metadata, everything fell apart.

Debug console comparing Spring AI ChatResponse and Google GenAI SDK grounding metadata Figure 1. Side-by-side debug dump showing Spring AI ChatResponse dropping groundingMetadata to null while the Google GenAI SDK preserves all fields.

Three pieces of data disappeared inside Spring AI’s mapping layer:

  • groundingMetadata vanished: candidate.groundingMetadata (verified web URIs, page titles, and domains) came back null on ChatResponseMetadata.
  • webSearchQueries disappeared: I couldn’t log the exact search queries Gemini ran, making retrieval debugging impossible.
  • Token counts were flattened: Gemini’s raw usageMetadata splits out thoughtsTokenCount and toolUsePromptTokenCount, but Spring AI merged them into generic prompt/generation totals, hiding search and reasoning cost.

Because my pipeline rejects any candidate with zero verified groundingChunks, every batch run threw an exception and halted.


Why generic abstractions lose provider metadata

Spring AI’s ChatModel exists to wrap OpenAI, Anthropic, Bedrock, and Gemini behind one portable ChatResponse contract. Provider-specific extensions don’t fit cleanly into that lowest common denominator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[Google GenAI raw API]
GenerateContentResponse
  └── candidates[0]
        ├── content (parts...)
        └── groundingMetadata  <-- Gemini-specific schema
              ├── webSearchQueries
              ├── groundingChunks (web.uri, web.title, web.domain)
              └── groundingSupports

                  ▼ (Spring AI 2.0.1 DTO mapping)

[Spring AI generic model]
ChatResponse
  └── results[0] -> Generation (AssistantMessage)
  └── metadata -> ChatResponseMetadata
        └── usage (promptTokens, generationTokens)
        └── (groundingMetadata field missing or unmapped)

I also hit a second problem with global options: enabling Google Search on a shared ChatModel caused the model to fire unnecessary web searches during the second JSON-structuring call, adding latency and tool-token charges.

Spring AI ChatModel vs. direct Google GenAI SDK

CriterionSpring AI ChatModelDirect Google GenAI SDK (Client)
Multi-provider portabilityHigh (swap OpenAI / Claude / Gemini)Tied to Gemini behind your own interface
groundingChunks & webSearchQueriesDropped in 2.0.1100% preserved
thoughtTokens / toolTokens breakdownMerged into generic totalsExposed individually
Per-call tool isolationEasy to leak via default optionsExplicit per-request GenerateContentConfig

When not to bypass Spring AI: If your app only needs standard chat completions, structured JSON output, or multi-provider portability across OpenAI and Gemini, stay on ChatClient. Dropping down to the raw SDK only pays off when your business rules depend on provider-native metadata like groundingChunks or per-category safety ratings.


Isolating the Google GenAI SDK behind a domain interface

Instead of leaking com.google.genai.* types into application services, I defined a DiscoveryModel port in the domain layer and confined the SDK to a single implementation (GeminiDiscoveryModel).

1. Dependencies and client configuration

Keeping spring-ai-starter-model-google-genai in build.gradle.kts already pulls in com.google.genai transitively, or you can declare the official SDK directly:

1
2
3
4
dependencies {
    implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
    implementation("tools.jackson.module:jackson-module-kotlin")
}

I reuse the existing spring.ai.google.genai.api-key property to build a dedicated Client bean with an explicit timeout and no SDK-level retries (failed batch runs retry on the next schedule):

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
// src/main/kotlin/com/example/server/discovery/JudgmentDiscoveryConfig.kt
package com.example.server.discovery

import com.google.genai.Client
import com.google.genai.types.HttpOptions
import com.google.genai.types.HttpRetryOptions
import com.example.server.discovery.application.DiscoveryModel
import com.example.server.discovery.application.GeminiDiscoveryModel
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class JudgmentDiscoveryConfig {
    /** Dedicated discovery client: timeout stays below the job lease, retries disabled at SDK level. */
    @Bean
    fun discoveryModel(
        @Value("\${spring.ai.google.genai.api-key}") apiKey: String,
        properties: JudgmentDiscoveryProperties
    ): DiscoveryModel {
        val client = Client.builder()
            .apiKey(apiKey)
            .vertexAI(false)
            .httpOptions(
                HttpOptions.builder()
                    .timeout(properties.timeout.toMillis().toInt())
                    .retryOptions(HttpRetryOptions.builder().attempts(1).build())
                    .build()
            )
            .build()
        return GeminiDiscoveryModel(client, properties)
    }
}

Bound limits live in a validated @ConfigurationProperties class:

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
// src/main/kotlin/com/example/server/discovery/JudgmentDiscoveryProperties.kt
package com.example.server.discovery

import org.springframework.boot.context.properties.ConfigurationProperties
import java.time.Duration

@ConfigurationProperties("app.judgment-discovery")
data class JudgmentDiscoveryProperties(
    val model: String = "gemini-3.5-flash-lite",
    val windowDays: Int = 7,
    val maxCandidates: Int = 10,
    val dailyCallLimit: Int = 4,
    val timeout: Duration = Duration.ofSeconds(120),
    val maxOutputTokens: Int = 8192,
    val verifyBatchSize: Int = 20,
    val verifyRetryInterval: Duration = Duration.ofDays(1),
    val sourceWaitDays: Int = 14,
) {
    init {
        require(model.matches(Regex("[a-z0-9.\\-]{1,100}"))) { "Invalid discovery model name." }
        require(windowDays in 1..30) { "Discovery window must be between 1 and 30 days." }
        require(maxCandidates in 1..30) { "Max candidates per run must be between 1 and 30." }
        require(timeout > Duration.ZERO && timeout <= Duration.ofMinutes(4)) { "Timeout must be > 0s and <= 4m." }
    }
}

2. Extracting groundingMetadata cleanly

GeminiDiscoveryModel separates search() (Google Search tool enabled, no JSON schema) from structure() (JSON Schema enforced, search tool disabled):

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// src/main/kotlin/com/example/server/discovery/application/DiscoveryModel.kt
package com.example.server.discovery.application

import com.google.genai.Client
import com.google.genai.errors.ApiException
import com.google.genai.errors.GenAiIOException
import com.google.genai.types.GenerateContentConfig
import com.google.genai.types.GenerateContentResponse
import com.google.genai.types.GoogleSearch
import com.google.genai.types.Tool
import com.example.server.discovery.JudgmentDiscoveryProperties

data class DiscoveryUsage(
    val promptTokens: Int?,
    val outputTokens: Int?,
    val thoughtTokens: Int?,
    val toolTokens: Int?,
    val totalTokens: Int?
)

/** Source verified by Gemini grounding metadata. Links written in model prose are ignored. */
data class GroundedSource(val url: String, val title: String?, val domain: String?)

data class DiscoverySearchResult(
    val text: String,
    val sources: List<GroundedSource>,
    val queries: List<String>,
    val usage: DiscoveryUsage?
)

data class DiscoveryStructureResult(val json: String, val usage: DiscoveryUsage?)

/** Domain boundary for discovery calls. Unit tests mock this interface. */
interface DiscoveryModel {
    val modelName: String
    fun search(prompt: String): DiscoverySearchResult
    fun structure(prompt: String, schema: Map<String, Any>): DiscoveryStructureResult
}

class DiscoveryModelException(message: String) : RuntimeException(message)

/**
 * Uses the Google GenAI SDK directly because Spring AI 2.0.1 ChatResponse
 * does not preserve groundingMetadata. Attaches GoogleSearch only to search().
 */
class GeminiDiscoveryModel(
    private val client: Client,
    private val properties: JudgmentDiscoveryProperties
) : DiscoveryModel {

    override val modelName: String get() = properties.model

    override fun search(prompt: String): DiscoverySearchResult {
        val config = GenerateContentConfig.builder()
            .tools(Tool.builder().googleSearch(GoogleSearch.builder().build()).build())
            .maxOutputTokens(properties.maxOutputTokens)
            .build()

        val response = call { client.models.generateContent(properties.model, prompt, config) }
        val candidate = response.candidates().orElse(emptyList()).firstOrNull()
            ?: throw DiscoveryModelException("Search response returned no candidates.")

        val text = text(response)
        val metadata = candidate.groundingMetadata().orElse(null)

        // Extract only web chunks verified by Google Search
        val sources = metadata?.groundingChunks()?.orElse(emptyList()).orEmpty().mapNotNull { chunk ->
            val web = chunk.web().orElse(null) ?: return@mapNotNull null
            val url = web.uri().orElse(null)?.takeIf { it.startsWith("https://") || it.startsWith("http://") }
                ?: return@mapNotNull null
            GroundedSource(url, web.title().orElse(null), web.domain().orElse(null))
        }

        val queries = metadata?.webSearchQueries()?.orElse(emptyList()).orEmpty()
        return DiscoverySearchResult(text, sources, queries, usage(response))
    }

    override fun structure(prompt: String, schema: Map<String, Any>): DiscoveryStructureResult {
        val config = GenerateContentConfig.builder()
            .responseMimeType("application/json")
            .responseJsonSchema(schema)
            .maxOutputTokens(properties.maxOutputTokens)
            .build()

        val response = call { client.models.generateContent(properties.model, prompt, config) }
        return DiscoveryStructureResult(text(response), usage(response))
    }

    private fun call(action: () -> GenerateContentResponse): GenerateContentResponse = try {
        action()
    } catch (e: ApiException) {
        throw DiscoveryModelException("Gemini API call failed: HTTP ${e.code()} ${e.status()}")
    } catch (e: GenAiIOException) {
        if (Thread.currentThread().isInterrupted) throw InterruptedException("Gemini call interrupted.")
        throw DiscoveryModelException("Gemini network call failed.")
    }

    private fun text(response: GenerateContentResponse): String {
        val candidate = response.candidates().orElse(emptyList()).firstOrNull()
        val finish = candidate?.finishReason()?.orElse(null)?.toString()

        // Exclude reasoning parts (thought == true) so only final answer text is returned
        val text = candidate?.content()?.orElse(null)?.parts()?.orElse(emptyList()).orEmpty()
            .filter { it.thought().orElse(false) != true }
            .mapNotNull { it.text().orElse(null) }
            .joinToString("")
            .trim()

        if (finish != null && finish != "STOP") {
            throw DiscoveryModelException("Gemini response finished abnormally: $finish")
        }
        if (text.isEmpty()) {
            throw DiscoveryModelException("Gemini response body is empty.")
        }
        return text
    }

    private fun usage(response: GenerateContentResponse): DiscoveryUsage? =
        response.usageMetadata().orElse(null)?.let {
            DiscoveryUsage(
                promptTokens = it.promptTokenCount().orElse(null),
                outputTokens = it.candidatesTokenCount().orElse(null),
                thoughtTokens = it.thoughtsTokenCount().orElse(null),
                toolTokens = it.toolUsePromptTokenCount().orElse(null),
                totalTokens = it.totalTokenCount().orElse(null)
            )
        }
}

Filter out thought == true parts on Gemini 2.5/3.5: Reasoning-capable Gemini models can include internal thought parts alongside the final output. If you concatenate every part blindly, internal chain-of-thought text leaks into your JSON payload and breaks parsing. Always filter part.thought().orElse(false) != true.


Measured cost, latency, and admin console verification

After switching to the direct SDK two-step pipeline, I tracked token usage, latency, and source verification in production.

Token breakdown and cost

Gemini Flash Lite token usage and per-run cost dashboard Figure 2. Admin discovery dashboard showing prompt, output, thought, and tool tokens tracked separately.

  • Per-batch cost: Roughly $0.00042 per run on gemini-3.5-flash-lite. Running 4 scheduled discovery batches a day stays well under $1 per month.
  • Granular token auditing: Separating thoughtTokens (312) and toolTokens (480) makes it obvious when search queries or reasoning overhead spike.
  • Latency margin: Average search latency measured 1.84s and JSON structuring measured 1.42s—leaving over 98% headroom under the 120s timeout.

Verified source chips in the admin UI

Admin console judgment candidate detail with verified grounding source chips Figure 3. Candidate detail view rendering verified Google Search source chips alongside official precedent serial cross-checks.

Every chip in the admin console links to a URL present in groundingChunks. Reviewers open the original news report, compare it against the official precedent serial number, and import it with one click. To see how I verify those extracted fields against an authoritative public API downstream, check verifying LLM search outputs against public API ground truth.


Takeaways and checklist

  • Verify sources from metadata, never prose: Prompt instructions alone won’t stop fabricated URLs. Read groundingChunks directly and reject candidates with zero verified sources.
  • Hide vendor SDKs behind a domain port: Defining DiscoveryModel keeps com.google.genai.* isolated to one adapter so unit tests stay fast and vendor upgrades stay contained.
  • Split search and structuring calls: Attach GoogleSearch only on the retrieval turn, and run responseJsonSchema on a separate tool-free turn to avoid accidental searches and lower latency.
  • Strip thought parts before parsing: Always filter part.thought == true when reading raw Gemini candidate parts.

References

Google Gen AI Java SDK provides an interface for developers to integrate Google's generative models into their Java applications. - googleapis/java-genai
Ground your model's responses in real-time information from Google Search to improve factual accuracy and provide citations.
The Spring AI project aims to streamline the development of applications that incorporate artificial intelligence functionality without unnecessary complexity.
This post is licensed under CC BY 4.0 by the author.