FirebaseAI.swift 10 KB

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