- 
                Notifications
    You must be signed in to change notification settings 
- Fork 647
Server Templates #7503
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
          
     Merged
      
      
    
      
        
          +628
        
        
          −11
        
        
          
        
      
    
  
  
     Merged
                    Server Templates #7503
Changes from all commits
      Commits
    
    
            Show all changes
          
          
            14 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      ec8a8c2
              
                Server Templates
              
              
                 8a9e2e9
              
                add publicpreviewapi annotations and clean up code
              
              
                 a367826
              
                add java types
              
              
                 60f580b
              
                add missing template imagen model futures entry point
              
              
                 1c89819
              
                fixes for comments
              
              
                 7645acf
              
                fix serialization
              
              
                 6c4050c
              
                Merge branch 'main' into davidmotson.prompt_templates
              
              
                davidmotson f761374
              
                add TemplateChat and TemplateChatFutures
              
              
                 a105587
              
                fix for issue with thought in parts sent as history for template chat
              
              
                 b9e3c88
              
                remove template chat
              
              
                 d8ec7cc
              
                fixes for comments
              
              
                 aa8949c
              
                add serialization tests
              
              
                 e63f756
              
                format
              
              
                 ef90dce
              
                remove history param from TemplateGenerativeModel
              
              
                 File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              
        
          
          
            141 changes: 141 additions & 0 deletions
          
          141 
        
  firebase-ai/src/main/kotlin/com/google/firebase/ai/TemplateGenerativeModel.kt
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| /* | ||
| * Copyright 2025 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.FirebaseApp | ||
| import com.google.firebase.ai.common.APIController | ||
| import com.google.firebase.ai.common.AppCheckHeaderProvider | ||
| import com.google.firebase.ai.common.TemplateGenerateContentRequest | ||
| import com.google.firebase.ai.type.Content | ||
| import com.google.firebase.ai.type.FinishReason | ||
| import com.google.firebase.ai.type.FirebaseAIException | ||
| import com.google.firebase.ai.type.GenerateContentResponse | ||
| import com.google.firebase.ai.type.PromptBlockedException | ||
| import com.google.firebase.ai.type.PublicPreviewAPI | ||
| import com.google.firebase.ai.type.RequestOptions | ||
| import com.google.firebase.ai.type.ResponseStoppedException | ||
| import com.google.firebase.ai.type.SerializationException | ||
| import com.google.firebase.appcheck.interop.InteropAppCheckTokenProvider | ||
| import com.google.firebase.auth.internal.InternalAuthProvider | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.catch | ||
| import kotlinx.coroutines.flow.map | ||
| import kotlinx.serialization.json.Json | ||
| import kotlinx.serialization.json.jsonObject | ||
| import org.json.JSONObject | ||
|  | ||
| /** | ||
| * Represents a multimodal model (like Gemini), capable of generating content based on various | ||
| * templated input types. | ||
| */ | ||
| @PublicPreviewAPI | ||
| public class TemplateGenerativeModel | ||
|         
                  davidmotson marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| internal constructor( | ||
| private val templateUri: String, | ||
| private val controller: APIController, | ||
| ) { | ||
|  | ||
| internal constructor( | ||
| templateUri: String, | ||
| apiKey: String, | ||
| firebaseApp: FirebaseApp, | ||
| useLimitedUseAppCheckTokens: Boolean, | ||
| requestOptions: RequestOptions = RequestOptions(), | ||
| appCheckTokenProvider: InteropAppCheckTokenProvider? = null, | ||
| internalAuthProvider: InternalAuthProvider? = null | ||
| ) : this( | ||
| templateUri, | ||
| APIController( | ||
| apiKey, | ||
| "", | ||
| requestOptions, | ||
| "gl-kotlin/${KotlinVersion.CURRENT}-ai fire/${BuildConfig.VERSION_NAME}", | ||
| firebaseApp, | ||
| AppCheckHeaderProvider( | ||
| TAG, | ||
| useLimitedUseAppCheckTokens, | ||
| appCheckTokenProvider, | ||
| internalAuthProvider | ||
| ), | ||
| ), | ||
| ) | ||
|  | ||
| /** | ||
| * Generates content from a prompt template and inputs. | ||
| * | ||
| * @param templateId The ID of the prompt template to use. | ||
| * @param inputs A map of variables to substitute into the template. | ||
| * @return The content generated by the model. | ||
| * @throws [FirebaseAIException] if the request failed. | ||
| * @see [FirebaseAIException] for types of errors. | ||
| */ | ||
| public suspend fun generateContent( | ||
| templateId: String, | ||
| inputs: Map<String, Any>, | ||
| ): GenerateContentResponse = | ||
| try { | ||
| controller | ||
| .templateGenerateContent("$templateUri$templateId", constructRequest(inputs)) | ||
| .toPublic() | ||
| .validate() | ||
| } catch (e: Throwable) { | ||
| throw FirebaseAIException.from(e) | ||
| } | ||
|  | ||
| /** | ||
| * Generates content as a stream from a prompt template and inputs. | ||
| * | ||
| * @param templateId The ID of the prompt template to use. | ||
| * @param inputs A map of variables to substitute into the template. | ||
| * @return A [Flow] which will emit responses as they are returned by the model. | ||
| * @throws [FirebaseAIException] if the request failed. | ||
| * @see [FirebaseAIException] for types of errors. | ||
| */ | ||
| public fun generateContentStream( | ||
| templateId: String, | ||
| inputs: Map<String, Any> | ||
| ): Flow<GenerateContentResponse> = | ||
| controller | ||
| .templateGenerateContentStream("$templateUri$templateId", constructRequest(inputs)) | ||
| .catch { throw FirebaseAIException.from(it) } | ||
| .map { it.toPublic().validate() } | ||
|  | ||
| internal fun constructRequest( | ||
| inputs: Map<String, Any>, | ||
| history: List<Content>? = null | ||
| ): TemplateGenerateContentRequest { | ||
| return TemplateGenerateContentRequest( | ||
| Json.parseToJsonElement(JSONObject(inputs).toString()).jsonObject, | ||
| history?.let { it.map { it.toTemplateInternal() } } | ||
| ) | ||
| } | ||
|  | ||
| private fun GenerateContentResponse.validate() = apply { | ||
| if (candidates.isEmpty() && promptFeedback == null) { | ||
| throw SerializationException("Error deserializing response, found no valid fields") | ||
| } | ||
| promptFeedback?.blockReason?.let { throw PromptBlockedException(this) } | ||
| candidates | ||
| .mapNotNull { it.finishReason } | ||
| .firstOrNull { it != FinishReason.STOP } | ||
| ?.let { throw ResponseStoppedException(this) } | ||
| } | ||
|  | ||
| private companion object { | ||
| private val TAG = TemplateGenerativeModel::class.java.simpleName | ||
| } | ||
| } | ||
        
          
          
            106 changes: 106 additions & 0 deletions
          
          106 
        
  firebase-ai/src/main/kotlin/com/google/firebase/ai/TemplateImagenModel.kt
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| /* | ||
| * Copyright 2025 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.FirebaseApp | ||
| import com.google.firebase.ai.common.APIController | ||
| import com.google.firebase.ai.common.AppCheckHeaderProvider | ||
| import com.google.firebase.ai.common.TemplateGenerateImageRequest | ||
| import com.google.firebase.ai.type.FirebaseAIException | ||
| import com.google.firebase.ai.type.ImagenGenerationResponse | ||
| import com.google.firebase.ai.type.ImagenInlineImage | ||
| import com.google.firebase.ai.type.PublicPreviewAPI | ||
| import com.google.firebase.ai.type.RequestOptions | ||
| import com.google.firebase.appcheck.interop.InteropAppCheckTokenProvider | ||
| import com.google.firebase.auth.internal.InternalAuthProvider | ||
| import kotlinx.serialization.json.Json | ||
| import kotlinx.serialization.json.jsonObject | ||
| import org.json.JSONObject | ||
|  | ||
| /** | ||
| * Represents a generative model (like Imagen), capable of generating images based a template. | ||
| * | ||
| * See the documentation for a list of | ||
| * [supported models](https://firebase.google.com/docs/ai-logic/models). | ||
| */ | ||
| @PublicPreviewAPI | ||
| public class TemplateImagenModel | ||
|         
                  davidmotson marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| internal constructor( | ||
| private val templateUri: String, | ||
| private val controller: APIController, | ||
| ) { | ||
|  | ||
| @JvmOverloads | ||
| internal constructor( | ||
| templateUri: String, | ||
| apiKey: String, | ||
| firebaseApp: FirebaseApp, | ||
| useLimitedUseAppCheckTokens: Boolean, | ||
| requestOptions: RequestOptions = RequestOptions(), | ||
| appCheckTokenProvider: InteropAppCheckTokenProvider? = null, | ||
| internalAuthProvider: InternalAuthProvider? = null, | ||
| ) : this( | ||
| templateUri, | ||
| APIController( | ||
| apiKey, | ||
| "", | ||
| requestOptions, | ||
| "gl-kotlin/${KotlinVersion.CURRENT}-ai fire/${BuildConfig.VERSION_NAME}", | ||
| firebaseApp, | ||
| AppCheckHeaderProvider( | ||
| TAG, | ||
| useLimitedUseAppCheckTokens, | ||
| appCheckTokenProvider, | ||
| internalAuthProvider | ||
| ), | ||
| ), | ||
| ) | ||
|         
                  davidmotson marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
|  | ||
| /** | ||
| * Generates an image, returning the result directly to the caller. | ||
| * | ||
| * @param templateId The ID of server prompt template. | ||
| * @param inputs the inputs needed to fill in the prompt | ||
| */ | ||
| public suspend fun generateImages( | ||
| templateId: String, | ||
| inputs: Map<String, Any> | ||
|         
                  davidmotson marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| ): ImagenGenerationResponse<ImagenInlineImage> = | ||
| try { | ||
| controller | ||
| .templateGenerateImage( | ||
| "$templateUri$templateId", | ||
| constructTemplateGenerateImageRequest(inputs) | ||
| ) | ||
| .validate() | ||
| .toPublicInline() | ||
| } catch (e: Throwable) { | ||
| throw FirebaseAIException.from(e) | ||
| } | ||
|  | ||
| private fun constructTemplateGenerateImageRequest( | ||
| inputs: Map<String, Any> | ||
| ): TemplateGenerateImageRequest { | ||
| return TemplateGenerateImageRequest( | ||
| Json.parseToJsonElement(JSONObject(inputs).toString()).jsonObject | ||
| ) | ||
| } | ||
|  | ||
| internal companion object { | ||
| private val TAG = TemplateImagenModel::class.java.simpleName | ||
| } | ||
| } | ||
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.