GenerativeModel.swift 14 KB

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