GenerativeModel.swift 14 KB

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