TemplateChatSession.swift 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // Copyright 2024 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. /// A chat session that allows for conversation with a model.
  16. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  17. public final class TemplateChatSession: Sendable {
  18. private let model: TemplateGenerativeModel
  19. private let template: String
  20. private let _history: History
  21. init(model: TemplateGenerativeModel, template: String, history: [ModelContent]) {
  22. self.model = model
  23. self.template = template
  24. _history = History(history: history)
  25. }
  26. public var history: [ModelContent] {
  27. get {
  28. return _history.history
  29. }
  30. set {
  31. _history.history = newValue
  32. }
  33. }
  34. /// Sends a message to the model and returns the response.
  35. public func sendMessage(_ message: any PartsRepresentable,
  36. variables: [String: Any],
  37. options: RequestOptions = RequestOptions()) async throws
  38. -> GenerateContentResponse {
  39. let templateVariables = try variables.mapValues { try TemplateVariable(value: $0) }
  40. let newContent = populateContentRole(ModelContent(parts: message.partsValue))
  41. let response = try await model.generateContentWithHistory(
  42. history: _history.history + [newContent],
  43. template: template,
  44. variables: templateVariables,
  45. options: options
  46. )
  47. _history.append(newContent)
  48. if let modelResponse = response.candidates.first {
  49. _history.append(modelResponse.content)
  50. }
  51. return response
  52. }
  53. public func sendMessageStream(_ message: any PartsRepresentable,
  54. variables: [String: Any],
  55. options: RequestOptions = RequestOptions()) throws
  56. -> AsyncThrowingStream<GenerateContentResponse, Error> {
  57. let templateVariables = try variables.mapValues { try TemplateVariable(value: $0) }
  58. let newContent = populateContentRole(ModelContent(parts: message.partsValue))
  59. let stream = try model.generateContentStreamWithHistory(
  60. history: _history.history + [newContent],
  61. template: template,
  62. variables: templateVariables,
  63. options: options
  64. )
  65. return AsyncThrowingStream { continuation in
  66. Task {
  67. var aggregatedContent: [ModelContent] = []
  68. do {
  69. for try await chunk in stream {
  70. // Capture any content that's streaming. This should be populated if there's no error.
  71. if let chunkContent = chunk.candidates.first?.content {
  72. aggregatedContent.append(chunkContent)
  73. }
  74. // Pass along the chunk.
  75. continuation.yield(chunk)
  76. }
  77. } catch {
  78. // Rethrow the error that the underlying stream threw. Don't add anything to history.
  79. continuation.finish(throwing: error)
  80. return
  81. }
  82. // Save the request.
  83. _history.append(newContent)
  84. // Aggregate the content to add it to the history before we finish.
  85. let aggregated = _history.aggregatedChunks(aggregatedContent)
  86. _history.append(aggregated)
  87. continuation.finish()
  88. }
  89. }
  90. }
  91. private func populateContentRole(_ content: ModelContent) -> ModelContent {
  92. if content.role != nil {
  93. return content
  94. } else {
  95. return ModelContent(role: "user", parts: content.parts)
  96. }
  97. }
  98. }