VertexAI.swift 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. @_implementationOnly import FirebaseCoreExtension
  20. /// The Vertex AI for Firebase 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 class VertexAI {
  23. // MARK: - Public APIs
  24. /// The default `VertexAI` instance.
  25. ///
  26. /// - Parameter location: The region identifier, defaulting to `us-central1`; see [Vertex AI
  27. /// regions
  28. /// ](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#available-regions)
  29. /// for a list of supported regions.
  30. /// - Returns: An instance of `VertexAI`, configured with the default `FirebaseApp`.
  31. public static func vertexAI(location: String = "us-central1") -> VertexAI {
  32. guard let app = FirebaseApp.app() else {
  33. fatalError("No instance of the default Firebase app was found.")
  34. }
  35. return vertexAI(app: app, location: location)
  36. }
  37. /// Creates an instance of `VertexAI` configured with a custom `FirebaseApp`.
  38. ///
  39. /// - Parameters:
  40. /// - app: The custom `FirebaseApp` used for initialization.
  41. /// - location: The region identifier, defaulting to `us-central1`; see
  42. /// [Vertex AI locations]
  43. /// (https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations)
  44. /// for a list of supported locations.
  45. /// - Returns: A `VertexAI` instance, configured with the custom `FirebaseApp`.
  46. public static func vertexAI(app: FirebaseApp, location: String = "us-central1") -> VertexAI {
  47. os_unfair_lock_lock(&instancesLock)
  48. // Unlock before the function returns.
  49. defer { os_unfair_lock_unlock(&instancesLock) }
  50. let instanceKey = "\(app.name):\(location)"
  51. if let instance = instances[instanceKey] {
  52. return instance
  53. }
  54. let newInstance = VertexAI(app: app, location: location)
  55. instances[instanceKey] = newInstance
  56. return newInstance
  57. }
  58. /// Initializes a generative model with the given parameters.
  59. ///
  60. /// - Note: Refer to [Gemini models](https://firebase.google.com/docs/vertex-ai/gemini-models) for
  61. /// guidance on choosing an appropriate model for your use case.
  62. ///
  63. /// - Parameters:
  64. /// - modelName: The name of the model to use, for example `"gemini-1.5-flash"`; see
  65. /// [available model names
  66. /// ](https://firebase.google.com/docs/vertex-ai/gemini-models#available-model-names) for a
  67. /// list of supported model names.
  68. /// - generationConfig: The content generation parameters your model should use.
  69. /// - safetySettings: A value describing what types of harmful content your model should allow.
  70. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  71. /// - toolConfig: Tool configuration for any `Tool` specified in the request.
  72. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  73. /// only text content is supported.
  74. /// - requestOptions: Configuration parameters for sending requests to the backend.
  75. public func generativeModel(modelName: String,
  76. generationConfig: GenerationConfig? = nil,
  77. safetySettings: [SafetySetting]? = nil,
  78. tools: [Tool]? = nil,
  79. toolConfig: ToolConfig? = nil,
  80. systemInstruction: ModelContent? = nil,
  81. requestOptions: RequestOptions = RequestOptions())
  82. -> GenerativeModel {
  83. return GenerativeModel(
  84. name: modelResourceName(modelName: modelName),
  85. projectID: projectID,
  86. apiKey: apiKey,
  87. generationConfig: generationConfig,
  88. safetySettings: safetySettings,
  89. tools: tools,
  90. toolConfig: toolConfig,
  91. systemInstruction: systemInstruction,
  92. requestOptions: requestOptions,
  93. appCheck: appCheck,
  94. auth: auth
  95. )
  96. }
  97. /// Class to enable VertexAI to register via the Objective-C based Firebase component system
  98. /// to include VertexAI in the userAgent.
  99. @objc(FIRVertexAIComponent) class FirebaseVertexAIComponent: NSObject {}
  100. // MARK: - Private
  101. /// The `FirebaseApp` associated with this `VertexAI` instance.
  102. private let app: FirebaseApp
  103. private let appCheck: AppCheckInterop?
  104. private let auth: AuthInterop?
  105. /// A map of active `VertexAI` instances keyed by the `FirebaseApp` name and the `location`, in
  106. /// the format `appName:location`.
  107. private static var instances: [String: VertexAI] = [:]
  108. /// Lock to manage access to the `instances` array to avoid race conditions.
  109. private static var instancesLock: os_unfair_lock = .init()
  110. let projectID: String
  111. let apiKey: String
  112. let location: String
  113. init(app: FirebaseApp, location: String) {
  114. self.app = app
  115. appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self, in: app.container)
  116. auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  117. guard let projectID = app.options.projectID else {
  118. fatalError("The Firebase app named \"\(app.name)\" has no project ID in its configuration.")
  119. }
  120. self.projectID = projectID
  121. guard let apiKey = app.options.apiKey else {
  122. fatalError("The Firebase app named \"\(app.name)\" has no API key in its configuration.")
  123. }
  124. self.apiKey = apiKey
  125. self.location = location
  126. }
  127. func modelResourceName(modelName: String) -> String {
  128. guard !modelName.isEmpty && modelName
  129. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  130. fatalError("""
  131. Invalid model name "\(modelName)" specified; see \
  132. https://firebase.google.com/docs/vertex-ai/gemini-model#available-models for a list of \
  133. available models.
  134. """)
  135. }
  136. guard !location.isEmpty && location
  137. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  138. fatalError("""
  139. Invalid location "\(location)" specified; see \
  140. https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations \
  141. for a list of available locations.
  142. """)
  143. }
  144. return "projects/\(projectID)/locations/\(location)/publishers/google/models/\(modelName)"
  145. }
  146. }