VertexAI.swift 5.9 KB

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