Chat.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 Foundation
  15. /// An object that represents a back-and-forth chat with a model, capturing the history and saving
  16. /// the context in memory between each message sent.
  17. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, *)
  18. public class Chat {
  19. private let model: GenerativeModel
  20. /// Initializes a new chat representing a 1:1 conversation between model and user.
  21. init(model: GenerativeModel, history: [ModelContent]) {
  22. self.model = model
  23. self.history = history
  24. }
  25. /// The previous content from the chat that has been successfully sent and received from the
  26. /// model. This will be provided to the model for each message sent as context for the discussion.
  27. public var history: [ModelContent]
  28. /// See ``sendMessage(_:)-3ify5``.
  29. public func sendMessage(_ parts: any ThrowingPartsRepresentable...) async throws
  30. -> GenerateContentResponse {
  31. return try await sendMessage([ModelContent(parts: parts)])
  32. }
  33. /// Sends a message using the existing history of this chat as context. If successful, the message
  34. /// and response will be added to the history. If unsuccessful, history will remain unchanged.
  35. /// - Parameter content: The new content to send as a single chat message.
  36. /// - Returns: The model's response if no error occurred.
  37. /// - Throws: A ``GenerateContentError`` if an error occurred.
  38. public func sendMessage(_ content: @autoclosure () throws -> [ModelContent]) async throws
  39. -> GenerateContentResponse {
  40. // Ensure that the new content has the role set.
  41. let newContent: [ModelContent]
  42. do {
  43. newContent = try content().map(populateContentRole(_:))
  44. } catch let underlying {
  45. if let contentError = underlying as? ImageConversionError {
  46. throw GenerateContentError.promptImageContentError(underlying: contentError)
  47. } else {
  48. throw GenerateContentError.internalError(underlying: underlying)
  49. }
  50. }
  51. // Send the history alongside the new message as context.
  52. let request = history + newContent
  53. let result = try await model.generateContent(request)
  54. guard let reply = result.candidates.first?.content else {
  55. let error = NSError(domain: "com.google.generative-ai",
  56. code: -1,
  57. userInfo: [
  58. NSLocalizedDescriptionKey: "No candidates with content available.",
  59. ])
  60. throw GenerateContentError.internalError(underlying: error)
  61. }
  62. // Make sure we inject the role into the content received.
  63. let toAdd = ModelContent(role: "model", parts: reply.parts)
  64. // Append the request and successful result to history, then return the value.
  65. history.append(contentsOf: newContent)
  66. history.append(toAdd)
  67. return result
  68. }
  69. /// See ``sendMessageStream(_:)-4abs3``.
  70. @available(macOS 12.0, *)
  71. public func sendMessageStream(_ parts: any ThrowingPartsRepresentable...)
  72. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  73. return try sendMessageStream([ModelContent(parts: parts)])
  74. }
  75. /// Sends a message using the existing history of this chat as context. If successful, the message
  76. /// and response will be added to the history. If unsuccessful, history will remain unchanged.
  77. /// - Parameter content: The new content to send as a single chat message.
  78. /// - Returns: A stream containing the model's response or an error if an error occurred.
  79. @available(macOS 12.0, *)
  80. public func sendMessageStream(_ content: @autoclosure () throws -> [ModelContent])
  81. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  82. let resolvedContent: [ModelContent]
  83. do {
  84. resolvedContent = try content()
  85. } catch let underlying {
  86. return AsyncThrowingStream { continuation in
  87. let error: Error
  88. if let contentError = underlying as? ImageConversionError {
  89. error = GenerateContentError.promptImageContentError(underlying: contentError)
  90. } else {
  91. error = GenerateContentError.internalError(underlying: underlying)
  92. }
  93. continuation.finish(throwing: error)
  94. }
  95. }
  96. return AsyncThrowingStream { continuation in
  97. Task {
  98. var aggregatedContent: [ModelContent] = []
  99. // Ensure that the new content has the role set.
  100. let newContent: [ModelContent] = resolvedContent.map(populateContentRole(_:))
  101. // Send the history alongside the new message as context.
  102. let request = history + newContent
  103. let stream = model.generateContentStream(request)
  104. do {
  105. for try await chunk in stream {
  106. // Capture any content that's streaming. This should be populated if there's no error.
  107. if let chunkContent = chunk.candidates.first?.content {
  108. aggregatedContent.append(chunkContent)
  109. }
  110. // Pass along the chunk.
  111. continuation.yield(chunk)
  112. }
  113. } catch {
  114. // Rethrow the error that the underlying stream threw. Don't add anything to history.
  115. continuation.finish(throwing: error)
  116. return
  117. }
  118. // Save the request.
  119. history.append(contentsOf: newContent)
  120. // Aggregate the content to add it to the history before we finish.
  121. let aggregated = aggregatedChunks(aggregatedContent)
  122. history.append(aggregated)
  123. continuation.finish()
  124. }
  125. }
  126. }
  127. private func aggregatedChunks(_ chunks: [ModelContent]) -> ModelContent {
  128. var parts: [ModelContent.Part] = []
  129. var combinedText = ""
  130. for aggregate in chunks {
  131. // Loop through all the parts, aggregating the text and adding the images.
  132. for part in aggregate.parts {
  133. switch part {
  134. case let .text(str):
  135. combinedText += str
  136. case .data, .functionCall, .functionResponse:
  137. // Don't combine it, just add to the content. If there's any text pending, add that as
  138. // a part.
  139. if !combinedText.isEmpty {
  140. parts.append(.text(combinedText))
  141. combinedText = ""
  142. }
  143. parts.append(part)
  144. }
  145. }
  146. }
  147. if !combinedText.isEmpty {
  148. parts.append(.text(combinedText))
  149. }
  150. return ModelContent(role: "model", parts: parts)
  151. }
  152. /// Populates the `role` field with `user` if it doesn't exist. Required in chat sessions.
  153. private func populateContentRole(_ content: ModelContent) -> ModelContent {
  154. if content.role != nil {
  155. return content
  156. } else {
  157. return ModelContent(role: "user", parts: content.parts)
  158. }
  159. }
  160. }