VertexAI.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. /// A map of active `VertexAI` instances keyed by the `FirebaseApp` name and the `location`, in
  130. /// the format `appName:location`.
  131. private nonisolated(unsafe) static var instances: [InstanceKey: VertexAI] = [:]
  132. /// Lock to manage access to the `instances` array to avoid race conditions.
  133. private nonisolated(unsafe) static var instancesLock: os_unfair_lock = .init()
  134. let location: String?
  135. static let defaultVertexAIAPIConfig = APIConfig(
  136. service: .vertexAI(endpoint: .firebaseVertexAIProd),
  137. version: .v1beta
  138. )
  139. static func vertexAI(app: FirebaseApp?, location: String?, apiConfig: APIConfig) -> VertexAI {
  140. guard let app = app ?? FirebaseApp.app() else {
  141. fatalError("No instance of the default Firebase app was found.")
  142. }
  143. os_unfair_lock_lock(&instancesLock)
  144. // Unlock before the function returns.
  145. defer { os_unfair_lock_unlock(&instancesLock) }
  146. let instanceKey = InstanceKey(appName: app.name, location: location, apiConfig: apiConfig)
  147. if let instance = instances[instanceKey] {
  148. return instance
  149. }
  150. let newInstance = VertexAI(app: app, location: location, apiConfig: apiConfig)
  151. instances[instanceKey] = newInstance
  152. return newInstance
  153. }
  154. init(app: FirebaseApp, location: String?, apiConfig: APIConfig) {
  155. guard let projectID = app.options.projectID else {
  156. fatalError("The Firebase app named \"\(app.name)\" has no project ID in its configuration.")
  157. }
  158. guard let apiKey = app.options.apiKey else {
  159. fatalError("The Firebase app named \"\(app.name)\" has no API key in its configuration.")
  160. }
  161. firebaseInfo = FirebaseInfo(
  162. appCheck: ComponentType<AppCheckInterop>.instance(
  163. for: AppCheckInterop.self,
  164. in: app.container
  165. ),
  166. auth: ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container),
  167. projectID: projectID,
  168. apiKey: apiKey,
  169. firebaseAppID: app.options.googleAppID,
  170. firebaseApp: app
  171. )
  172. self.apiConfig = apiConfig
  173. self.location = location
  174. }
  175. func modelResourceName(modelName: String) -> String {
  176. guard !modelName.isEmpty && modelName
  177. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  178. fatalError("""
  179. Invalid model name "\(modelName)" specified; see \
  180. https://firebase.google.com/docs/vertex-ai/gemini-model#available-models for a list of \
  181. available models.
  182. """)
  183. }
  184. switch apiConfig.service {
  185. case .vertexAI:
  186. return vertexAIModelResourceName(modelName: modelName)
  187. case .developer:
  188. return developerModelResourceName(modelName: modelName)
  189. }
  190. }
  191. private func vertexAIModelResourceName(modelName: String) -> String {
  192. guard let location else {
  193. fatalError("Location must be specified for the Vertex AI service.")
  194. }
  195. guard !location.isEmpty && location
  196. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  197. fatalError("""
  198. Invalid location "\(location)" specified; see \
  199. https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations \
  200. for a list of available locations.
  201. """)
  202. }
  203. let projectID = firebaseInfo.projectID
  204. return "projects/\(projectID)/locations/\(location)/publishers/google/models/\(modelName)"
  205. }
  206. private func developerModelResourceName(modelName: String) -> String {
  207. switch apiConfig.service.endpoint {
  208. case .firebaseVertexAIStaging, .firebaseVertexAIProd:
  209. let projectID = firebaseInfo.projectID
  210. return "projects/\(projectID)/models/\(modelName)"
  211. case .generativeLanguage:
  212. return "models/\(modelName)"
  213. }
  214. }
  215. /// Identifier for a unique instance of ``VertexAI``.
  216. ///
  217. /// This type is `Hashable` so that it can be used as a key in the `instances` dictionary.
  218. private struct InstanceKey: Sendable, Hashable {
  219. let appName: String
  220. let location: String?
  221. let apiConfig: APIConfig
  222. }
  223. }