Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ai-logic/firebase-ai/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Unreleased

- [fixed] Fixed citation indices to be native UTF-16 instead of UTF-8. (#8056)

- [feature] Added support for [Maps Grounding](https://ai.google.dev/gemini-api/docs/maps-grounding) (#7950)

- [feature] Added support for `ImageConfig` and `finishMessage`. (#8020)

- [feature] Added a Java-friendly wrapper for TemplateChat interactions (`TemplateChatFutures`).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ import kotlinx.coroutines.runBlocking
import org.junit.Test

class GroundingTests {
private val validator = TypesValidator()

@Test
fun groundingTests_canRecognizeAreas(): Unit = runBlocking {
val model = setupModel(config = ToolConfig())
val response = model.generateContent("Where is a good place to grab a coffee near Alameda, CA?")
validator.validateResponse(response)

response.candidates.isEmpty() shouldBe false
response.candidates[0].groundingMetadata?.groundingChunks?.any { it.maps != null } shouldBe true
Expand All @@ -51,11 +53,27 @@ class GroundingTests {
)
)
val response = model.generateContent("Find bookstores in my area.")
validator.validateResponse(response)

response.candidates.isEmpty() shouldBe false
response.candidates[0].groundingMetadata?.groundingChunks?.any { it.maps != null } shouldBe true
}

@Test
fun groundingTests_canSearchWeather(): Unit = runBlocking {
val model =
FirebaseAI.getInstance(app(), GenerativeBackend.vertexAI())
.generativeModel(
modelName = "gemini-2.5-flash",
tools = listOf(Tool.googleSearch()),
)
val response = model.generateContent("What temperature is it today in Cancún?")
// Grounding indices should be correct
validator.validateResponse(response)
// Search grounding should be used
response.candidates.any { it.groundingMetadata != null } shouldBe true
}

companion object {

@JvmStatic
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ package com.google.firebase.ai
import com.google.firebase.ai.type.Candidate
import com.google.firebase.ai.type.Content
import com.google.firebase.ai.type.GenerateContentResponse
import com.google.firebase.ai.type.GroundingSupport
import com.google.firebase.ai.type.TextPart
import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual
import io.kotest.matchers.ints.shouldBeLessThan
import io.kotest.matchers.ints.shouldBeLessThanOrEqual
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
Expand All @@ -38,6 +42,24 @@ class TypesValidator {

fun validateCandidate(candidate: Candidate) {
validateContent(candidate.content)
if (candidate.groundingMetadata != null) {
for (grounding in candidate.groundingMetadata.groundingSupports) {
validateGroundingSupport(candidate, grounding)
}
}
}

fun validateGroundingSupport(candidate: Candidate, grounding: GroundingSupport) {
val segment = grounding.segment
segment.partIndex shouldBeGreaterThanOrEqual 0
segment.partIndex shouldBeLessThan candidate.content.parts.size
Comment on lines +54 to +55
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as below

val part = candidate.content.parts[segment.partIndex]
part::class shouldBe TextPart::class
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

val text = (part as TextPart).text
segment.startIndex shouldBeGreaterThanOrEqual 0
segment.startIndex shouldBeLessThanOrEqual segment.endIndex
Comment on lines +59 to +60
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

segment.endIndex shouldBeLessThanOrEqual text.length
segment.text shouldBe text.substring(segment.startIndex, segment.endIndex)
}

fun validateContent(content: Content) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,15 @@ internal constructor(

@OptIn(PublicPreviewAPI::class)
internal fun toPublic(): Candidate {
val content = this.content?.toPublic() ?: content("model") {}
val safetyRatings = safetyRatings?.mapNotNull { it.toPublic() }.orEmpty()
val citations = citationMetadata?.toPublic()
val citations = citationMetadata?.toPublic(content)
val finishReason = finishReason?.toPublic()
val groundingMetadata = groundingMetadata?.toPublic()
val groundingMetadata = groundingMetadata?.toPublic(content)
val urlContextMetadata = urlContextMetadata?.toPublic()

return Candidate(
this.content?.toPublic() ?: content("model") {},
content,
safetyRatings,
citations,
finishReason,
Expand Down Expand Up @@ -169,7 +170,8 @@ public class CitationMetadata internal constructor(public val citations: List<Ci
@OptIn(ExperimentalSerializationApi::class)
internal constructor(@JsonNames("citations") val citationSources: List<Citation.Internal>) {

internal fun toPublic() = CitationMetadata(citationSources.map { it.toPublic() })
internal fun toPublic(content: Content) =
CitationMetadata(citationSources.map { it.toPublic(content) })
}
}

Expand Down Expand Up @@ -209,7 +211,7 @@ internal constructor(
val publicationDate: Date? = null,
) {

internal fun toPublic(): Citation {
internal fun toPublic(content: Content): Citation {
val publicationDateAsCalendar =
publicationDate?.let {
val calendar = Calendar.getInstance()
Expand All @@ -226,8 +228,8 @@ internal constructor(
}
return Citation(
title = title,
startIndex = startIndex,
endIndex = endIndex,
startIndex = convertUtf8IndexToUtf16(content, startIndex),
endIndex = convertUtf8IndexToUtf16(content, endIndex),
uri = uri,
license = license,
publicationDate = publicationDateAsCalendar
Expand Down Expand Up @@ -431,14 +433,15 @@ public class GroundingMetadata(
val groundingChunks: List<GroundingChunk.Internal>?,
val groundingSupports: List<GroundingSupport.Internal>?,
) {
internal fun toPublic() =
internal fun toPublic(content: Content) =
GroundingMetadata(
webSearchQueries = webSearchQueries.orEmpty(),
searchEntryPoint = searchEntryPoint?.toPublic(),
retrievalQueries = retrievalQueries.orEmpty(),
groundingAttribution = groundingAttribution?.map { it.toPublic() }.orEmpty(),
groundingAttribution = groundingAttribution?.map { it.toPublic(content) }.orEmpty(),
groundingChunks = groundingChunks?.map { it.toPublic() }.orEmpty(),
groundingSupports = groundingSupports?.map { it.toPublic() }.orEmpty().filterNotNull()
groundingSupports =
groundingSupports?.map { it.toPublic(content) }.orEmpty().filterNotNull()
)
}
}
Expand Down Expand Up @@ -551,12 +554,12 @@ public class GroundingSupport(
val segment: Segment.Internal?,
val groundingChunkIndices: List<Int>?,
) {
internal fun toPublic(): GroundingSupport? {
internal fun toPublic(content: Content): GroundingSupport? {
if (segment == null) {
return null
}
return GroundingSupport(
segment = segment.toPublic(),
segment = segment.toPublic(content),
groundingChunkIndices = groundingChunkIndices.orEmpty(),
)
}
Expand All @@ -574,8 +577,8 @@ public class GroundingAttribution(
val segment: Segment.Internal,
val confidenceScore: Float?,
) {
internal fun toPublic() =
GroundingAttribution(segment = segment.toPublic(), confidenceScore = confidenceScore)
internal fun toPublic(content: Content) =
GroundingAttribution(segment = segment.toPublic(content), confidenceScore = confidenceScore)
}
}

Expand All @@ -586,11 +589,11 @@ public class GroundingAttribution(
* @property partIndex The zero-based index of the [Part] object within the `parts` array of its
* parent [Content] object. This identifies which part of the content the segment belongs to.
* @property startIndex The zero-based start index of the segment within the specified [Part],
* measured in UTF-8 bytes. This offset is inclusive, starting from 0 at the beginning of the part's
* content.
* measured in UTF-16 characters. This offset is inclusive, starting from 0 at the beginning of the
* part's content.
* @property endIndex The zero-based end index of the segment within the specified [Part], measured
* in UTF-8 bytes. This offset is exclusive, meaning the character at this index is not included in
* the segment.
* in UTF-16 characters. This offset is exclusive, meaning the character at this index is not
* included in the segment.
* @property text The text corresponding to the segment from the response.
*/
public class Segment(
Expand All @@ -606,13 +609,17 @@ public class Segment(
val partIndex: Int?,
val text: String?,
) {
internal fun toPublic() =
Segment(
startIndex = startIndex ?: 0,
endIndex = endIndex ?: 0,
partIndex = partIndex ?: 0,
internal fun toPublic(content: Content): Segment {
val partIndex = this.partIndex ?: 0
val part = content.parts.getOrNull(partIndex)
val fakeContent = Content(content.role, if (part == null) emptyList() else listOf(part))
return Segment(
startIndex = convertUtf8IndexToUtf16(fakeContent, startIndex ?: 0),
endIndex = convertUtf8IndexToUtf16(fakeContent, endIndex ?: 0),
partIndex = partIndex,
text = text ?: ""
)
}
}
}

Expand Down Expand Up @@ -695,3 +702,36 @@ private constructor(public val name: String, public val ordinal: Int) {
@JvmField public val UNSAFE: UrlRetrievalStatus = UrlRetrievalStatus("UNSAFE", 4)
}
}

internal fun convertUtf8IndexToUtf16(content: Content, originalIndex: Int): Int {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a comment to help understand the logic below

if (originalIndex == 0) {
return 0
}
var sumIndex = 0
var progress = 0
for (part in content.parts) {
val text = part.asTextOrNull() ?: ""
var i = 0
while (i < text.length) {
val c = text[i].code
progress +=
when {
c < 0x80 -> 1 // ASCII
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch, we should be able to use them for some cases, but at a quick glance there's not methods for all of these cases, would you prefer we mix and match direct checking and method usage or remain consistent?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think using the ones in Char and adding our own as extension functions can help with clarity. Without some decent understanding of encoding it's not easy to follow the code (IMO).

c < 0x800 -> 2 // Two-byte codepoint
c in 0xD800..0xDBFF -> 4 // High surrogate character
else -> 3
}
if (c in 0xD800..0xDBFF && i + 1 < text.length) {
i++ // Skip the low surrogate
}
i++
if (progress >= originalIndex) {
return sumIndex + i
}
}
sumIndex += text.length
}
throw StringIndexOutOfBoundsException(
"Desired index $originalIndex is higher than content size $progress"
)
}
Comment thread
emilypgoogle marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.firebase.ai

import com.google.firebase.ai.type.Candidate
import com.google.firebase.ai.type.Citation
import com.google.firebase.ai.type.CitationMetadata
import com.google.firebase.ai.type.Content
import com.google.firebase.ai.type.PublicPreviewAPI
import com.google.firebase.ai.type.TextPart
import com.google.firebase.ai.type.content
import com.google.firebase.ai.type.convertUtf8IndexToUtf16
import io.kotest.matchers.shouldBe
import kotlinx.serialization.ExperimentalSerializationApi
import org.junit.Test

@OptIn(PublicPreviewAPI::class, ExperimentalSerializationApi::class)
class EncodingTests {
val testStrings =
listOf(
"hello world",
"¡Sí! Tengo muchos años.",
"🙂🤝📩",
"速度を上げて",
"",
)

@Test
fun `UTF-8 to UFT-16 index mapping matches length`() {
for (string in testStrings) {
val content = content { text(string) }
val ba = string.toByteArray(Charsets.UTF_8)
val index = convertUtf8IndexToUtf16(content, ba.size)
index shouldBe string.length
}
}

@Test
fun `CitationMetadata gets converted to UTF-16`() {
val internalCandidate =
Candidate.Internal(
content = Content.Internal("", listOf(TextPart.Internal("í abc í"))),
citationMetadata =
CitationMetadata.Internal(
listOf(
Citation.Internal(
startIndex = 3,
endIndex = 6,
)
)
)
)
val candidate = internalCandidate.toPublic()
val start = candidate.citationMetadata!!.citations.first().startIndex
val end = candidate.citationMetadata.citations.first().endIndex
(candidate.content.parts.first() as TextPart).text.substring(start, end) shouldBe "abc"
start shouldBe 2
end shouldBe 5
}
}
Loading