GenerativeModel.swift 14 KB

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