FirebaseAI.swift 12 KB

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