|
| 1 | +// Copyright 2025 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import FirebaseAI |
| 16 | +import FirebaseCore |
| 17 | +import XCTest |
| 18 | + |
| 19 | +// These snippet tests are intentionally skipped in CI jobs; see the README file in this directory |
| 20 | +// for instructions on running them manually. |
| 21 | + |
| 22 | +@available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *) |
| 23 | +final class CountTokensSnippets: XCTestCase { |
| 24 | + let bundle = BundleTestUtil.bundle() |
| 25 | + lazy var model = FirebaseAI.firebaseAI().generativeModel(modelName: "gemini-2.0-flash") |
| 26 | + lazy var imageURL = { |
| 27 | + guard let url = bundle.url(forResource: "blue", withExtension: "png") else { |
| 28 | + fatalError("Image file blue.png not found in Resources.") |
| 29 | + } |
| 30 | + return url |
| 31 | + }() |
| 32 | + |
| 33 | + lazy var image = { |
| 34 | + guard let imageData = try? Data(contentsOf: imageURL) else { |
| 35 | + fatalError("Failed to load image from URL: \(imageURL)") |
| 36 | + } |
| 37 | + return InlineDataPart(data: imageData, mimeType: "image/png") |
| 38 | + }() |
| 39 | + |
| 40 | + override func setUpWithError() throws { |
| 41 | + try FirebaseApp.configureDefaultAppForSnippets() |
| 42 | + } |
| 43 | + |
| 44 | + override func tearDown() async throws { |
| 45 | + await FirebaseApp.deleteDefaultAppForSnippets() |
| 46 | + } |
| 47 | + |
| 48 | + func testTextOnlyInput() async throws { |
| 49 | + let response = try await model.countTokens("Write a story about a magic backpack.") |
| 50 | + |
| 51 | + print("Total Tokens: \(response.totalTokens)") |
| 52 | + } |
| 53 | + |
| 54 | + func testMultimodalInput() async throws { |
| 55 | + let response = try await model.countTokens(image, "What's in this picture?") |
| 56 | + |
| 57 | + print("Total Tokens: \(response.totalTokens)") |
| 58 | + // Print tokens by modality, for example "TEXT Tokens: 7" and "IMAGE Tokens: 258" |
| 59 | + for promptTokensDetail in response.promptTokensDetails { |
| 60 | + print("\(promptTokensDetail.modality.rawValue) Tokens: \(promptTokensDetail.tokenCount)") |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments