Spring › Spring-AI

Grounding Gemini responses with Google Search in Spring AI

Configure Google Search Grounding in Spring AI 2.0.1 with Gemini, extract citation URLs via the GenAI SDK, and enforce strict anti-hallucination rules.

Grounding Gemini responses with Google Search in Spring AI

Building a custom web crawler and vector database just to feed current exchange rates, legal updates, or tech news into an LLM adds heavy operational overhead. Google Gemini supports Google Search Grounding natively, returning both live web-backed answers and structured citation metadata. This post covers the two ways to wire Search Grounding in Spring AI 2.0.1, why ChatClient drops citation links today, and how to extract full metadata safely with the auto-configured GenAI SDK client.

Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, and gemini-3.5-flash-lite.


How Google Search Grounding works under the hood

When you attach the GoogleSearch tool to a Gemini request, the model decides on its own whether parametric memory is enough or whether it needs fresh web results:

sequenceDiagram
    autonumber
    actor Client as Client
    participant SpringApp as Spring Boot Backend
    participant Gemini as Google Gemini 3.5
    participant GoogleSearch as Google Search Index
    Client->>SpringApp: GET /api/search/grounded
    SpringApp->>Gemini: generateContent(tools: [GoogleSearch])
    Note over Gemini: Detects need for live web info
    Gemini->>GoogleSearch: Server-side search query
    GoogleSearch-->>Gemini: Web snippets and source URLs
    Note over Gemini: Synthesizes answer with sentence citations
    Gemini-->>SpringApp: Answer text + groundingMetadata
    SpringApp->>SpringApp: Map metadata and apply strict policy
    SpringApp-->>Client: 200 OK (GroundedAnswer JSON)

Along with the generated text, Gemini populates three structured fields inside groundingMetadata:

  • Grounding Chunks (groundingChunks): The actual web pages the model relied on, including title, domain, and a Google redirect URI.
  • Grounding Supports (groundingSupports): Sentence-level mappings linking each generated text segment to groundingChunkIndices and confidenceScores.
  • Search Entry Point (searchEntryPoint): Pre-rendered HTML containing Google search suggestion chips required by Google’s display policy.

Search Grounding vs. custom RAG (and when not to use it)

AspectGoogle Search GroundingCustom RAG (Crawler + Vector DB)
Data scopePublic web indexed by GooglePrivate internal docs, DBs, intranets
Infrastructure costZero crawler/index maintenanceCrawler, embedding pipeline, vector store
FreshnessNear real-timeLimited by your sync schedule
Citation granularitySentence-level chunk indices & scoresDepends on your chunking implementation

Don’t use Google Search Grounding for private corporate knowledge bases, PII-sensitive queries (since search queries leave your VPC to Google Search), or deterministic offline workflows that can’t tolerate variable web results and per-search grounding charges.


Project setup and dependencies

All code in this post comes from the search-grounding module in spring-ai-examples.

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

1
2
3
4
5
6
7
8
9
10
11
12
server:
  port: 8089

spring:
  application:
    name: search-grounding
  ai:
    google:
      genai:
        api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY:demo-key}
        chat:
          model: gemini-3.5-flash-lite

Two ways to enable grounding in Spring AI 2.0.1

Before writing service code, you need to know what Spring AI 2.0.1 exposes and what it drops.

Option 1: ChatClient with GoogleGenAiChatOptions

Spring AI’s GoogleGenAiChatOptions builder lets you turn on Google Search Retrieval with two flags:

1
2
3
4
5
6
7
8
9
10
val options = GoogleGenAiChatOptions.builder()
    .googleSearchRetrieval(true)
    .includeServerSideToolInvocations(true)
    .build()

val chatResponse = chatClient.prompt()
    .user("What is today's USD to KRW exchange rate?")
    .options(options)
    .call()
    .chatResponse()

