VertexAI.swift 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. /// Creates an instance of `VertexAI`.
  25. ///
  26. /// - Parameters:
  27. /// - app: A custom `FirebaseApp` used for initialization; if not specified, uses the default
  28. /// ``FirebaseApp``.
  29. /// - location: The region identifier, defaulting to `us-central1`; see
  30. /// [Vertex AI locations]
  31. /// (https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations)
  32. /// for a list of supported locations.
  33. /// - Returns: A `VertexAI` instance, configured with the custom `FirebaseApp`.
  34. public static func vertexAI(app: FirebaseApp? = nil,
  35. location: String = "us-central1") -> VertexAI {
  36. let vertexInstance = vertexAI(app: app, location: location, apiConfig: defaultVertexAIAPIConfig)
  37. assert(vertexInstance.apiConfig.service == .vertexAI)
  38. assert(vertexInstance.apiConfig.service.endpoint == .firebaseVertexAIProd)
  39. assert(vertexInstance.apiConfig.version == .v1beta)
  40. return vertexInstance
  41. }
  42. /// Initializes a generative model with the given parameters.
  43. ///
  44. /// - Note: Refer to [Gemini models](https://firebase.google.com/docs/vertex-ai/gemini-models) for
  45. /// guidance on choosing an appropriate model for your use case.
  46. ///
  47. /// - Parameters:
  48. /// - modelName: The name of the model to use, for example `"gemini-1.5-flash"`; see
  49. /// [available model names
  50. /// ](https://firebase.google.com/docs/vertex-ai/gemini-models#available-model-names) for a
  51. /// list of supported model names.
  52. /// - generationConfig: The content generation parameters your model should use.
  53. /// - safetySettings: A value describing what types of harmful content your model should allow.
  54. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  55. /// - toolConfig: Tool configuration for any `Tool` specified in the request.
  56. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  57. /// only text content is supported.
  58. /// - requestOptions: Configuration parameters for sending requests to the backend.
  59. public func generativeModel(modelName: String,
  60. generationConfig: GenerationConfig? = nil,
  61. safetySettings: [SafetySetting]? = nil,
  62. tools: [Tool]? = nil,
  63. toolConfig: ToolConfig? = nil,
  64. systemInstruction: ModelContent? = nil,
  65. requestOptions: RequestOptions = RequestOptions())
  66. -> GenerativeModel {
  67. return GenerativeModel(
  68. name: modelResourceName(modelName: modelName),
  69. firebaseInfo: firebaseInfo,
  70. apiConfig: apiConfig,
  71. generationConfig: generationConfig,
  72. safetySettings: safetySettings,
  73. tools: tools,
  74. toolConfig: toolConfig,
  75. systemInstruction: systemInstruction,
  76. requestOptions: requestOptions
  77. )
  78. }
  79. /// **[Public Preview]** Initializes an ``ImagenModel`` with the given parameters.
  80. ///
  81. /// > Warning: For Vertex AI in Firebase, image generation using Imagen 3 models is in Public
  82. /// Preview, which means that the feature is not subject to any SLA or deprecation policy and
  83. /// could change in backwards-incompatible ways.
  84. ///
  85. /// > Important: Only Imagen 3 models (named `imagen-3.0-*`) are supported.
  86. ///
  87. /// - Parameters:
  88. /// - modelName: The name of the Imagen 3 model to use, for example `"imagen-3.0-generate-002"`;
  89. /// see [model versions](https://firebase.google.com/docs/vertex-ai/models) for a list of
  90. /// supported Imagen 3 models.
  91. /// - generationConfig: Configuration options for generating images with Imagen.
  92. /// - safetySettings: Settings describing what types of potentially harmful content your model
  93. /// should allow.
  94. /// - requestOptions: Configuration parameters for sending requests to the backend.
  95. public func imagenModel(modelName: String, generationConfig: ImagenGenerationConfig? = nil,
  96. safetySettings: ImagenSafetySettings? = nil,
  97. requestOptions: RequestOptions = RequestOptions()) -> ImagenModel {
  98. return ImagenModel(
  99. name: modelResourceName(modelName: modelName),
  100. firebaseInfo: firebaseInfo,
  101. apiConfig: apiConfig,
  102. generationConfig: generationConfig,
  103. safetySettings: safetySettings,
  104. requestOptions: requestOptions
  105. )
  106. }
  107. /// Class to enable VertexAI to register via the Objective-C based Firebase component system
  108. /// to include VertexAI in the userAgent.
  109. @objc(FIRVertexAIComponent) class FirebaseVertexAIComponent: NSObject {}
  110. // MARK: - Private
  111. /// Firebase data relevant to Vertex AI.
  112. let firebaseInfo: FirebaseInfo
  113. let apiConfig: APIConfig
  114. #if compiler(>=6)
  115. /// A map of active `VertexAI` instances keyed by the `FirebaseApp` name and the `location`, in
  116. /// the format `appName:location`.
  117. private nonisolated(unsafe) static var instances: [InstanceKey: VertexAI] = [:]
  118. /// Lock to manage access to the `instances` array to avoid race conditions.
  119. private nonisolated(unsafe) static var instancesLock: os_unfair_lock = .init()
  120. #else
  121. /// A map of active `VertexAI` instances keyed by the `FirebaseApp` name and the `location`, in
  122. /// the format `appName:location`.
  123. private static var instances: [InstanceKey: VertexAI] = [:]
  124. /// Lock to manage access to the `instances` array to avoid race conditions.
  125. private static var instancesLock: os_unfair_lock = .init()
  126. #endif
  127. let location: String?
  128. static let defaultVertexAIAPIConfig = APIConfig(service: .vertexAI, version: .v1beta)
  129. static func vertexAI(app: FirebaseApp?, location: String?, apiConfig: APIConfig) -> VertexAI {
  130. guard let app = app ?? FirebaseApp.app() else {
  131. fatalError("No instance of the default Firebase app was found.")
  132. }
  133. os_unfair_lock_lock(&instancesLock)
  134. // Unlock before the function returns.
  135. defer { os_unfair_lock_unlock(&instancesLock) }
  136. let instanceKey = InstanceKey(appName: app.name, location: location, apiConfig: apiConfig)
  137. if let instance = instances[instanceKey] {
  138. return instance
  139. }
  140. let newInstance = VertexAI(app: app, location: location, apiConfig: apiConfig)
  141. instances[instanceKey] = newInstance
  142. return newInstance
  143. }
  144. init(app: FirebaseApp, location: String?, apiConfig: APIConfig) {
  145. guard let projectID = app.options.projectID else {
  146. fatalError("The Firebase app named \"\(app.name)\" has no project ID in its configuration.")
  147. }
  148. guard let apiKey = app.options.apiKey else {
  149. fatalError("The Firebase app named \"\(app.name)\" has no API key in its configuration.")
  150. }
  151. firebaseInfo = FirebaseInfo(
  152. appCheck: ComponentType<AppCheckInterop>.instance(
  153. for: AppCheckInterop.self,
  154. in: app.container
  155. ),
  156. auth: ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container),
  157. projectID: projectID,
  158. apiKey: apiKey,
  159. firebaseAppID: app.options.googleAppID,
  160. firebaseApp: app
  161. )
  162. self.apiConfig = apiConfig
  163. self.location = location
  164. }
  165. func modelResourceName(modelName: String) -> String {
  166. guard !modelName.isEmpty && modelName
  167. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  168. fatalError("""
  169. Invalid model name "\(modelName)" specified; see \
  170. https://firebase.google.com/docs/vertex-ai/gemini-model#available-models for a list of \
  171. available models.
  172. """)
  173. }
  174. switch apiConfig.service {
  175. case .vertexAI:
  176. return vertexAIModelResourceName(modelName: modelName)
  177. case .developer:
  178. return developerModelResourceName(modelName: modelName)
  179. }
  180. }
  181. private func vertexAIModelResourceName(modelName: String) -> String {
  182. guard let location else {
  183. fatalError("Location must be specified for the Vertex AI service.")
  184. }
  185. guard !location.isEmpty && location
  186. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  187. fatalError("""
  188. Invalid location "\(location)" specified; see \
  189. https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations \
  190. for a list of available locations.
  191. """)
  192. }
  193. let projectID = firebaseInfo.projectID
  194. return "projects/\(projectID)/locations/\(location)/publishers/google/models/\(modelName)"
  195. }
  196. private func developerModelResourceName(modelName: String) -> String {
  197. switch apiConfig.service.endpoint {
  198. case .firebaseVertexAIStaging:
  199. let projectID = firebaseInfo.projectID
  200. return "projects/\(projectID)/models/\(modelName)"
  201. case .generativeLanguage:
  202. return "models/\(modelName)"
  203. default:
  204. fatalError("The Developer API is not supported on '\(apiConfig.service.endpoint)'.")
  205. }
  206. }
  207. /// Identifier for a unique instance of ``VertexAI``.
  208. ///
  209. /// This type is `Hashable` so that it can be used as a key in the `instances` dictionary.
  210. private struct InstanceKey: Sendable, Hashable {
  211. let appName: String
  212. let location: String?
  213. let apiConfig: APIConfig
  214. }
  215. }