GenerativeModel.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 11.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  20. public final class GenerativeModel {
  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. projectID: String,
  53. apiKey: String,
  54. generationConfig: GenerationConfig? = nil,
  55. safetySettings: [SafetySetting]? = nil,
  56. tools: [Tool]?,
  57. toolConfig: ToolConfig? = nil,
  58. systemInstruction: ModelContent? = nil,
  59. requestOptions: RequestOptions,
  60. appCheck: AppCheckInterop?,
  61. auth: AuthInterop?,
  62. urlSession: URLSession = .shared) {
  63. modelResourceName = name
  64. generativeAIService = GenerativeAIService(
  65. projectID: projectID,
  66. apiKey: apiKey,
  67. appCheck: appCheck,
  68. auth: auth,
  69. urlSession: urlSession
  70. )
  71. self.generationConfig = generationConfig
  72. self.safetySettings = safetySettings
  73. self.tools = tools
  74. self.toolConfig = toolConfig
  75. self.systemInstruction = systemInstruction
  76. self.requestOptions = requestOptions
  77. if VertexLog.additionalLoggingEnabled() {
  78. VertexLog.debug(code: .verboseLoggingEnabled, "Verbose logging enabled.")
  79. } else {
  80. VertexLog.info(code: .verboseLoggingDisabled, """
  81. [FirebaseVertexAI] To enable additional logging, add \
  82. `\(VertexLog.enableArgumentKey)` as a launch argument in Xcode.
  83. """)
  84. }
  85. VertexLog.debug(code: .generativeModelInitialized, "Model \(name) initialized.")
  86. }
  87. /// Generates content from String and/or image inputs, given to the model as a prompt, that are
  88. /// representable as one or more ``ModelContent/Part``s.
  89. ///
  90. /// Since ``ModelContent/Part``s do not specify a role, this method is intended for generating
  91. /// content from
  92. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  93. /// or "direct" prompts. For
  94. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  95. /// prompts, see `generateContent(_ content: @autoclosure () throws -> [ModelContent])`.
  96. ///
  97. /// - Parameter content: The input(s) given to the model as a prompt (see ``PartsRepresentable``
  98. /// for conforming types).
  99. /// - Returns: The content generated by the model.
  100. /// - Throws: A ``GenerateContentError`` if the request failed.
  101. public func generateContent(_ parts: any PartsRepresentable...)
  102. async throws -> GenerateContentResponse {
  103. return try await generateContent([ModelContent(parts: parts)])
  104. }
  105. /// Generates new content from input content given to the model as a prompt.
  106. ///
  107. /// - Parameter content: The input(s) given to the model as a prompt.
  108. /// - Returns: The generated content response from the model.
  109. /// - Throws: A ``GenerateContentError`` if the request failed.
  110. public func generateContent(_ content: [ModelContent]) async throws
  111. -> GenerateContentResponse {
  112. try content.throwIfError()
  113. let response: GenerateContentResponse
  114. let generateContentRequest = GenerateContentRequest(model: modelResourceName,
  115. contents: content,
  116. generationConfig: generationConfig,
  117. safetySettings: safetySettings,
  118. tools: tools,
  119. toolConfig: toolConfig,
  120. systemInstruction: systemInstruction,
  121. isStreaming: false,
  122. options: requestOptions)
  123. do {
  124. response = try await generativeAIService.loadRequest(request: generateContentRequest)
  125. } catch {
  126. throw GenerativeModel.generateContentError(from: error)
  127. }
  128. // Check the prompt feedback to see if the prompt was blocked.
  129. if response.promptFeedback?.blockReason != nil {
  130. throw GenerateContentError.promptBlocked(response: response)
  131. }
  132. // Check to see if an error should be thrown for stop reason.
  133. if let reason = response.candidates.first?.finishReason, reason != .stop {
  134. throw GenerateContentError.responseStoppedEarly(reason: reason, response: response)
  135. }
  136. return response
  137. }
  138. /// Generates content from String and/or image inputs, given to the model as a prompt, that are
  139. /// representable as one or more ``ModelContent/Part``s.
  140. ///
  141. /// Since ``ModelContent/Part``s do not specify a role, this method is intended for generating
  142. /// content from
  143. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  144. /// or "direct" prompts. For
  145. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  146. /// prompts, see `generateContentStream(_ content: @autoclosure () throws -> [ModelContent])`.
  147. ///
  148. /// - Parameter content: The input(s) given to the model as a prompt (see
  149. /// ``PartsRepresentable`` for conforming types).
  150. /// - Returns: A stream wrapping content generated by the model or a ``GenerateContentError``
  151. /// error if an error occurred.
  152. @available(macOS 12.0, *)
  153. public func generateContentStream(_ parts: any PartsRepresentable...) throws
  154. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  155. return try generateContentStream([ModelContent(parts: parts)])
  156. }
  157. /// Generates new content from input content given to the model as a prompt.
  158. ///
  159. /// - Parameter content: The input(s) given to the model as a prompt.
  160. /// - Returns: A stream wrapping content generated by the model or a ``GenerateContentError``
  161. /// error if an error occurred.
  162. @available(macOS 12.0, *)
  163. public func generateContentStream(_ content: [ModelContent]) throws
  164. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  165. try content.throwIfError()
  166. let generateContentRequest = GenerateContentRequest(model: modelResourceName,
  167. contents: content,
  168. generationConfig: generationConfig,
  169. safetySettings: safetySettings,
  170. tools: tools,
  171. toolConfig: toolConfig,
  172. systemInstruction: systemInstruction,
  173. isStreaming: true,
  174. options: requestOptions)
  175. var responseIterator = generativeAIService.loadRequestStream(request: generateContentRequest)
  176. .makeAsyncIterator()
  177. return AsyncThrowingStream {
  178. let response: GenerateContentResponse?
  179. do {
  180. response = try await responseIterator.next()
  181. } catch {
  182. throw GenerativeModel.generateContentError(from: error)
  183. }
  184. // The responseIterator will return `nil` when it's done.
  185. guard let response = response else {
  186. // This is the end of the stream! Signal it by sending `nil`.
  187. return nil
  188. }
  189. // Check the prompt feedback to see if the prompt was blocked.
  190. if response.promptFeedback?.blockReason != nil {
  191. throw GenerateContentError.promptBlocked(response: response)
  192. }
  193. // If the stream ended early unexpectedly, throw an error.
  194. if let finishReason = response.candidates.first?.finishReason, finishReason != .stop {
  195. throw GenerateContentError.responseStoppedEarly(reason: finishReason, response: response)
  196. } else {
  197. // Response was valid content, pass it along and continue.
  198. return response
  199. }
  200. }
  201. }
  202. /// Creates a new chat conversation using this model with the provided history.
  203. public func startChat(history: [ModelContent] = []) -> Chat {
  204. return Chat(model: self, history: history)
  205. }
  206. /// Runs the model's tokenizer on String and/or image inputs that are representable as one or more
  207. /// ``ModelContent/Part``s.
  208. ///
  209. /// Since ``ModelContent/Part``s do not specify a role, this method is intended for tokenizing
  210. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  211. /// or "direct" prompts. For
  212. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  213. /// input, see `countTokens(_ content: @autoclosure () throws -> [ModelContent])`.
  214. ///
  215. /// - Parameter content: The input(s) given to the model as a prompt (see ``PartsRepresentable``
  216. /// for conforming types).
  217. /// - Returns: The results of running the model's tokenizer on the input; contains
  218. /// ``CountTokensResponse/totalTokens``.
  219. /// - Throws: A ``CountTokensError`` if the tokenization request failed.
  220. public func countTokens(_ parts: any PartsRepresentable...) async throws
  221. -> CountTokensResponse {
  222. return try await countTokens([ModelContent(parts: parts)])
  223. }
  224. /// Runs the model's tokenizer on the input content and returns the token count.
  225. ///
  226. /// - Parameter content: The input given to the model as a prompt.
  227. /// - Returns: The results of running the model's tokenizer on the input; contains
  228. /// ``CountTokensResponse/totalTokens``.
  229. /// - Throws: A ``CountTokensError`` if the tokenization request failed or the input content was
  230. /// invalid.
  231. public func countTokens(_ content: [ModelContent]) async throws
  232. -> CountTokensResponse {
  233. let countTokensRequest = CountTokensRequest(
  234. model: modelResourceName,
  235. contents: content,
  236. systemInstruction: systemInstruction,
  237. tools: tools,
  238. generationConfig: generationConfig,
  239. options: requestOptions
  240. )
  241. return try await generativeAIService.loadRequest(request: countTokensRequest)
  242. }
  243. /// Returns a `GenerateContentError` (for public consumption) from an internal error.
  244. ///
  245. /// If `error` is already a `GenerateContentError` the error is returned unchanged.
  246. private static func generateContentError(from error: Error) -> GenerateContentError {
  247. if let error = error as? GenerateContentError {
  248. return error
  249. }
  250. return GenerateContentError.internalError(underlying: error)
  251. }
  252. }