GenerativeModel.swift 14 KB

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