-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathChatMemory.swift
More file actions
33 lines (29 loc) · 942 Bytes
/
ChatMemory.swift
File metadata and controls
33 lines (29 loc) · 942 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import Foundation
public protocol ChatMemory {
/// The message history.
var history: [ChatMessage] { get async }
/// Update the message history.
func mutateHistory(_ update: (inout [ChatMessage]) -> Void) async
}
public extension ChatMemory {
/// Append a message to the history.
func appendMessage(_ message: ChatMessage) async {
await mutateHistory { history in
if let index = history.firstIndex(where: { $0.id == message.id }) {
history[index].content = history[index].content + message.content
} else {
history.append(message)
}
}
}
/// Remove a message from the history.
func removeMessage(_ id: String) async {
await mutateHistory {
$0.removeAll { $0.id == id }
}
}
/// Clear the history.
func clearHistory() async {
await mutateHistory { $0.removeAll() }
}
}