-
Notifications
You must be signed in to change notification settings - Fork 678
[AI] Add TemplateChat for multi-turn template interactions #7986
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
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
122 changes: 122 additions & 0 deletions
122
ai-logic/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,122 @@ | ||
| /* | ||
| * 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.Content | ||
| import com.google.firebase.ai.type.GenerateContentResponse | ||
| import com.google.firebase.ai.type.InvalidStateException | ||
| import com.google.firebase.ai.type.Part | ||
| import com.google.firebase.ai.type.PublicPreviewAPI | ||
| import com.google.firebase.ai.type.content | ||
| 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 server template model. */ | ||
| @PublicPreviewAPI | ||
| public class TemplateChat | ||
| internal constructor( | ||
| private val model: TemplateGenerativeModel, | ||
| private val templateId: String, | ||
| private val inputs: Map<String, Any>, | ||
| public val history: MutableList<Content> = ArrayList() | ||
| ) { | ||
| private var lock = Semaphore(1) | ||
|
|
||
| /** | ||
| * Sends a message using the provided [prompt]; automatically providing the existing [history] as | ||
| * context. | ||
| * | ||
| * @param prompt The input that, together with the history, will be given to the model as the | ||
| * prompt. | ||
| */ | ||
| public suspend fun sendMessage(prompt: Content): GenerateContentResponse { | ||
| prompt.assertComesFromUser() | ||
| attemptLock() | ||
| try { | ||
| return model.generateContentWithHistory(templateId, inputs, history + prompt).also { resp -> | ||
| history.add(prompt) | ||
| history.add(resp.candidates.first().content) | ||
| } | ||
| } finally { | ||
| lock.release() | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Sends a message using the provided text [prompt]; automatically providing the existing | ||
| * [history] as context. | ||
| */ | ||
| public suspend fun sendMessage(prompt: String): GenerateContentResponse { | ||
| val content = content { text(prompt) } | ||
| return sendMessage(content) | ||
| } | ||
|
|
||
| /** | ||
| * Sends a message using the provided [prompt]; automatically providing the existing [history] as | ||
| * context. Returns a flow. | ||
| */ | ||
| public fun sendMessageStream(prompt: Content): Flow<GenerateContentResponse> { | ||
| prompt.assertComesFromUser() | ||
| attemptLock() | ||
|
|
||
| val fullPrompt = history + prompt | ||
| val flow = model.generateContentWithHistoryStream(templateId, inputs, fullPrompt) | ||
| val tempHistory = mutableListOf<Content>() | ||
| val responseParts = mutableListOf<Part>() | ||
|
|
||
| return flow | ||
| .onEach { response -> | ||
| response.candidates.first().content.parts.let { responseParts.addAll(it) } | ||
| } | ||
| .onCompletion { | ||
| lock.release() | ||
| if (it == null) { | ||
| tempHistory.add(prompt) | ||
| tempHistory.add( | ||
| content("model") { responseParts.forEach { part -> this.parts.add(part) } } | ||
| ) | ||
| history.addAll(tempHistory) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Sends a message using the provided text [prompt]; automatically providing the existing | ||
| * [history] as context. Returns a flow. | ||
| */ | ||
| public fun sendMessageStream(prompt: String): Flow<GenerateContentResponse> { | ||
| val content = content { text(prompt) } | ||
| return sendMessageStream(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" | ||
| ) | ||
| } | ||
| } | ||
| } | ||
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
108 changes: 108 additions & 0 deletions
108
ai-logic/firebase-ai/src/test/java/com/google/firebase/ai/TemplateChatTests.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,108 @@ | ||
| /* | ||
| * 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.Content | ||
| import com.google.firebase.ai.type.FinishReason | ||
| import com.google.firebase.ai.type.GenerateContentResponse | ||
| import com.google.firebase.ai.type.Part | ||
| import com.google.firebase.ai.type.PublicPreviewAPI | ||
| import com.google.firebase.ai.type.TextPart | ||
| import com.google.firebase.ai.type.content | ||
| import io.kotest.matchers.collections.shouldHaveSize | ||
| import io.kotest.matchers.shouldBe | ||
| import io.kotest.matchers.types.shouldBeInstanceOf | ||
| import io.mockk.coEvery | ||
| import io.mockk.every | ||
| import io.mockk.mockk | ||
| import kotlinx.coroutines.flow.flowOf | ||
| import kotlinx.coroutines.flow.toList | ||
| import kotlinx.coroutines.test.runTest | ||
| import org.junit.Before | ||
| import org.junit.Test | ||
| import org.junit.runner.RunWith | ||
| import org.robolectric.RobolectricTestRunner | ||
|
|
||
| @OptIn(PublicPreviewAPI::class) | ||
| @RunWith(RobolectricTestRunner::class) | ||
| class TemplateChatTests { | ||
| private val model = mockk<TemplateGenerativeModel>() | ||
| private val templateId = "test-template" | ||
| private val inputs = mapOf("key" to "value") | ||
|
|
||
| private lateinit var chat: TemplateChat | ||
|
|
||
| @Before | ||
| fun setup() { | ||
| chat = TemplateChat(model, templateId, inputs) | ||
| } | ||
|
|
||
| @Test | ||
| fun `sendMessage(Content) adds prompt and response to history`() = runTest { | ||
| val prompt = content("user") { text("hello") } | ||
| val responseContent = content("model") { text("hi") } | ||
| val response = createResponse(responseContent) | ||
|
|
||
| coEvery { model.generateContentWithHistory(templateId, inputs, any()) } returns response | ||
|
|
||
| chat.sendMessage(prompt) | ||
|
|
||
| chat.history shouldHaveSize 2 | ||
| chat.history[0] shouldBeEquivalentTo prompt | ||
| chat.history[1] shouldBeEquivalentTo responseContent | ||
| } | ||
|
|
||
| @Test | ||
| fun `sendMessageStream(Content) adds prompt and aggregated responses to history`() = runTest { | ||
| val prompt = content("user") { text("hello") } | ||
| val response1 = createResponse(content("model") { text("hi ") }) | ||
| val response2 = createResponse(content("model") { text("there") }) | ||
|
|
||
| every { model.generateContentWithHistoryStream(templateId, inputs, any()) } returns | ||
| flowOf(response1, response2) | ||
|
|
||
| val flow = chat.sendMessageStream(prompt) | ||
| flow.toList() | ||
|
|
||
| chat.history shouldHaveSize 2 | ||
| chat.history[0] shouldBeEquivalentTo prompt | ||
| chat.history[1].parts shouldHaveSize 2 | ||
| chat.history[1].parts[0].shouldBeInstanceOf<TextPart>().text shouldBe "hi " | ||
| chat.history[1].parts[1].shouldBeInstanceOf<TextPart>().text shouldBe "there" | ||
| } | ||
|
|
||
| private fun createResponse(content: Content): GenerateContentResponse { | ||
| return GenerateContentResponse.Internal( | ||
| listOf(Candidate.Internal(content.toInternal(), finishReason = FinishReason.Internal.STOP)) | ||
| ) | ||
| .toPublic() | ||
| } | ||
|
|
||
| private infix fun Content.shouldBeEquivalentTo(other: Content) { | ||
| this.role shouldBe other.role | ||
| this.parts shouldHaveSize other.parts.size | ||
| this.parts.zip(other.parts).forEach { (a, b) -> a.shouldBeEquivalentTo(b) } | ||
| } | ||
|
|
||
| private fun Part.shouldBeEquivalentTo(other: Part) { | ||
| this::class shouldBe other::class | ||
| if (this is TextPart && other is TextPart) { | ||
| this.text shouldBe other.text | ||
| } | ||
| } | ||
| } |
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.