GenerativeModel.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // Copyright 2023 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 Foundation
  17. /// A type that represents a remote multimodal model (like Gemini), with the ability to generate
  18. /// content based on various input types.
  19. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  20. public final class GenerativeModel: Sendable {
  21. /// The resource name of the model in the backend; has the format "models/model-name".
  22. let modelResourceName: String
  23. /// The backing service responsible for sending and receiving model requests to the backend.
  24. let generativeAIService: GenerativeAIService
  25. /// Configuration parameters used for the MultiModalModel.
  26. let generationConfig: GenerationConfig?
  27. /// The safety settings to be used for prompts.
  28. let safetySettings: [SafetySetting]?
  29. /// A list of tools the model may use to generate the next response.
  30. let tools: [Tool]?
  31. /// Tool configuration for any `Tool` specified in the request.
  32. let toolConfig: ToolConfig?
  33. /// Instructions that direct the model to behave a certain way.
  34. let systemInstruction: ModelContent?
  35. /// Configuration parameters for sending requests to the backend.
  36. let requestOptions: RequestOptions
  37. /// Initializes a new remote model with the given parameters.
  38. ///
  39. /// - Parameters:
  40. /// - name: The name of the model to use, for example `"gemini-1.0-pro"`.
  41. /// - projectID: The project ID from the Firebase console.
  42. /// - apiKey: The API key for your project.
  43. /// - generationConfig: The content generation parameters your model should use.
  44. /// - safetySettings: A value describing what types of harmful content your model should allow.
  45. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  46. /// - toolConfig: Tool configuration for any `Tool` specified in the request.
  47. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  48. /// only text content is supported.
  49. /// - requestOptions: Configuration parameters for sending requests to the backend.
  50. /// - urlSession: The `URLSession` to use for requests; defaults to `URLSession.shared`.
  51. init(name: String,
  52. firebaseInfo: FirebaseInfo,
  53. generationConfig: GenerationConfig? = nil,
  54. safetySettings: [SafetySetting]? = nil,
  55. tools: [Tool]?,
  56. toolConfig: ToolConfig? = nil,
  57. systemInstruction: ModelContent? = nil,
  58. requestOptions: RequestOptions,
  59. urlSession: URLSession = .shared) {
  60. modelResourceName = name
  61. generativeAIService = GenerativeAIService(
  62. firebaseInfo: firebaseInfo,
  63. urlSession: urlSession
  64. )
  65. self.generationConfig = generationConfig
  66. self.safetySettings = safetySettings
  67. self.tools = tools
  68. self.toolConfig = toolConfig
  69. self.systemInstruction = systemInstruction
  70. self.requestOptions = requestOptions
  71. if VertexLog.additionalLoggingEnabled() {
  72. VertexLog.debug(code: .verboseLoggingEnabled, "Verbose logging enabled.")
  73. } else {
  74. VertexLog.info(code: .verboseLoggingDisabled, """
  75. [FirebaseVertexAI] To enable additional logging, add \
  76. `\(VertexLog.enableArgumentKey)` as a launch argument in Xcode.
  77. """)
  78. }
  79. VertexLog.debug(code: .generativeModelInitialized, "Model \(name) initialized.")
  80. }
  81. /// Generates content from String and/or image inputs, given to the model as a prompt, that are
  82. /// representable as one or more ``Part``s.
  83. ///
  84. /// Since ``Part``s do not specify a role, this method is intended for generating content from
  85. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  86. /// or "direct" prompts. For
  87. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  88. /// prompts, see `generateContent(_ content: [ModelContent])`.
  89. ///
  90. /// - Parameters:
  91. /// - parts: The input(s) given to the model as a prompt (see ``PartsRepresentable`` for
  92. /// conforming types).
  93. /// - Returns: The content generated by the model.
  94. /// - Throws: A ``GenerateContentError`` if the request failed.
  95. public func generateContent(_ parts: any PartsRepresentable...)
  96. async throws -> GenerateContentResponse {
  97. return try await generateContent([ModelContent(parts: parts)])
  98. }
  99. /// Generates new content from input content given to the model as a prompt.
  100. ///
  101. /// - Parameter content: The input(s) given to the model as a prompt.
  102. /// - Returns: The generated content response from the model.
  103. /// - Throws: A ``GenerateContentError`` if the request failed.
  104. public func generateContent(_ content: [ModelContent]) async throws
  105. -> GenerateContentResponse {
  106. try content.throwIfError()
  107. let response: GenerateContentResponse
  108. let generateContentRequest = GenerateContentRequest(model: modelResourceName,
  109. contents: content,
  110. generationConfig: generationConfig,
  111. safetySettings: safetySettings,
  112. tools: tools,
  113. toolConfig: toolConfig,
  114. systemInstruction: systemInstruction,
  115. isStreaming: false,
  116. options: requestOptions)
  117. do {
  118. response = try await generativeAIService.loadRequest(request: generateContentRequest)
  119. } catch {
  120. throw GenerativeModel.generateContentError(from: error)
  121. }
  122. // Check the prompt feedback to see if the prompt was blocked.
  123. if response.promptFeedback?.blockReason != nil {
  124. throw GenerateContentError.promptBlocked(response: response)
  125. }
  126. // Check to see if an error should be thrown for stop reason.
  127. if let reason = response.candidates.first?.finishReason, reason != .stop {
  128. throw GenerateContentError.responseStoppedEarly(reason: reason, response: response)
  129. }
  130. return response
  131. }
  132. /// Generates content from String and/or image inputs, given to the model as a prompt, that are
  133. /// representable as one or more ``Part``s.
  134. ///
  135. /// Since ``Part``s do not specify a role, this method is intended for generating content from
  136. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  137. /// or "direct" prompts. For
  138. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  139. /// prompts, see `generateContentStream(_ content: @autoclosure () throws -> [ModelContent])`.
  140. ///
  141. /// - Parameters:
  142. /// - parts: The input(s) given to the model as a prompt (see ``PartsRepresentable`` for
  143. /// conforming types).
  144. /// - Returns: A stream wrapping content generated by the model or a ``GenerateContentError``
  145. /// error if an error occurred.
  146. @available(macOS 12.0, *)
  147. public func generateContentStream(_ parts: any PartsRepresentable...) throws
  148. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  149. return try generateContentStream([ModelContent(parts: parts)])
  150. }
  151. /// Generates new content from input content given to the model as a prompt.
  152. ///
  153. /// - Parameter content: The input(s) given to the model as a prompt.
  154. /// - Returns: A stream wrapping content generated by the model or a ``GenerateContentError``
  155. /// error if an error occurred.
  156. @available(macOS 12.0, *)
  157. public func generateContentStream(_ content: [ModelContent]) throws
  158. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  159. try content.throwIfError()
  160. let generateContentRequest = GenerateContentRequest(model: modelResourceName,
  161. contents: content,
  162. generationConfig: generationConfig,
  163. safetySettings: safetySettings,
  164. tools: tools,
  165. toolConfig: toolConfig,
  166. systemInstruction: systemInstruction,
  167. isStreaming: true,
  168. options: requestOptions)
  169. var responseIterator = generativeAIService.loadRequestStream(request: generateContentRequest)
  170. .makeAsyncIterator()
  171. return AsyncThrowingStream {
  172. let response: GenerateContentResponse?
  173. do {
  174. response = try await responseIterator.next()
  175. } catch {
  176. throw GenerativeModel.generateContentError(from: error)
  177. }
  178. // The responseIterator will return `nil` when it's done.
  179. guard let response = response else {
  180. // This is the end of the stream! Signal it by sending `nil`.
  181. return nil
  182. }
  183. // Check the prompt feedback to see if the prompt was blocked.
  184. if response.promptFeedback?.blockReason != nil {
  185. throw GenerateContentError.promptBlocked(response: response)
  186. }
  187. // If the stream ended early unexpectedly, throw an error.
  188. if let finishReason = response.candidates.first?.finishReason, finishReason != .stop {
  189. throw GenerateContentError.responseStoppedEarly(reason: finishReason, response: response)
  190. } else {
  191. // Response was valid content, pass it along and continue.
  192. return response
  193. }
  194. }
  195. }
  196. /// Creates a new chat conversation using this model with the provided history.
  197. public func startChat(history: [ModelContent] = []) -> Chat {
  198. return Chat(model: self, history: history)
  199. }
  200. /// Runs the model's tokenizer on String and/or image inputs that are representable as one or more
  201. /// ``Part``s.
  202. ///
  203. /// Since ``Part``s do not specify a role, this method is intended for tokenizing
  204. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  205. /// or "direct" prompts. For
  206. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  207. /// input, see `countTokens(_ content: @autoclosure () throws -> [ModelContent])`.
  208. ///
  209. /// - Parameters:
  210. /// - parts: The input(s) given to the model as a prompt (see ``PartsRepresentable`` for
  211. /// conforming types).
  212. /// - Returns: The results of running the model's tokenizer on the input; contains
  213. /// ``CountTokensResponse/totalTokens``.
  214. public func countTokens(_ parts: any PartsRepresentable...) async throws -> CountTokensResponse {
  215. return try await countTokens([ModelContent(parts: parts)])
  216. }
  217. /// Runs the model's tokenizer on the input content and returns the token count.
  218. ///
  219. /// - Parameter content: The input given to the model as a prompt.
  220. /// - Returns: The results of running the model's tokenizer on the input; contains
  221. /// ``CountTokensResponse/totalTokens``.
  222. public func countTokens(_ content: [ModelContent]) async throws -> CountTokensResponse {
  223. let countTokensRequest = CountTokensRequest(
  224. model: modelResourceName,
  225. contents: content,
  226. systemInstruction: systemInstruction,
  227. tools: tools,
  228. generationConfig: generationConfig,
  229. options: requestOptions
  230. )
  231. return try await generativeAIService.loadRequest(request: countTokensRequest)
  232. }
  233. /// Returns a `GenerateContentError` (for public consumption) from an internal error.
  234. ///
  235. /// If `error` is already a `GenerateContentError` the error is returned unchanged.
  236. private static func generateContentError(from error: Error) -> GenerateContentError {
  237. if let error = error as? GenerateContentError {
  238. return error
  239. }
  240. return GenerateContentError.internalError(underlying: error)
  241. }
  242. }