[AI] support on-device structured output - #8395
Conversation
📝 PRs merging into main branchOur main branch should always be in a releasable state. If you are working on a larger change, or if you don't want this change to see the light of the day just yet, consider using a feature branch first, and only merge into the main branch when the code complete and ready to be released. |
Generated by 🚫 Danger |
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. |
|
The public api surface has changed for the subproject ai-logic_firebase-ai-ondevice-interop: Please update the api.txt files for the subprojects being affected by this change by running ./gradlew ${subproject}:generateApiTxtFile. Also perform a major/minor bump accordingly. |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces support for structured object generation (generateObject) in the on-device model interop and implementation layers, including updates to the KSP processor to generate ML Kit companion classes and support enum values in the @Guide annotation. Feedback on these changes highlights a type-safety issue in GenerateObjectResponse.kt regarding MutableList invariance, as well as an opportunity to replace unsafe non-null assertions (!!) with idiomatic safe calls in SchemaSymbolProcessorVisitor.kt.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces support for structured object generation on-device by integrating with ML Kit's schema-based generation. It updates the KSP processor to generate companion classes (_MlKitCompanion) for @Generable classes, adds the generateObject API to the on-device interop and implementation layers, and updates GenerateObjectResponse to support lazy-loading and caching of deserialized instances. The review feedback highlights several important improvements: handling nested classes correctly when resolving companion class names, refining the caching logic in GenerateObjectResponse to prevent redundant deserialization of null values, safely escaping enum values using KotlinPoet's %S specifier, and propagating KDoc-based class and property descriptions to the generated companion annotations.
| schemaClass: kotlin.reflect.KClass<T> | ||
| ): com.google.firebase.ai.ondevice.interop.GenerateObjectResponse<T> = | ||
| try { | ||
| val companionClassName = "${schemaClass.java.name}_MlKitCompanion" |
There was a problem hiding this comment.
If schemaClass is a nested class (e.g., Outer.Inner), schemaClass.java.name will be Outer$Inner. However, KSP generates the companion class as a top-level class named Inner_MlKitCompanion in the same package. Using ${schemaClass.java.name}_MlKitCompanion will resolve to Outer$Inner_MlKitCompanion, which does not exist and will cause a runtime IllegalArgumentException. Construct the companion class name using the package name and the simple name of the class to support nested classes correctly.
val packageName = schemaClass.java.name.substringBeforeLast('.', "")
val simpleName = schemaClass.java.simpleName
val companionClassName = if (packageName.isEmpty()) "${simpleName}_MlKitCompanion" else "$packageName.${simpleName}_MlKitCompanion"| public class GenerateObjectResponse<T : Any> | ||
| internal constructor( | ||
| public val response: GenerateContentResponse, | ||
| internal val schema: JsonSchema<T> | ||
| internal val schema: JsonSchema<T>?, | ||
| internal var instances: MutableList<T?>? | ||
| ) { | ||
|
|
||
| internal constructor( |
There was a problem hiding this comment.
Introduce a resolvedIndices set to track which candidate indices have already been resolved. This is necessary to distinguish between an unresolved candidate and a candidate that has been resolved to null (e.g., due to empty text or deserialization failure), preventing redundant deserialization attempts.
| public class GenerateObjectResponse<T : Any> | |
| internal constructor( | |
| public val response: GenerateContentResponse, | |
| internal val schema: JsonSchema<T> | |
| internal val schema: JsonSchema<T>?, | |
| internal var instances: MutableList<T?>? | |
| ) { | |
| internal constructor( | |
| public class GenerateObjectResponse<T : Any> | |
| internal constructor( | |
| public val response: GenerateContentResponse, | |
| internal val schema: JsonSchema<T>?, | |
| internal var instances: MutableList<T?>? | |
| ) { | |
| private val resolvedIndices = HashSet<Int>() | |
| internal constructor( |
| // 1. Fast Path / Cache Hit: Return immediately if already resolved or in memory | ||
| insts?.getOrNull(candidateIndex)?.let { | ||
| return it | ||
| } |
There was a problem hiding this comment.
Check if the candidate index has already been resolved or if we are in on-device mode (where schema is null and instances are pre-populated), and return the cached value directly. This avoids skipping the cache when the resolved value is null.
| // 1. Fast Path / Cache Hit: Return immediately if already resolved or in memory | |
| insts?.getOrNull(candidateIndex)?.let { | |
| return it | |
| } | |
| // 1. Fast Path / Cache Hit: Return immediately if already resolved or in memory | |
| if (insts != null && (schema == null || candidateIndex in resolvedIndices)) { | |
| return insts.getOrNull(candidateIndex) | |
| } |
| if (candidateIndex < currentInstances.size) { | ||
| currentInstances[candidateIndex] = deserialized | ||
| } |
There was a problem hiding this comment.
Mark the candidate index as resolved when saving the deserialized value to the cache.
| if (candidateIndex < currentInstances.size) { | |
| currentInstances[candidateIndex] = deserialized | |
| } | |
| if (candidateIndex < currentInstances.size) { | |
| currentInstances[candidateIndex] = deserialized | |
| resolvedIndices.add(candidateIndex) | |
| } |
| .indent() | ||
| .addStatement("values = listOf(") | ||
| .indent() | ||
| .addStatement(guideValues.enumValues.joinToString { "\"$it\"" }) |
There was a problem hiding this comment.
Using joinToString { "\"$it\"" } to embed raw string values directly into the generated code block can result in invalid Kotlin code if any enum value contains double quotes or other special characters. Use KotlinPoet's %S format specifier to safely escape and format the string values.
| .addStatement(guideValues.enumValues.joinToString { "\"$it\"" }) | |
| .addStatement( | |
| guideValues.enumValues.joinToString { "%S" }, | |
| *guideValues.enumValues.toTypedArray() | |
| ) |
| val packageName = classDeclaration.packageName.asString() | ||
| val companionClassName = "${classDeclaration.simpleName.asString()}_MlKitCompanion" |
There was a problem hiding this comment.
Extract the property KDocs once at the beginning of the function so they can be used as fallbacks for property descriptions in the generated companion class.
| val packageName = classDeclaration.packageName.asString() | |
| val companionClassName = "${classDeclaration.simpleName.asString()}_MlKitCompanion" | |
| val packageName = classDeclaration.packageName.asString() | |
| val companionClassName = "${classDeclaration.simpleName.asString()}_MlKitCompanion" | |
| val propertyDocs = extractPropertyKdocs(classDeclaration.docString ?: "") |
| val generableAnn = | ||
| classDeclaration.annotations.firstOrNull { it.shortName.getShortName() == "Generable" } | ||
| val classDesc = getStringFromAnnotation(generableAnn, "description") |
There was a problem hiding this comment.
Class descriptions documented via KDocs are not propagated to the generated companion class's @Generable annotation. Since ML Kit's on-device structured output engine relies on these annotations on the companion class to build the schema, any KDoc-based class descriptions will be lost on-device. We should fall back to the base KDoc description if the annotation description is missing.
| val generableAnn = | |
| classDeclaration.annotations.firstOrNull { it.shortName.getShortName() == "Generable" } | |
| val classDesc = getStringFromAnnotation(generableAnn, "description") | |
| val generableAnn = | |
| classDeclaration.annotations.firstOrNull { it.shortName.getShortName() == "Generable" } | |
| val classDesc = getStringFromAnnotation(generableAnn, "description") ?: extractBaseKdoc(classDeclaration.docString ?: "") |
| val guideAnn = property.annotations.firstOrNull { it.shortName.getShortName() == "Guide" } | ||
| if (guideAnn != null) { | ||
| val guideValues = | ||
| getGuideValuesFromAnnotation(guideAnn, getStringFromAnnotation(guideAnn, "description")) |
There was a problem hiding this comment.
Use the extracted property KDocs as a fallback description for the @Guide annotation on the companion class property, and ensure the @Guide annotation is generated if a description exists even if the original property lacked a @Guide annotation.
| val guideAnn = property.annotations.firstOrNull { it.shortName.getShortName() == "Guide" } | |
| if (guideAnn != null) { | |
| val guideValues = | |
| getGuideValuesFromAnnotation(guideAnn, getStringFromAnnotation(guideAnn, "description")) | |
| val guideAnn = property.annotations.firstOrNull { it.shortName.getShortName() == "Guide" } | |
| val propDescription = getStringFromAnnotation(guideAnn, "description") ?: propertyDocs[propName] | |
| if (guideAnn != null || !propDescription.isNullOrEmpty()) { | |
| val guideValues = | |
| getGuideValuesFromAnnotation(guideAnn, propDescription) |
This PR introduces Structured Output support on device, allowing developers to generate strongly-typed objects using ML Kit's backend. It defines the public API (GenerateObjectResponse and generateObject()), handles the necessary Kotlin Symbol Processing (KSP) logic for schema translation.
How to use On-Device Structured Output