GenerativeModel.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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"`; see
  43. /// [Gemini models](https://ai.google.dev/models/gemini) for a list of supported model names.
  44. /// - apiKey: The API key for your project.
  45. /// - generationConfig: The content generation parameters your model should use.
  46. /// - safetySettings: A value describing what types of harmful content your model should allow.
  47. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  48. /// - toolConfig: Tool configuration for any `Tool` specified in the request.
  49. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  50. /// only text content is supported.
  51. /// - requestOptions: Configuration parameters for sending requests to the backend.
  52. /// - urlSession: The `URLSession` to use for requests; defaults to `URLSession.shared`.
  53. init(name: String,
  54. apiKey: String,
  55. generationConfig: GenerationConfig? = nil,
  56. safetySettings: [SafetySetting]? = nil,
  57. tools: [Tool]?,
  58. toolConfig: ToolConfig? = nil,
  59. systemInstruction: ModelContent? = nil,
  60. requestOptions: RequestOptions,
  61. appCheck: AppCheckInterop?,
  62. auth: AuthInterop?,
  63. urlSession: URLSession = .shared) {
  64. modelResourceName = GenerativeModel.modelResourceName(name: name)
  65. generativeAIService = GenerativeAIService(
  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...)
  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])
  176. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  177. let evaluatedContent: [ModelContent]
  178. do {
  179. evaluatedContent = try content()
  180. } catch let underlying {
  181. return AsyncThrowingStream { continuation in
  182. let error: Error
  183. if let contentError = underlying as? ImageConversionError {
  184. error = GenerateContentError.promptImageContentError(underlying: contentError)
  185. } else {
  186. error = GenerateContentError.internalError(underlying: underlying)
  187. }
  188. continuation.finish(throwing: error)
  189. }
  190. }
  191. let generateContentRequest = GenerateContentRequest(model: modelResourceName,
  192. contents: evaluatedContent,
  193. generationConfig: generationConfig,
  194. safetySettings: safetySettings,
  195. tools: tools,
  196. toolConfig: toolConfig,
  197. systemInstruction: systemInstruction,
  198. isStreaming: true,
  199. options: requestOptions)
  200. var responseIterator = generativeAIService.loadRequestStream(request: generateContentRequest)
  201. .makeAsyncIterator()
  202. return AsyncThrowingStream {
  203. let response: GenerateContentResponse?
  204. do {
  205. response = try await responseIterator.next()
  206. } catch {
  207. throw GenerativeModel.generateContentError(from: error)
  208. }
  209. // The responseIterator will return `nil` when it's done.
  210. guard let response = response else {
  211. // This is the end of the stream! Signal it by sending `nil`.
  212. return nil
  213. }
  214. // Check the prompt feedback to see if the prompt was blocked.
  215. if response.promptFeedback?.blockReason != nil {
  216. throw GenerateContentError.promptBlocked(response: response)
  217. }
  218. // If the stream ended early unexpectedly, throw an error.
  219. if let finishReason = response.candidates.first?.finishReason, finishReason != .stop {
  220. throw GenerateContentError.responseStoppedEarly(reason: finishReason, response: response)
  221. } else {
  222. // Response was valid content, pass it along and continue.
  223. return response
  224. }
  225. }
  226. }
  227. /// Creates a new chat conversation using this model with the provided history.
  228. public func startChat(history: [ModelContent] = []) -> Chat {
  229. return Chat(model: self, history: history)
  230. }
  231. /// Runs the model's tokenizer on String and/or image inputs that are representable as one or more
  232. /// ``ModelContent/Part``s.
  233. ///
  234. /// Since ``ModelContent/Part``s do not specify a role, this method is intended for tokenizing
  235. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  236. /// or "direct" prompts. For
  237. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  238. /// input, see `countTokens(_ content: @autoclosure () throws -> [ModelContent])`.
  239. ///
  240. /// - Parameter content: The input(s) given to the model as a prompt (see
  241. /// ``ThrowingPartsRepresentable``
  242. /// for conforming types).
  243. /// - Returns: The results of running the model's tokenizer on the input; contains
  244. /// ``CountTokensResponse/totalTokens``.
  245. /// - Throws: A ``CountTokensError`` if the tokenization request failed.
  246. public func countTokens(_ parts: any ThrowingPartsRepresentable...) async throws
  247. -> CountTokensResponse {
  248. return try await countTokens([ModelContent(parts: parts)])
  249. }
  250. /// Runs the model's tokenizer on the input content and returns the token count.
  251. ///
  252. /// - Parameter content: The input given to the model as a prompt.
  253. /// - Returns: The results of running the model's tokenizer on the input; contains
  254. /// ``CountTokensResponse/totalTokens``.
  255. /// - Throws: A ``CountTokensError`` if the tokenization request failed or the input content was
  256. /// invalid.
  257. public func countTokens(_ content: @autoclosure () throws -> [ModelContent]) async throws
  258. -> CountTokensResponse {
  259. do {
  260. let countTokensRequest = try CountTokensRequest(
  261. model: modelResourceName,
  262. contents: content(),
  263. options: requestOptions
  264. )
  265. return try await generativeAIService.loadRequest(request: countTokensRequest)
  266. } catch {
  267. throw CountTokensError.internalError(underlying: error)
  268. }
  269. }
  270. /// Returns a model resource name of the form "models/model-name" based on `name`.
  271. private static func modelResourceName(name: String) -> String {
  272. if name.contains("/") {
  273. return name
  274. } else {
  275. return modelResourcePrefix + name
  276. }
  277. }
  278. /// Returns a `GenerateContentError` (for public consumption) from an internal error.
  279. ///
  280. /// If `error` is already a `GenerateContentError` the error is returned unchanged.
  281. private static func generateContentError(from error: Error) -> GenerateContentError {
  282. if let error = error as? GenerateContentError {
  283. return error
  284. }
  285. return GenerateContentError.internalError(underlying: error)
  286. }
  287. }
  288. /// An error thrown in `GenerativeModel.countTokens(_:)`.
  289. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
  290. public enum CountTokensError: Error {
  291. case internalError(underlying: Error)
  292. }