GenerativeModel.swift 14 KB

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