FirebaseAI.swift 11 KB

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