This keeps your code on Spring AI’s standard fluent ChatClient API. Setting includeServerSideToolInvocations(true) also populates AssistantMessage.metadata["serverSideToolInvocations"], so you can confirm whether Google Search actually ran.

The catch: In Spring AI 2.0.1, GoogleGenAiChatModel discards Gemini’s groundingMetadata instead of mapping it onto ChatResponse. You get the grounded text, but you lose the source URLs, executed search queries, sentence-level citations, and searchEntryPoint HTML.

GoogleGenAiChatOptions debug log showing server-side tool invocations Figure 1. Enabling googleSearchRetrieval in GoogleGenAiChatOptions and verifying server-side tool invocation in logs.

CapabilitySpring AI ChatClient (2.0.1)Direct com.google.genai.Client
Live Google Search groundingYesYes
Server-side invocation flagYesYes
Source URLs (groundingChunks)DroppedFull access
Sentence citations & confidenceDroppedFull access
searchEntryPoint HTMLDroppedFull access

Extracting full citation metadata with the GenAI SDK

If your UI needs clickable source links—which is also required to comply with Google’s grounding guidelines—inject the com.google.genai.Client bean that spring-ai-starter-model-google-genai already auto-configures in the Spring context. (I compare this hybrid pattern in more detail in Spring AI vs. Google GenAI SDK for grounding.)

dto/GroundedAnswer.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package io.github.cmsong111.search_grounding.dto

data class GroundedAnswer(
    val answer: String,
    val grounded: Boolean,
    val webSearchQueries: List<String>,
    val sources: List<GroundingSource>,
    val citations: List<Citation>,
    val searchEntryPointHtml: String?
)

data class GroundingSource(
    val index: Int,
    val title: String?,
    val uri: String?,
    val domain: String?
)

data class Citation(
    val text: String,
    val sourceIndices: List<Int>,
    val confidenceScores: List<Double>
)

service/GroundingMetadataMapper.kt

This mapper converts the raw GenerateContentResponse into our API DTO, handling missing Optional fields safely:

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
package io.github.cmsong111.search_grounding.service

import com.google.genai.types.GenerateContentResponse
import io.github.cmsong111.search_grounding.dto.Citation
import io.github.cmsong111.search_grounding.dto.GroundedAnswer
import io.github.cmsong111.search_grounding.dto.GroundingSource

object GroundingMetadataMapper {

    fun toGroundedAnswer(response: GenerateContentResponse): GroundedAnswer {
        val answer = response.text() ?: ""
        val metadata = response.candidates().orElse(emptyList())
            .firstOrNull()
            ?.groundingMetadata()
            ?.orElse(null)
            ?: return GroundedAnswer(answer, false, emptyList(), emptyList(), emptyList(), null)

        val sources = metadata.groundingChunks().orElse(emptyList())
            .mapIndexedNotNull { index, chunk ->
                chunk.web().map { web ->
                    GroundingSource(
                        index = index,
                        title = web.title().orElse(null),
                        uri = web.uri().orElse(null),
                        domain = web.domain().orElse(null)
                    )
                }.orElse(null)
            }

        val citations = metadata.groundingSupports().orElse(emptyList())
            .map { support ->
                Citation(
                    text = support.segment().flatMap { it.text() }.orElse(""),
                    sourceIndices = support.groundingChunkIndices().orElse(emptyList()),
                    confidenceScores = support.confidenceScores().orElse(emptyList())
                )
            }

        return GroundedAnswer(
            answer = answer,
            grounded = sources.isNotEmpty(),
            webSearchQueries = metadata.webSearchQueries().orElse(emptyList()),
            sources = sources,
            citations = citations,
            searchEntryPointHtml = metadata.searchEntryPoint().flatMap { it.renderedContent() }.orElse(null)
        )
    }
}

Enforcing a strict anti-hallucination policy

