CountTokensSnippets.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. import FirebaseAI
  15. import FirebaseCore
  16. import XCTest
  17. // These snippet tests are intentionally skipped in CI jobs; see the README file in this directory
  18. // for instructions on running them manually.
  19. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  20. final class CountTokensSnippets: XCTestCase {
  21. let bundle = BundleTestUtil.bundle()
  22. lazy var model = FirebaseAI.firebaseAI().generativeModel(modelName: "gemini-2.0-flash")
  23. lazy var imageURL = {
  24. guard let url = bundle.url(forResource: "blue", withExtension: "png") else {
  25. fatalError("Image file blue.png not found in Resources.")
  26. }
  27. return url
  28. }()
  29. lazy var image = {
  30. guard let imageData = try? Data(contentsOf: imageURL) else {
  31. fatalError("Failed to load image from URL: \(imageURL)")
  32. }
  33. return InlineDataPart(data: imageData, mimeType: "image/png")
  34. }()
  35. override func setUpWithError() throws {
  36. try FirebaseApp.configureDefaultAppForSnippets()
  37. }
  38. override func tearDown() async throws {
  39. await FirebaseApp.deleteDefaultAppForSnippets()
  40. }
  41. func testTextOnlyInput() async throws {
  42. let response = try await model.countTokens("Write a story about a magic backpack.")
  43. print("Total Tokens: \(response.totalTokens)")
  44. }
  45. func testMultimodalInput() async throws {
  46. let response = try await model.countTokens(image, "What's in this picture?")
  47. print("Total Tokens: \(response.totalTokens)")
  48. // Print tokens by modality, for example "TEXT Tokens: 7" and "IMAGE Tokens: 258"
  49. for promptTokensDetail in response.promptTokensDetails {
  50. print("\(promptTokensDetail.modality.rawValue) Tokens: \(promptTokensDetail.tokenCount)")
  51. }
  52. }
  53. }