VertexAI.swift 11 KB

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