VertexAI.swift 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // Copyright 2024 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 FirebaseAppCheckInterop
  15. import FirebaseAuthInterop
  16. import FirebaseCore
  17. import Foundation
  18. // Avoids exposing internal FirebaseCore APIs to Swift users.
  19. @_implementationOnly import FirebaseCoreExtension
  20. /// The Vertex AI for Firebase SDK provides access to Gemini models directly from your app.
  21. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  22. public class VertexAI {
  23. // MARK: - Public APIs
  24. /// The default `VertexAI` instance.
  25. ///
  26. /// - Parameter location: The region identifier, defaulting to `us-central1`; see [Vertex AI
  27. /// regions
  28. /// ](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#available-regions)
  29. /// for a list of supported regions.
  30. /// - Returns: An instance of `VertexAI`, configured with the default `FirebaseApp`.
  31. public static func vertexAI(location: String = "us-central1") -> VertexAI {
  32. guard let app = FirebaseApp.app() else {
  33. fatalError("No instance of the default Firebase app was found.")
  34. }
  35. return vertexAI(app: app, location: location)
  36. }
  37. /// Creates an instance of `VertexAI` configured with a custom `FirebaseApp`.
  38. ///
  39. /// - Parameters:
  40. /// - app: The custom `FirebaseApp` used for initialization.
  41. /// - location: The region identifier, defaulting to `us-central1`; see
  42. /// [Vertex AI locations]
  43. /// (https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations)
  44. /// for a list of supported locations.
  45. /// - Returns: A `VertexAI` instance, configured with the custom `FirebaseApp`.
  46. public static func vertexAI(app: FirebaseApp, location: String = "us-central1") -> VertexAI {
  47. os_unfair_lock_lock(&instancesLock)
  48. // Unlock before the function returns.
  49. defer { os_unfair_lock_unlock(&instancesLock) }
  50. if let instance = instances[location] {
  51. return instance
  52. }
  53. let newInstance = VertexAI(app: app, location: location)
  54. instances[location] = newInstance
  55. return newInstance
  56. }
  57. /// Initializes a generative model with the given parameters.
  58. ///
  59. /// - Note: Refer to [Gemini models](https://firebase.google.com/docs/vertex-ai/gemini-models) for
  60. /// guidance on choosing an appropriate model for your use case.
  61. ///
  62. /// - Parameters:
  63. /// - modelName: The name of the model to use, for example `"gemini-1.5-flash"`; see
  64. /// [available model names
  65. /// ](https://firebase.google.com/docs/vertex-ai/gemini-models#available-model-names) for a
  66. /// list of supported model names.
  67. /// - generationConfig: The content generation parameters your model should use.
  68. /// - safetySettings: A value describing what types of harmful content your model should allow.
  69. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  70. /// - toolConfig: Tool configuration for any `Tool` specified in the request.
  71. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  72. /// only text content is supported.
  73. /// - requestOptions: Configuration parameters for sending requests to the backend.
  74. public func generativeModel(modelName: String,
  75. generationConfig: GenerationConfig? = nil,
  76. safetySettings: [SafetySetting]? = nil,
  77. tools: [Tool]? = nil,
  78. toolConfig: ToolConfig? = nil,
  79. systemInstruction: ModelContent? = nil,
  80. requestOptions: RequestOptions = RequestOptions())
  81. -> GenerativeModel {
  82. return GenerativeModel(
  83. name: modelResourceName(modelName: modelName),
  84. projectID: projectID,
  85. apiKey: apiKey,
  86. generationConfig: generationConfig,
  87. safetySettings: safetySettings,
  88. tools: tools,
  89. toolConfig: toolConfig,
  90. systemInstruction: systemInstruction,
  91. requestOptions: requestOptions,
  92. appCheck: appCheck,
  93. auth: auth
  94. )
  95. }
  96. /// Class to enable VertexAI to register via the Objective-C based Firebase component system
  97. /// to include VertexAI in the userAgent.
  98. @objc(FIRVertexAIComponent) class FirebaseVertexAIComponent: NSObject {}
  99. // MARK: - Private
  100. /// The `FirebaseApp` associated with this `VertexAI` instance.
  101. private let app: FirebaseApp
  102. private let appCheck: AppCheckInterop?
  103. private let auth: AuthInterop?
  104. /// A map of active `VertexAI` instances for `app`, keyed by model resource names
  105. /// (e.g., "projects/my-project-id/locations/us-central1/publishers/google/models/gemini-pro").
  106. private static var instances: [String: VertexAI] = [:]
  107. /// Lock to manage access to the `instances` array to avoid race conditions.
  108. private static var instancesLock: os_unfair_lock = .init()
  109. let projectID: String
  110. let apiKey: String
  111. let location: String
  112. init(app: FirebaseApp, location: String) {
  113. self.app = app
  114. appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self, in: app.container)
  115. auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  116. guard let projectID = app.options.projectID else {
  117. fatalError("The Firebase app named \"\(app.name)\" has no project ID in its configuration.")
  118. }
  119. self.projectID = projectID
  120. guard let apiKey = app.options.apiKey else {
  121. fatalError("The Firebase app named \"\(app.name)\" has no API key in its configuration.")
  122. }
  123. self.apiKey = apiKey
  124. self.location = location
  125. }
  126. func modelResourceName(modelName: String) -> String {
  127. guard !modelName.isEmpty && modelName
  128. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  129. fatalError("""
  130. Invalid model name "\(modelName)" specified; see \
  131. https://firebase.google.com/docs/vertex-ai/gemini-model#available-models for a list of \
  132. available models.
  133. """)
  134. }
  135. guard !location.isEmpty && location
  136. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  137. fatalError("""
  138. Invalid location "\(location)" specified; see \
  139. https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations \
  140. for a list of available locations.
  141. """)
  142. }
  143. return "projects/\(projectID)/locations/\(location)/publishers/google/models/\(modelName)"
  144. }
  145. }