FirebaseAI.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. /// - useLimitedUseAppCheckTokens: When sending tokens to the backend, this option enables
  32. /// the usage of App Check's limited-use tokens instead of the standard cached tokens. Learn
  33. /// more about [limited-use tokens](https://firebase.google.com/docs/ai-logic/app-check),
  34. /// including their nuances, when to use them, and best practices for integrating them into
  35. /// your app.
  36. ///
  37. /// _This flag is set to `false` by default._
  38. /// > Migrating to limited-use tokens sooner minimizes disruption when support for replay
  39. /// > protection is added.
  40. /// - Returns: A `FirebaseAI` instance, configured with the custom `FirebaseApp`.
  41. public static func firebaseAI(app: FirebaseApp? = nil,
  42. backend: Backend = .googleAI(),
  43. useLimitedUseAppCheckTokens: Bool = false) -> FirebaseAI {
  44. let instance = createInstance(
  45. app: app,
  46. location: backend.location,
  47. apiConfig: backend.apiConfig,
  48. useLimitedUseAppCheckTokens: useLimitedUseAppCheckTokens
  49. )
  50. // Verify that the `FirebaseAI` instance is always configured with the production endpoint since
  51. // this is the public API surface for creating an instance.
  52. assert(instance.apiConfig.service.endpoint == .firebaseProxyProd)
  53. assert(instance.apiConfig.version == .v1beta)
  54. return instance
  55. }
  56. /// Initializes a generative model with the given parameters.
  57. ///
  58. /// - Note: Refer to [Gemini models](https://firebase.google.com/docs/vertex-ai/gemini-models) for
  59. /// guidance on choosing an appropriate model for your use case.
  60. ///
  61. /// - Parameters:
  62. /// - modelName: The name of the model to use, for example `"gemini-1.5-flash"`; see
  63. /// [available model names
  64. /// ](https://firebase.google.com/docs/vertex-ai/gemini-models#available-model-names) for a
  65. /// list of supported model names.
  66. /// - generationConfig: The content generation parameters your model should use.
  67. /// - safetySettings: A value describing what types of harmful content your model should allow.
  68. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  69. /// - toolConfig: Tool configuration for any `Tool` specified in the request.
  70. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  71. /// only text content is supported.
  72. /// - requestOptions: Configuration parameters for sending requests to the backend.
  73. public func generativeModel(modelName: String,
  74. generationConfig: GenerationConfig? = nil,
  75. safetySettings: [SafetySetting]? = nil,
  76. tools: [Tool]? = nil,
  77. toolConfig: ToolConfig? = nil,
  78. systemInstruction: ModelContent? = nil,
  79. requestOptions: RequestOptions = RequestOptions())
  80. -> GenerativeModel {
  81. if !modelName.starts(with: GenerativeModel.geminiModelNamePrefix)
  82. && !modelName.starts(with: GenerativeModel.gemmaModelNamePrefix) {
  83. AILog.warning(code: .unsupportedGeminiModel, """
  84. Unsupported Gemini model "\(modelName)"; see \
  85. https://firebase.google.com/docs/vertex-ai/models for a list supported Gemini model names.
  86. """)
  87. }
  88. return GenerativeModel(
  89. modelName: modelName,
  90. modelResourceName: modelResourceName(modelName: modelName),
  91. firebaseInfo: firebaseInfo,
  92. apiConfig: apiConfig,
  93. generationConfig: generationConfig,
  94. safetySettings: safetySettings,
  95. tools: tools,
  96. toolConfig: toolConfig,
  97. systemInstruction: systemInstruction,
  98. requestOptions: requestOptions
  99. )
  100. }
  101. /// Initializes an ``ImagenModel`` with the given parameters.
  102. ///
  103. /// > Important: Only Imagen 3 models (named `imagen-3.0-*`) are supported.
  104. ///
  105. /// - Parameters:
  106. /// - modelName: The name of the Imagen 3 model to use, for example `"imagen-3.0-generate-002"`;
  107. /// see [model versions](https://firebase.google.com/docs/vertex-ai/models) for a list of
  108. /// supported Imagen 3 models.
  109. /// - generationConfig: Configuration options for generating images with Imagen.
  110. /// - safetySettings: Settings describing what types of potentially harmful content your model
  111. /// should allow.
  112. /// - requestOptions: Configuration parameters for sending requests to the backend.
  113. public func imagenModel(modelName: String, generationConfig: ImagenGenerationConfig? = nil,
  114. safetySettings: ImagenSafetySettings? = nil,
  115. requestOptions: RequestOptions = RequestOptions()) -> ImagenModel {
  116. if !modelName.starts(with: ImagenModel.imagenModelNamePrefix) {
  117. AILog.warning(code: .unsupportedImagenModel, """
  118. Unsupported Imagen model "\(modelName)"; see \
  119. https://firebase.google.com/docs/vertex-ai/models for a list supported Imagen model names.
  120. """)
  121. }
  122. return ImagenModel(
  123. modelResourceName: modelResourceName(modelName: modelName),
  124. firebaseInfo: firebaseInfo,
  125. apiConfig: apiConfig,
  126. generationConfig: generationConfig,
  127. safetySettings: safetySettings,
  128. requestOptions: requestOptions
  129. )
  130. }
  131. /// **[Public Preview]** Initializes a ``LiveGenerativeModel`` with the given parameters.
  132. ///
  133. /// > Warning: Using the Firebase AI Logic SDKs with the Gemini Live API is in Public
  134. /// Preview, which means that the feature is not subject to any SLA or deprecation policy and
  135. /// could change in backwards-incompatible ways.
  136. ///
  137. /// > Important: Only models that support the Gemini Live API (typically containing `live-*` in
  138. /// the name) are supported.
  139. ///
  140. /// - Parameters:
  141. /// - modelName: The name of the model to use, for example
  142. /// `"gemini-live-2.5-flash-preview"`;
  143. /// see [model versions](https://firebase.google.com/docs/ai-logic/live-api?api=dev#models-that-support-capability)
  144. /// for a list of supported models.
  145. /// - generationConfig: The content generation parameters your model should use.
  146. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  147. /// - toolConfig: Tool configuration for any ``Tool`` specified in the request.
  148. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  149. /// only text content is supported.
  150. /// - requestOptions: Configuration parameters for sending requests to the backend.
  151. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, *)
  152. @available(watchOS, unavailable)
  153. public func liveModel(modelName: String,
  154. generationConfig: LiveGenerationConfig? = nil,
  155. tools: [Tool]? = nil,
  156. toolConfig: ToolConfig? = nil,
  157. systemInstruction: ModelContent? = nil,
  158. requestOptions: RequestOptions = RequestOptions()) -> LiveGenerativeModel {
  159. return LiveGenerativeModel(
  160. modelResourceName: modelResourceName(modelName: modelName),
  161. firebaseInfo: firebaseInfo,
  162. apiConfig: apiConfig,
  163. generationConfig: generationConfig,
  164. tools: tools,
  165. toolConfig: toolConfig,
  166. systemInstruction: systemInstruction,
  167. requestOptions: requestOptions
  168. )
  169. }
  170. /// Class to enable FirebaseAI to register via the Objective-C based Firebase component system
  171. /// to include FirebaseAI in the userAgent.
  172. @objc(FIRVertexAIComponent) class FirebaseVertexAIComponent: NSObject {}
  173. // MARK: - Private
  174. /// Firebase data relevant to Firebase AI.
  175. let firebaseInfo: FirebaseInfo
  176. let apiConfig: APIConfig
  177. /// A map of active `FirebaseAI` instances keyed by the `FirebaseApp` name and the `location`,
  178. /// in the format `appName:location`.
  179. private nonisolated(unsafe) static var instances: [InstanceKey: FirebaseAI] = [:]
  180. /// Lock to manage access to the `instances` array to avoid race conditions.
  181. private nonisolated(unsafe) static var instancesLock: os_unfair_lock = .init()
  182. let location: String?
  183. static let defaultVertexAIAPIConfig = APIConfig(
  184. service: .vertexAI(endpoint: .firebaseProxyProd),
  185. version: .v1beta
  186. )
  187. static func createInstance(app: FirebaseApp?, location: String?,
  188. apiConfig: APIConfig,
  189. useLimitedUseAppCheckTokens: Bool) -> FirebaseAI {
  190. guard let app = app ?? FirebaseApp.app() else {
  191. fatalError("No instance of the default Firebase app was found.")
  192. }
  193. os_unfair_lock_lock(&instancesLock)
  194. // Unlock before the function returns.
  195. defer { os_unfair_lock_unlock(&instancesLock) }
  196. let instanceKey = InstanceKey(
  197. appName: app.name,
  198. location: location,
  199. apiConfig: apiConfig,
  200. useLimitedUseAppCheckTokens: useLimitedUseAppCheckTokens
  201. )
  202. if let instance = instances[instanceKey] {
  203. return instance
  204. }
  205. let newInstance = FirebaseAI(
  206. app: app,
  207. location: location,
  208. apiConfig: apiConfig,
  209. useLimitedUseAppCheckTokens: useLimitedUseAppCheckTokens
  210. )
  211. instances[instanceKey] = newInstance
  212. return newInstance
  213. }
  214. init(app: FirebaseApp, location: String?, apiConfig: APIConfig,
  215. useLimitedUseAppCheckTokens: Bool) {
  216. guard let projectID = app.options.projectID else {
  217. fatalError("The Firebase app named \"\(app.name)\" has no project ID in its configuration.")
  218. }
  219. guard let apiKey = app.options.apiKey else {
  220. fatalError("The Firebase app named \"\(app.name)\" has no API key in its configuration.")
  221. }
  222. firebaseInfo = FirebaseInfo(
  223. appCheck: ComponentType<AppCheckInterop>.instance(
  224. for: AppCheckInterop.self,
  225. in: app.container
  226. ),
  227. auth: ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container),
  228. projectID: projectID,
  229. apiKey: apiKey,
  230. firebaseAppID: app.options.googleAppID,
  231. firebaseApp: app,
  232. useLimitedUseAppCheckTokens: useLimitedUseAppCheckTokens
  233. )
  234. self.apiConfig = apiConfig
  235. self.location = location
  236. }
  237. func modelResourceName(modelName: String) -> String {
  238. guard !modelName.isEmpty && modelName
  239. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  240. fatalError("""
  241. Invalid model name "\(modelName)" specified; see \
  242. https://firebase.google.com/docs/vertex-ai/gemini-model#available-models for a list of \
  243. available models.
  244. """)
  245. }
  246. switch apiConfig.service {
  247. case .vertexAI:
  248. return vertexAIModelResourceName(modelName: modelName)
  249. case .googleAI:
  250. return developerModelResourceName(modelName: modelName)
  251. }
  252. }
  253. private func vertexAIModelResourceName(modelName: String) -> String {
  254. guard let location else {
  255. fatalError("Location must be specified for the Firebase AI service.")
  256. }
  257. guard !location.isEmpty && location
  258. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  259. fatalError("""
  260. Invalid location "\(location)" specified; see \
  261. https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations \
  262. for a list of available locations.
  263. """)
  264. }
  265. let projectID = firebaseInfo.projectID
  266. return "projects/\(projectID)/locations/\(location)/publishers/google/models/\(modelName)"
  267. }
  268. private func developerModelResourceName(modelName: String) -> String {
  269. switch apiConfig.service.endpoint {
  270. case .firebaseProxyStaging, .firebaseProxyProd:
  271. let projectID = firebaseInfo.projectID
  272. return "projects/\(projectID)/models/\(modelName)"
  273. case .googleAIBypassProxy:
  274. return "models/\(modelName)"
  275. }
  276. }
  277. /// Identifier for a unique instance of ``FirebaseAI``.
  278. ///
  279. /// This type is `Hashable` so that it can be used as a key in the `instances` dictionary.
  280. private struct InstanceKey: Sendable, Hashable {
  281. let appName: String
  282. let location: String?
  283. let apiConfig: APIConfig
  284. let useLimitedUseAppCheckTokens: Bool
  285. }
  286. }