VertexAI.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 11.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  22. public class VertexAI: NSObject {
  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. guard let provider = ComponentType<VertexAIProvider>.instance(for: VertexAIProvider.self,
  48. in: app.container) else {
  49. fatalError("No \(VertexAIProvider.self) instance found for Firebase app: \(app.name)")
  50. }
  51. return provider.vertexAI(location)
  52. }
  53. /// Initializes a generative model with the given parameters.
  54. ///
  55. /// - Note: Refer to [Gemini models](https://firebase.google.com/docs/vertex-ai/gemini-models) for
  56. /// guidance on choosing an appropriate model for your use case.
  57. ///
  58. /// - Parameters:
  59. /// - modelName: The name of the model to use, for example `"gemini-1.5-flash"`; see
  60. /// [available model names
  61. /// ](https://firebase.google.com/docs/vertex-ai/gemini-models#available-model-names) for a
  62. /// list of supported model names.
  63. /// - generationConfig: The content generation parameters your model should use.
  64. /// - safetySettings: A value describing what types of harmful content your model should allow.
  65. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  66. /// - toolConfig: Tool configuration for any `Tool` specified in the request.
  67. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  68. /// only text content is supported.
  69. /// - requestOptions: Configuration parameters for sending requests to the backend.
  70. public func generativeModel(modelName: String,
  71. generationConfig: GenerationConfig? = nil,
  72. safetySettings: [SafetySetting]? = nil,
  73. tools: [Tool]? = nil,
  74. toolConfig: ToolConfig? = nil,
  75. systemInstruction: ModelContent? = nil,
  76. requestOptions: RequestOptions = RequestOptions())
  77. -> GenerativeModel {
  78. guard let projectID = app.options.projectID else {
  79. fatalError("The Firebase app named \"\(app.name)\" has no project ID in its configuration.")
  80. }
  81. let modelResourceName = modelResourceName(
  82. modelName: modelName,
  83. projectID: projectID,
  84. location: location
  85. )
  86. guard let apiKey = app.options.apiKey else {
  87. fatalError("The Firebase app named \"\(app.name)\" has no API key in its configuration.")
  88. }
  89. return GenerativeModel(
  90. name: modelResourceName,
  91. projectID: projectID,
  92. apiKey: apiKey,
  93. generationConfig: generationConfig,
  94. safetySettings: safetySettings,
  95. tools: tools,
  96. toolConfig: toolConfig,
  97. systemInstruction: systemInstruction,
  98. requestOptions: requestOptions,
  99. appCheck: appCheck,
  100. auth: auth
  101. )
  102. }
  103. // MARK: - Private
  104. /// The `FirebaseApp` associated with this `VertexAI` instance.
  105. private let app: FirebaseApp
  106. private let appCheck: AppCheckInterop?
  107. private let auth: AuthInterop?
  108. let location: String
  109. init(app: FirebaseApp, location: String) {
  110. self.app = app
  111. self.location = location
  112. appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self, in: app.container)
  113. auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  114. }
  115. private func modelResourceName(modelName: String, projectID: String, location: String) -> String {
  116. guard !modelName.isEmpty && modelName
  117. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  118. fatalError("""
  119. Invalid model name "\(modelName)" specified; see \
  120. https://firebase.google.com/docs/vertex-ai/gemini-model#available-models for a list of \
  121. available models.
  122. """)
  123. }
  124. guard !location.isEmpty && location
  125. .allSatisfy({ !$0.isWhitespace && !$0.isNewline && $0 != "/" }) else {
  126. fatalError("""
  127. Invalid location "\(location)" specified; see \
  128. https://firebase.google.com/docs/vertex-ai/locations?platform=ios#available-locations \
  129. for a list of available locations.
  130. """)
  131. }
  132. return "projects/\(projectID)/locations/\(location)/publishers/google/models/\(modelName)"
  133. }
  134. }