-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathChatMemory.swift
More file actions
72 lines (59 loc) · 2.14 KB
/
ChatMemory.swift
File metadata and controls
72 lines (59 loc) · 2.14 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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].mergeMessage(with: message)
} 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() }
}
}
extension ChatMessage {
mutating func mergeMessage(with message: ChatMessage) {
// merge content
self.content = self.content + message.content
// merge references
var seen = Set<ConversationReference>()
// without duplicated and keep order
self.references = (self.references + message.references).filter { seen.insert($0).inserted }
// merge followUp
self.followUp = message.followUp ?? self.followUp
// merge suggested title
self.suggestedTitle = message.suggestedTitle ?? self.suggestedTitle
// merge error message
if let errorMessage = message.errorMessage {
self.errorMessage = (self.errorMessage ?? "") + errorMessage
}
// merge steps
if !message.steps.isEmpty {
var mergedSteps = self.steps
for newStep in message.steps {
if let index = mergedSteps.firstIndex(where: { $0.id == newStep.id }) {
mergedSteps[index] = newStep
} else {
mergedSteps.append(newStep)
}
}
self.steps = mergedSteps
}
}
}