-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[FirebaseAI] Implicit caching support #14944
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
8 commits
Select commit
Hold shift + click to select a range
3628cc5
[FirebaseAI] Implicit caching support
paulb777 a02ee27
style
paulb777 5dc8c1e
Updates and testing
paulb777 2d4f331
Apply suggestions from code review
paulb777 679697a
review
paulb777 9dfb304
Better docs
paulb777 086fd6c
Add vertexai testing
paulb777 7130994
Merge branch 'main' into pb-implicit-cache
paulb777 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
93 changes: 93 additions & 0 deletions
93
FirebaseAI/Tests/TestApp/Tests/Integration/ImplicitCacheTests.swift
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,93 @@ | ||
| // 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. | ||
|
|
||
| import FirebaseAILogic | ||
| import FirebaseAITestApp | ||
| import Foundation | ||
| import Testing | ||
|
|
||
| @Suite(.serialized) | ||
| struct ImplicitCacheTests { | ||
| // A large repeating string to exceed the 1024 token threshold for implicit caching. | ||
| // 500 repetitions of ~68 chars = ~34000 chars, which is > 1024 tokens. | ||
| let largeContext = String( | ||
| repeating: "This is a repeating sentence to generate enough tokens for implicit caching. ", | ||
| count: 500 | ||
| ) | ||
|
|
||
| @Test(arguments: [ | ||
| (InstanceConfig.vertexAI_v1beta, ModelNames.gemini2_5_Flash), | ||
| (InstanceConfig.googleAI_v1beta, ModelNames.gemini2_5_Flash), | ||
| (InstanceConfig.googleAI_v1beta, ModelNames.gemini2_5_Pro), | ||
| (InstanceConfig.googleAI_v1beta, ModelNames.gemini3FlashPreview), | ||
| ]) | ||
| func implicitCaching(_ config: InstanceConfig, modelName: String) async throws { | ||
| let model = FirebaseAI.componentInstance(config).generativeModel( | ||
| modelName: modelName | ||
| ) | ||
|
|
||
| // First request: establish the cache (if implicit caching works) | ||
| let prompt1 = largeContext + "\nQuestion 1: What is the first word of this text?" | ||
| let response1 = try await model.generateContent(prompt1) | ||
| let text1 = try #require(response1.text) | ||
| #expect(!text1.isEmpty) | ||
|
|
||
| // Usage metadata for first request might not show cache usage yet, or show 0. | ||
| _ = try #require(response1.usageMetadata) | ||
| // We don't strictly assert 0 here because it's possible (though unlikely) we hit an existing | ||
| // cache from another run. | ||
|
|
||
| // Second request: reuse the exact same prefix | ||
| let prompt2 = largeContext + "\nQuestion 2: What is the last word of the repeating sentence?" | ||
| let response2 = try await model.generateContent(prompt2) | ||
| let text2 = try #require(response2.text) | ||
| #expect(!text2.isEmpty) | ||
|
|
||
| let usage2 = try #require(response2.usageMetadata) | ||
|
|
||
| // Verify that cache usage is reported (non-zero or accessible). | ||
| // Note: Implicit caching is "best effort" and depends on backend state/timing. | ||
| // If it triggers, `cachedContentTokenCount` should be > 0. | ||
| // If it doesn't trigger, we at least verify the field exists and is 0. | ||
| // However, the goal is "generate requests with a non-zero cacheContentTokenCount". | ||
| // We can try to assert > 0, but if it fails flakily, we might need to relax it or use | ||
| // `Issue.record`. | ||
|
|
||
| if usage2.cachedContentTokenCount > 0 { | ||
| print("Implicit cache hit! cachedContentTokenCount: \(usage2.cachedContentTokenCount)") | ||
| #expect(usage2.cacheTokensDetails.count > 0) | ||
| #expect(usage2.cacheTokensDetails.first?.modality == .text) | ||
| let totalDetailTokens = usage2.cacheTokensDetails.map(\.tokenCount).reduce(0, +) | ||
| #expect(totalDetailTokens == usage2.cachedContentTokenCount) | ||
| } else { | ||
| print( | ||
| "Implicit cache miss. This test might be flaky if the backend doesn't cache immediately." | ||
| ) | ||
| // We don't fail the test here to avoid CI flakiness, but we log it. | ||
| } | ||
|
|
||
| // Ensure the total token count logic holds | ||
| // Note: totalTokenCount typically includes prompt + candidates (+ thoughts). | ||
| // cachedContentTokenCount is usually a subset of promptTokenCount or separate, but often not | ||
| // added to total if total represents "tokens processed" or similar, | ||
| // or if promptTokenCount already covers the semantic prompt. | ||
| // Based on observation, it seems cached tokens are NOT added to the totalTokenCount field | ||
| // returned by backend. | ||
| #expect(usage2.totalTokenCount == ( | ||
| usage2.promptTokenCount + | ||
| usage2.candidatesTokenCount + | ||
| usage2.thoughtsTokenCount | ||
| )) | ||
| } | ||
| } |
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
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.