TemplateChatSession.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. // Copyright 2025 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. // TODO: Restore `public` to class and methods when determined to be releaseable.
  16. /// A chat session that allows for conversation with a model.
  17. ///
  18. /// **Public Preview**: This API is a public preview and may be subject to change.
  19. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  20. final class TemplateChatSession: Sendable {
  21. private let model: TemplateGenerativeModel
  22. private let templateID: String
  23. private let _history: History
  24. init(model: TemplateGenerativeModel, templateID: String, history: [ModelContent]) {
  25. self.model = model
  26. self.templateID = templateID
  27. _history = History(history: history)
  28. }
  29. public var history: [ModelContent] {
  30. get {
  31. return _history.history
  32. }
  33. set {
  34. _history.history = newValue
  35. }
  36. }
  37. /// Sends a message to the model and returns the response.
  38. ///
  39. /// **Public Preview**: This API is a public preview and may be subject to change.
  40. ///
  41. /// - Parameters:
  42. /// - content: The message to send to the model.
  43. /// - inputs: A dictionary of variables to substitute into the template.
  44. /// - options: The ``RequestOptions`` for the request, currently used to override default
  45. /// request timeout.
  46. /// - Returns: The content generated by the model.
  47. /// - Throws: A ``GenerateContentError`` if the request failed.
  48. func sendMessage(_ content: [ModelContent],
  49. inputs: [String: Any],
  50. options: RequestOptions = RequestOptions()) async throws
  51. -> GenerateContentResponse {
  52. let templateInputs = try inputs.mapValues { try TemplateInput(value: $0) }
  53. let newContent = content.map(populateContentRole)
  54. let response = try await model.generateContentWithHistory(
  55. history: _history.history + newContent,
  56. template: templateID,
  57. inputs: templateInputs,
  58. options: options
  59. )
  60. _history.append(contentsOf: newContent)
  61. if let modelResponse = response.candidates.first {
  62. _history.append(modelResponse.content)
  63. }
  64. return response
  65. }
  66. /// Sends a message to the model and returns the response.
  67. ///
  68. /// **Public Preview**: This API is a public preview and may be subject to change.
  69. ///
  70. /// - Parameters:
  71. /// - message: The message to send to the model.
  72. /// - inputs: A dictionary of variables to substitute into the template.
  73. /// - options: The ``RequestOptions`` for the request, currently used to override default
  74. /// request timeout.
  75. /// - Returns: The content generated by the model.
  76. /// - Throws: A ``GenerateContentError`` if the request failed.
  77. func sendMessage(_ message: any PartsRepresentable,
  78. inputs: [String: Any],
  79. options: RequestOptions = RequestOptions()) async throws
  80. -> GenerateContentResponse {
  81. return try await sendMessage([ModelContent(parts: message.partsValue)],
  82. inputs: inputs,
  83. options: options)
  84. }
  85. /// Sends a message to the model and returns the response as a stream of
  86. /// `GenerateContentResponse`s.
  87. ///
  88. /// **Public Preview**: This API is a public preview and may be subject to change.
  89. ///
  90. /// - Parameters:
  91. /// - content: The message to send to the model.
  92. /// - inputs: A dictionary of variables to substitute into the template.
  93. /// - options: The ``RequestOptions`` for the request, currently used to override default
  94. /// request timeout.
  95. /// - Returns: An `AsyncThrowingStream` that yields `GenerateContentResponse` objects.
  96. /// - Throws: A ``GenerateContentError`` if the request failed.
  97. func sendMessageStream(_ content: [ModelContent],
  98. inputs: [String: Any],
  99. options: RequestOptions = RequestOptions()) throws
  100. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  101. let templateInputs = try inputs.mapValues { try TemplateInput(value: $0) }
  102. let newContent = content.map(populateContentRole)
  103. let stream = try model.generateContentStreamWithHistory(
  104. history: _history.history + newContent,
  105. template: templateID,
  106. inputs: templateInputs,
  107. options: options
  108. )
  109. return AsyncThrowingStream { continuation in
  110. Task {
  111. var aggregatedContent: [ModelContent] = []
  112. do {
  113. for try await chunk in stream {
  114. // Capture any content that's streaming. This should be populated if there's no error.
  115. if let chunkContent = chunk.candidates.first?.content {
  116. aggregatedContent.append(chunkContent)
  117. }
  118. // Pass along the chunk.
  119. continuation.yield(chunk)
  120. }
  121. } catch {
  122. // Rethrow the error that the underlying stream threw. Don't add anything to history.
  123. continuation.finish(throwing: error)
  124. return
  125. }
  126. // Save the request.
  127. _history.append(contentsOf: newContent)
  128. // Aggregate the content to add it to the history before we finish.
  129. let aggregated = _history.aggregatedChunks(aggregatedContent)
  130. _history.append(aggregated)
  131. continuation.finish()
  132. }
  133. }
  134. }
  135. /// Sends a message to the model and returns the response as a stream of
  136. /// `GenerateContentResponse`s.
  137. ///
  138. /// **Public Preview**: This API is a public preview and may be subject to change.
  139. ///
  140. /// - Parameters:
  141. /// - message: The message to send to the model.
  142. /// - inputs: A dictionary of variables to substitute into the template.
  143. /// - options: The ``RequestOptions`` for the request, currently used to override default
  144. /// request timeout.
  145. /// - Returns: An `AsyncThrowingStream` that yields `GenerateContentResponse` objects.
  146. /// - Throws: A ``GenerateContentError`` if the request failed.
  147. func sendMessageStream(_ message: any PartsRepresentable,
  148. inputs: [String: Any],
  149. options: RequestOptions = RequestOptions()) throws
  150. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  151. return try sendMessageStream([ModelContent(parts: message.partsValue)],
  152. inputs: inputs,
  153. options: options)
  154. }
  155. private func populateContentRole(_ content: ModelContent) -> ModelContent {
  156. if content.role != nil {
  157. return content
  158. } else {
  159. return ModelContent(role: "user", parts: content.parts)
  160. }
  161. }
  162. }