FirebaseAI.swift 10 KB

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