-
Notifications
You must be signed in to change notification settings - Fork 650
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
Merged
Server Templates #7503
Changes from 9 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
166 changes: 166 additions & 0 deletions
166
firebase-ai/src/main/kotlin/com/google/firebase/ai/TemplateChat.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,166 @@ | ||
| /* | ||
| * 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 android.graphics.Bitmap | ||
| import com.google.firebase.ai.type.Content | ||
| import com.google.firebase.ai.type.GenerateContentResponse | ||
| import com.google.firebase.ai.type.ImagePart | ||
| import com.google.firebase.ai.type.InlineDataPart | ||
| import com.google.firebase.ai.type.InvalidStateException | ||
| import com.google.firebase.ai.type.PublicPreviewAPI | ||
| import com.google.firebase.ai.type.TextPart | ||
| import com.google.firebase.ai.type.content | ||
| import java.util.LinkedList | ||
| import java.util.concurrent.Semaphore | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.onCompletion | ||
| import kotlinx.coroutines.flow.onEach | ||
|
|
||
| /** | ||
| * Representation of a multi-turn interaction with a model. | ||
| * | ||
| * Captures and stores the history of communication in memory, and provides it as context with each | ||
| * new message. | ||
| * | ||
| * **Note:** This object is not thread-safe, and calling [sendMessage] multiple times without | ||
| * waiting for a response will throw an [InvalidStateException]. | ||
| * | ||
| * @param model The model to use for the interaction. | ||
davidmotson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| * @param templateID The template ID for this chat session | ||
| * @property history The previous content from the chat that has been successfully sent and received | ||
| * from the model. This will be provided to the model for each message sent (as context for the | ||
| * discussion). | ||
| */ | ||
| @PublicPreviewAPI | ||
| public class TemplateChat( | ||
davidmotson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| private val model: TemplateGenerativeModel, | ||
| private val templateID: String, | ||
| public val history: MutableList<Content> = ArrayList() | ||
| ) { | ||
| private var lock = Semaphore(1) | ||
|
|
||
| /** | ||
| * Sends a message using the provided [prompt]; automatically providing the existing [history] as | ||
davidmotson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| * context. | ||
| * | ||
| * If successful, the message and response will be added to the [history]. If unsuccessful, | ||
| * [history] will remain unchanged. | ||
| * | ||
| * @param prompt The input that, together with the history, will be given to the model as the | ||
davidmotson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| * prompt. | ||
| * @param inputs the inputs needed to fill in the template ID | ||
davidmotson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| * @throws InvalidStateException if [prompt] is not coming from the 'user' role. | ||
| * @throws InvalidStateException if the [Chat] instance has an active request. | ||
| */ | ||
| public suspend fun sendMessage( | ||
| prompt: Content, | ||
| inputs: Map<String, Any> | ||
| ): GenerateContentResponse { | ||
| prompt.assertComesFromUser() | ||
| attemptLock() | ||
| try { | ||
| val fullPrompt = history + prompt | ||
| val response = model.generateContent(templateID, inputs, fullPrompt) | ||
davidmotson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| history.add(prompt) | ||
| history.add(response.candidates.first().content) | ||
| return response | ||
| } finally { | ||
| lock.release() | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Sends a message using the existing history of this chat as context and the provided [Content] | ||
| * prompt. | ||
| * | ||
| * The response from the model is returned as a stream. | ||
| * | ||
| * If successful, the message and response will be added to the history. If unsuccessful, history | ||
| * will remain unchanged. | ||
| * | ||
| * @param prompt The input that, together with the history, will be given to the model as the | ||
| * prompt. | ||
| * @param inputs the inputs needed to fill in the template ID | ||
| * @throws InvalidStateException if [prompt] is not coming from the 'user' role. | ||
| * @throws InvalidStateException if the [Chat] instance has an active request. | ||
| */ | ||
| public fun sendMessageStream( | ||
| prompt: Content, | ||
| inputs: Map<String, Any> | ||
| ): Flow<GenerateContentResponse> { | ||
| prompt.assertComesFromUser() | ||
| attemptLock() | ||
|
|
||
| val fullPrompt = history + prompt | ||
| val flow = model.generateContentStream(templateID, inputs, fullPrompt) | ||
| val bitmaps = LinkedList<Bitmap>() | ||
davidmotson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| val inlineDataParts = LinkedList<InlineDataPart>() | ||
| val text = StringBuilder() | ||
|
|
||
| /** | ||
| * TODO: revisit when images and inline data are returned. This will cause issues with how | ||
| * things are structured in the response. eg; a text/image/text response will be (incorrectly) | ||
| * represented as image/text | ||
| */ | ||
| return flow | ||
| .onEach { | ||
| for (part in it.candidates.first().content.parts) { | ||
| when (part) { | ||
| is TextPart -> text.append(part.text) | ||
| is ImagePart -> bitmaps.add(part.image) | ||
| is InlineDataPart -> inlineDataParts.add(part) | ||
| } | ||
| } | ||
| } | ||
| .onCompletion { | ||
| lock.release() | ||
| if (it == null) { | ||
| val content = | ||
| content("model") { | ||
| for (bitmap in bitmaps) { | ||
| image(bitmap) | ||
| } | ||
| for (inlineDataPart in inlineDataParts) { | ||
| inlineData(inlineDataPart.inlineData, inlineDataPart.mimeType) | ||
| } | ||
| if (text.isNotBlank()) { | ||
| text(text.toString()) | ||
| } | ||
| } | ||
|
|
||
| history.add(prompt) | ||
| history.add(content) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun Content.assertComesFromUser() { | ||
| if (role !in listOf("user", "function")) { | ||
| throw InvalidStateException("Chat prompts should come from the 'user' or 'function' role.") | ||
| } | ||
| } | ||
|
|
||
| private fun attemptLock() { | ||
| if (!lock.tryAcquire()) { | ||
| throw InvalidStateException( | ||
| "This chat instance currently has an ongoing request, please wait for it to complete " + | ||
| "before sending more messages" | ||
| ) | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
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.