-
Notifications
You must be signed in to change notification settings - Fork 685
[ALF] Add index adjustment for UTF-8 indices #8056
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
bd55c3b
2847898
3645af7
5d0e072
9b2abc0
c9b8811
3047aa6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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 | ||
| val part = candidate.content.parts[segment.partIndex] | ||
| part::class shouldBe TextPart::class | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. shouldBeInstanceOf ? https://kotest.io/docs/assertions/core-matchers.html |
||
| val text = (part as TextPart).text | ||
| segment.startIndex shouldBeGreaterThanOrEqual 0 | ||
| segment.startIndex shouldBeLessThanOrEqual segment.endIndex | ||
|
Comment on lines
+59
to
+60
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. shouldBeBetween ? https://kotest.io/docs/assertions/core-matchers.html |
||
| segment.endIndex shouldBeLessThanOrEqual text.length | ||
| segment.text shouldBe text.substring(segment.startIndex, segment.endIndex) | ||
| } | ||
|
|
||
| fun validateContent(content: Content) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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, | ||
|
|
@@ -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) }) | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -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() | ||
|
|
@@ -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 | ||
|
|
@@ -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() | ||
| ) | ||
| } | ||
| } | ||
|
|
@@ -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(), | ||
| ) | ||
| } | ||
|
|
@@ -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) | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -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( | ||
|
|
@@ -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 ?: "" | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -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 { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Char has methods like
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think using the ones in |
||
| 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" | ||
| ) | ||
| } | ||
|
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 | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
same as below