Even with the GoogleSearch tool attached, Gemini can skip web search and answer from stale training data if it thinks it already knows the answer. For freshness-critical endpoints, I added a strict flag in SearchGroundingService: when strict is enabled and sources is empty, the service suppresses the ungrounded response and returns a clear fallback message instead.

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
package io.github.cmsong111.search_grounding.service

import com.google.genai.Client
import com.google.genai.types.*
import io.github.cmsong111.search_grounding.dto.GroundedAnswer
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service

@Service
class SearchGroundingService(
    private val genAiClient: Client,
    @Value("\${spring.ai.google.genai.chat.model:gemini-3.5-flash-lite}")
    private val model: String
) {

    fun askWithGrounding(question: String, strict: Boolean): GroundedAnswer {
        val config = GenerateContentConfig.builder()
            .systemInstruction(Content.fromParts(Part.fromText(SYSTEM_INSTRUCTION)))
            .tools(Tool.builder().googleSearch(GoogleSearch.builder().build()).build())
            .build()

        val response = genAiClient.models.generateContent(model, question, config)
        val groundedAnswer = GroundingMetadataMapper.toGroundedAnswer(response)

        return applyGroundingPolicy(groundedAnswer, strict)
    }

    companion object {
        private const val SYSTEM_INSTRUCTION =
            "You are an AI assistant that delivers accurate, up-to-date information. Always base your answers on Google Search results."
        const val UNGROUNDED_MESSAGE =
            "No verified search sources were found for this query. Please make your question more specific."

        fun applyGroundingPolicy(answer: GroundedAnswer, strict: Boolean): GroundedAnswer {
            if (!strict || answer.grounded) return answer
            return answer.copy(answer = UNGROUNDED_MESSAGE)
        }
    }
}

Verification and inspecting citation payloads

Run the unit tests (metadata mapping and strict policy) together with the live Gemini Search integration test:

1
./gradlew :search-grounding:test

Console output showing Google Search Grounding unit and integration tests passing Figure 2. Unit and integration tests passing for source mapping, search queries, citation segments, and strict grounding.

Next, query the running endpoint with strict=true and inspect the returned JSON:

1
2
3
curl -s -G "http://localhost:8089/api/search/grounded" \
  --data-urlencode "question=What are the top tech industry headlines this week?" \
  --data-urlencode "strict=true" | jq .

JSON response with Google Search grounding sources and citation confidence scores Figure 3. Grounded JSON response including source URLs, search queries, and per-sentence citation confidence scores.

Each sources[i].uri is a Google redirect URL (https://vertexaisearch.cloud.google.com/grounding-api-redirect/...) that forwards users to the original article or documentation page.


Google branding requirements and production checklist

Google AI Studio’s grounding terms require you to preserve the returned source links without rewriting or stripping them, and to render the searchEntryPointHtml search suggestion chips alongside grounded results in user-facing UIs.

Keep these operational checks in mind before rolling Search Grounding out to production:

  • Use the auto-configured com.google.genai.Client bean whenever your UI needs clickable citations or searchEntryPointHtml, since Spring AI 2.0.1 ChatResponse omits groundingMetadata.
  • Enable a strict fallback check (sources.isEmpty()) on time-sensitive endpoints so ungrounded parametric guesses never slip through.
  • Sanitize or isolate searchEntryPointHtml carefully in your frontend container without altering Google’s required styling or links.
  • Set an explicit HTTP timeout and budget alert—grounded calls add external search latency and separate grounding billing per request.

References

  • Ground your model's responses in real-time information from Google Search to improve factual accuracy and provide citations.

</div>

  • The Google GenAI API allows developers to build generative AI applications using Google’s Gemini models through either the Gemini Developer API or Vertex AI. The Google GenAI API supports multimodal prompts as input and outputs text or code. A multimodal model is capable of processing information from multiple modalities, including images, videos, and text. For example, you can send the model a photo of a plate of cookies and ask it to give you a recipe for those cookies.

</div>

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