GenerativeModel.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  20. public final class GenerativeModel: Sendable {
  21. /// Model name prefix to identify Gemini models.
  22. static let geminiModelNamePrefix = "gemini-"
  23. /// The resource name of the model in the backend; has the format "models/model-name".
  24. let modelResourceName: String
  25. /// Configuration for the backend API used by this model.
  26. let apiConfig: APIConfig
  27. /// The backing service responsible for sending and receiving model requests to the backend.
  28. let generativeAIService: GenerativeAIService
  29. /// Configuration parameters used for the MultiModalModel.
  30. let generationConfig: GenerationConfig?
  31. /// The safety settings to be used for prompts.
  32. let safetySettings: [SafetySetting]?
  33. /// A list of tools the model may use to generate the next response.
  34. let tools: [Tool]?
  35. /// Tool configuration for any `Tool` specified in the request.
  36. let toolConfig: ToolConfig?
  37. /// Instructions that direct the model to behave a certain way.
  38. let systemInstruction: ModelContent?
  39. /// Configuration parameters for sending requests to the backend.
  40. let requestOptions: RequestOptions
  41. /// Initializes a new remote model with the given parameters.
  42. ///
  43. /// - Parameters:
  44. /// - modelResourceName: The resource name of the model to use, for example
  45. /// `"projects/{project-id}/locations/{location-id}/publishers/google/models/{model-name}"`.
  46. /// - firebaseInfo: Firebase data used by the SDK, including project ID and API key.
  47. /// - apiConfig: Configuration for the backend API used by this model.
  48. /// - generationConfig: The content generation parameters your model should use.
  49. /// - safetySettings: A value describing what types of harmful content your model should allow.
  50. /// - tools: A list of ``Tool`` objects that the model may use to generate the next response.
  51. /// - toolConfig: Tool configuration for any `Tool` specified in the request.
  52. /// - systemInstruction: Instructions that direct the model to behave a certain way; currently
  53. /// only text content is supported.
  54. /// - requestOptions: Configuration parameters for sending requests to the backend.
  55. /// - urlSession: The `URLSession` to use for requests; defaults to `URLSession.shared`.
  56. init(modelResourceName: String,
  57. firebaseInfo: FirebaseInfo,
  58. apiConfig: APIConfig,
  59. generationConfig: GenerationConfig? = nil,
  60. safetySettings: [SafetySetting]? = nil,
  61. tools: [Tool]?,
  62. toolConfig: ToolConfig? = nil,
  63. systemInstruction: ModelContent? = nil,
  64. requestOptions: RequestOptions,
  65. urlSession: URLSession = .shared) {
  66. self.modelResourceName = modelResourceName
  67. self.apiConfig = apiConfig
  68. generativeAIService = GenerativeAIService(
  69. firebaseInfo: firebaseInfo,
  70. urlSession: urlSession
  71. )
  72. self.generationConfig = generationConfig
  73. self.safetySettings = safetySettings
  74. self.tools = tools
  75. self.toolConfig = toolConfig
  76. self.systemInstruction = systemInstruction.map {
  77. // The `role` defaults to "user" but is ignored in system instructions. However, it is
  78. // erroneously counted towards the prompt and total token count in `countTokens` when using
  79. // the Developer API backend; set to `nil` to avoid token count discrepancies between
  80. // `countTokens` and `generateContent`.
  81. ModelContent(role: nil, parts: $0.parts)
  82. }
  83. self.requestOptions = requestOptions
  84. if VertexLog.additionalLoggingEnabled() {
  85. VertexLog.debug(code: .verboseLoggingEnabled, "Verbose logging enabled.")
  86. } else {
  87. VertexLog.info(code: .verboseLoggingDisabled, """
  88. [FirebaseVertexAI] To enable additional logging, add \
  89. `\(VertexLog.enableArgumentKey)` as a launch argument in Xcode.
  90. """)
  91. }
  92. VertexLog.debug(code: .generativeModelInitialized, "Model \(modelResourceName) 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 ``Part``s.
  96. ///
  97. /// Since ``Part``s do not specify a role, this method is intended for generating content from
  98. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  99. /// or "direct" prompts. For
  100. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  101. /// prompts, see `generateContent(_ content: [ModelContent])`.
  102. ///
  103. /// - Parameters:
  104. /// - parts: The input(s) given to the model as a prompt (see ``PartsRepresentable`` for
  105. /// conforming types).
  106. /// - Returns: The content generated by the model.
  107. /// - Throws: A ``GenerateContentError`` if the request failed.
  108. public func generateContent(_ parts: any PartsRepresentable...)
  109. async throws -> GenerateContentResponse {
  110. return try await generateContent([ModelContent(parts: parts)])
  111. }
  112. /// Generates new content from input content given to the model as a prompt.
  113. ///
  114. /// - Parameter content: The input(s) given to the model as a prompt.
  115. /// - Returns: The generated content response from the model.
  116. /// - Throws: A ``GenerateContentError`` if the request failed.
  117. public func generateContent(_ content: [ModelContent]) async throws
  118. -> GenerateContentResponse {
  119. try content.throwIfError()
  120. let response: GenerateContentResponse
  121. let generateContentRequest = GenerateContentRequest(
  122. model: modelResourceName,
  123. contents: content,
  124. generationConfig: generationConfig,
  125. safetySettings: safetySettings,
  126. tools: tools,
  127. toolConfig: toolConfig,
  128. systemInstruction: systemInstruction,
  129. apiConfig: apiConfig,
  130. apiMethod: .generateContent,
  131. options: requestOptions
  132. )
  133. do {
  134. response = try await generativeAIService.loadRequest(request: generateContentRequest)
  135. } catch {
  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 ``Part``s.
  150. ///
  151. /// Since ``Part``s do not specify a role, this method is intended for generating content from
  152. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  153. /// or "direct" prompts. For
  154. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  155. /// prompts, see `generateContentStream(_ content: @autoclosure () throws -> [ModelContent])`.
  156. ///
  157. /// - Parameters:
  158. /// - parts: The input(s) given to the model as a prompt (see ``PartsRepresentable`` for
  159. /// conforming types).
  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(_ parts: any PartsRepresentable...) throws
  164. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  165. return try generateContentStream([ModelContent(parts: parts)])
  166. }
  167. /// Generates new content from input content given to the model as a prompt.
  168. ///
  169. /// - Parameter content: The input(s) given to the model as a prompt.
  170. /// - Returns: A stream wrapping content generated by the model or a ``GenerateContentError``
  171. /// error if an error occurred.
  172. @available(macOS 12.0, *)
  173. public func generateContentStream(_ content: [ModelContent]) throws
  174. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  175. try content.throwIfError()
  176. let generateContentRequest = GenerateContentRequest(
  177. model: modelResourceName,
  178. contents: content,
  179. generationConfig: generationConfig,
  180. safetySettings: safetySettings,
  181. tools: tools,
  182. toolConfig: toolConfig,
  183. systemInstruction: systemInstruction,
  184. apiConfig: apiConfig,
  185. apiMethod: .streamGenerateContent,
  186. options: requestOptions
  187. )
  188. return AsyncThrowingStream { continuation in
  189. let responseStream = generativeAIService.loadRequestStream(request: generateContentRequest)
  190. Task {
  191. do {
  192. for try await response in responseStream {
  193. // Check the prompt feedback to see if the prompt was blocked.
  194. if response.promptFeedback?.blockReason != nil {
  195. throw GenerateContentError.promptBlocked(response: response)
  196. }
  197. // If the stream ended early unexpectedly, throw an error.
  198. if let finishReason = response.candidates.first?.finishReason, finishReason != .stop {
  199. throw GenerateContentError.responseStoppedEarly(
  200. reason: finishReason,
  201. response: response
  202. )
  203. }
  204. continuation.yield(response)
  205. }
  206. continuation.finish()
  207. } catch {
  208. continuation.finish(throwing: GenerativeModel.generateContentError(from: error))
  209. return
  210. }
  211. }
  212. }
  213. }
  214. /// Creates a new chat conversation using this model with the provided history.
  215. public func startChat(history: [ModelContent] = []) -> Chat {
  216. return Chat(model: self, history: history)
  217. }
  218. /// Runs the model's tokenizer on String and/or image inputs that are representable as one or more
  219. /// ``Part``s.
  220. ///
  221. /// Since ``Part``s do not specify a role, this method is intended for tokenizing
  222. /// [zero-shot](https://developers.google.com/machine-learning/glossary/generative#zero-shot-prompting)
  223. /// or "direct" prompts. For
  224. /// [few-shot](https://developers.google.com/machine-learning/glossary/generative#few-shot-prompting)
  225. /// input, see `countTokens(_ content: @autoclosure () throws -> [ModelContent])`.
  226. ///
  227. /// - Parameters:
  228. /// - parts: The input(s) given to the model as a prompt (see ``PartsRepresentable`` for
  229. /// conforming types).
  230. /// - Returns: The results of running the model's tokenizer on the input; contains
  231. /// ``CountTokensResponse/totalTokens``.
  232. public func countTokens(_ parts: any PartsRepresentable...) async throws -> CountTokensResponse {
  233. return try await countTokens([ModelContent(parts: parts)])
  234. }
  235. /// Runs the model's tokenizer on the input content and returns the token count.
  236. ///
  237. /// - Parameter content: The input given to the model as a prompt.
  238. /// - Returns: The results of running the model's tokenizer on the input; contains
  239. /// ``CountTokensResponse/totalTokens``.
  240. public func countTokens(_ content: [ModelContent]) async throws -> CountTokensResponse {
  241. let requestContent = switch apiConfig.service {
  242. case .vertexAI:
  243. content
  244. case .developer:
  245. // The `role` defaults to "user" but is ignored in `countTokens`. However, it is erroneously
  246. // erroneously counted towards the prompt and total token count when using the Developer API
  247. // backend; set to `nil` to avoid token count discrepancies between `countTokens` and
  248. // `generateContent` and the two backend APIs.
  249. content.map { ModelContent(role: nil, parts: $0.parts) }
  250. }
  251. let generateContentRequest = GenerateContentRequest(
  252. model: modelResourceName,
  253. contents: requestContent,
  254. generationConfig: generationConfig,
  255. safetySettings: safetySettings,
  256. tools: tools,
  257. toolConfig: toolConfig,
  258. systemInstruction: systemInstruction,
  259. apiConfig: apiConfig,
  260. apiMethod: .countTokens,
  261. options: requestOptions
  262. )
  263. let countTokensRequest = CountTokensRequest(generateContentRequest: generateContentRequest)
  264. return try await generativeAIService.loadRequest(request: countTokensRequest)
  265. }
  266. /// Returns a `GenerateContentError` (for public consumption) from an internal error.
  267. ///
  268. /// If `error` is already a `GenerateContentError` the error is returned unchanged.
  269. private static func generateContentError(from error: Error) -> GenerateContentError {
  270. if let error = error as? GenerateContentError {
  271. return error
  272. }
  273. return GenerateContentError.internalError(underlying: error)
  274. }
  275. }