forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatGPTMemory.swift
More file actions
62 lines (55 loc) · 1.8 KB
/
ChatGPTMemory.swift
File metadata and controls
62 lines (55 loc) · 1.8 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
import Foundation
import GPTEncoder
public protocol ChatGPTMemory {
/// The visible messages to the ChatGPT service.
var messages: [ChatMessage] { get async }
/// The remaining tokens available for the reply.
var remainingTokens: Int? { get async }
/// Update the message history.
func mutateHistory(_ update: (inout [ChatMessage]) -> Void) async
}
public extension ChatGPTMemory {
/// Append a message to the history.
func appendMessage(_ message: ChatMessage) async {
await mutateHistory {
$0.append(message)
}
}
/// Update a message in the history.
func updateMessage(id: String, _ update: (inout ChatMessage) -> Void) async {
await mutateHistory { history in
if let index = history.firstIndex(where: { $0.id == id }) {
update(&history[index])
}
}
}
/// Remove a message from the history.
func removeMessage(_ id: String) async {
await mutateHistory {
$0.removeAll { $0.id == id }
}
}
/// Stream a message to the history.
func streamMessage(id: String, role: ChatMessage.Role?, content: String?) async {
await mutateHistory { history in
if let index = history.firstIndex(where: { $0.id == id }) {
if let content {
history[index].content.append(content)
}
if let role {
history[index].role = role
}
} else {
history.append(.init(
id: id,
role: role ?? .system,
content: content ?? ""
))
}
}
}
/// Clear the history.
func clearHistory() async {
await mutateHistory { $0.removeAll() }
}
}