VertexAI.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 12.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. let instanceKey = "\(app.name):\(location)"
  51. if let instance = instances[instanceKey] {
  52. return instance
  53. }
  54. let newInstance = VertexAI(app: app, location: location)
  55. instances[instanceKey] = newInstance
  56. return newInstance
  57. }
  58. /// Initializes a generative model with the given parameters.
  59. ///
  60. /// - Note: Refer to [Gemini models](https://firebase.google.com/docs/vertex-ai/gemini-models) for
  61. /// guidance on choosing an appropriate model for your use case.
  62. ///
  63. /// - Parameters:
  64. /// - modelName: The name of the model to use, for example `"gemini-1.5-flash"`; see
  65. /// [available model names
  66. /// ](https://firebase.google.com/docs/vertex-ai/gemini-models#available-model-names) for a
  67. /// list of supported model names.
  68. /// - generationConfig: The content generation parameters your model should use.
  69. /// - safetySettings: A value describing what types of harmful content your model should allow.
  70. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  71. /// - toolConfig: Tool configuration for any `Tool` specified in the request.
  72. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  73. /// only text content is supported.
  74. /// - requestOptions: Configuration parameters for sending requests to the backend.
  75. public func generativeModel(modelName: String,
  76. generationConfig: GenerationConfig? = nil,
  77. safetySettings: [SafetySetting]? = nil,
  78. tools: [Tool]? = nil,
  79. toolConfig: ToolConfig? = nil,
  80. systemInstruction: ModelContent? = nil,
  81. requestOptions: RequestOptions = RequestOptions())
  82. -> GenerativeModel {
  83. return GenerativeModel(
  84. name: modelResourceName(modelName: modelName),
  85. projectID: projectID,
  86. apiKey: apiKey,
  87. generationConfig: generationConfig,
  88. safetySettings: safetySettings,
  89. tools: tools,
  90. toolConfig: toolConfig,
  91. systemInstruction: systemInstruction,
  92. requestOptions: requestOptions,
  93. appCheck: appCheck,
  94. auth: auth
  95. )
  96. }
  97. /// **[Public Preview]** Initializes an ``ImagenModel`` with the given parameters.
  98. ///
  99. /// > Warning: For Vertex AI in Firebase, image generation using Imagen 3 models is in Public
  100. /// Preview, which means that the feature is not subject to any SLA or deprecation policy and
  101. /// could change in backwards-incompatible ways.
  102. ///
  103. /// > Important: Only Imagen 3 models (named `imagen-3.0-*`) are supported.
  104. ///
  105. /// - Parameters:
  106. /// - modelName: The name of the Imagen 3 model to use, for example `"imagen-3.0-generate-002"`;
  107. /// see [model
  108. /// versions](https://cloud.google.com/vertex-ai/generative-ai/docs/image/model-versioning)
  109. /// for a list of supported Imagen 3 models.
  110. /// - generationConfig: Configuration options for generating images with Imagen.
  111. /// - safetySettings: Settings describing what types of potentially harmful content your model
  112. /// should allow.
  113. /// - requestOptions: Configuration parameters for sending requests to the backend.
  114. public func imagenModel(modelName: String, generationConfig: ImagenGenerationConfig? = nil,
  115. safetySettings: ImagenSafetySettings? = nil,
  116. requestOptions: RequestOptions = RequestOptions()) -> ImagenModel {
  117. return ImagenModel(
  118. name: modelResourceName(modelName: modelName),
  119. projectID: projectID,
  120. apiKey: apiKey,
  121. generationConfig: generationConfig,
  122. safetySettings: safetySettings,
  123. requestOptions: requestOptions,
  124. appCheck: appCheck,
  125. auth: auth
  126. )
  127. }
  128. /// Class to enable VertexAI to register via the Objective-C based Firebase component system
  129. /// to include VertexAI in the userAgent.
  130. @objc(FIRVertexAIComponent) class FirebaseVertexAIComponent: NSObject {}
  131. // MARK: - Private
  132. /// The `FirebaseApp` associated with this `VertexAI` instance.
  133. private let app: FirebaseApp
  134. private let appCheck: AppCheckInterop?
  135. private let auth: AuthInterop?
  136. /// A map of active `VertexAI` instances keyed by the `FirebaseApp` name and the `location`, in
  137. /// the format `appName:location`.
  138. private static var instances: [String: VertexAI] = [:]
  139. /// Lock to manage access to the `instances` array to avoid race conditions.
  140. private static var instancesLock: os_unfair_lock = .init()
  141. let projectID: String
  142. let apiKey: String
  143. let location: String
  144. init(app: FirebaseApp, location: String) {
  145. self.app = app
  146. appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self, in: app.container)
  147. auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  148. guard let projectID = app.options.projectID else {
  149. fatalError("The Firebase app named \"\(app.name)\" has no project ID in its configuration.")
  150. }
  151. self.projectID = projectID
  152. guard let apiKey = app.options.apiKey else {
  153. fatalError("The Firebase app named \"\(app.name)\" has no API key in its configuration.")
  154. }
  155. self.apiKey = apiKey
  156. self.location = location
  157. }
  158. func modelResourceName(modelName: String) -> String {
  159. guard !modelName.isEmpty && modelName
  160. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  161. fatalError("""
  162. Invalid model name "\(modelName)" specified; see \
  163. https://firebase.google.com/docs/vertex-ai/gemini-model#available-models for a list of \
  164. available models.
  165. """)
  166. }
  167. guard !location.isEmpty && location
  168. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  169. fatalError("""
  170. Invalid location "\(location)" specified; see \
  171. https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations \
  172. for a list of available locations.
  173. """)
  174. }
  175. return "projects/\(projectID)/locations/\(location)/publishers/google/models/\(modelName)"
  176. }
  177. }