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
176 lines (166 loc) · 6.25 KB
/
ChatGPTMemory.swift
File metadata and controls
176 lines (166 loc) · 6.25 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import Foundation
public struct ChatGPTPrompt: Equatable {
public var history: [ChatMessage]
public var references: [ChatMessage.Reference]
public var remainingTokenCount: Int?
public init(
history: [ChatMessage],
references: [ChatMessage.Reference] = [],
remainingTokenCount: Int? = nil
) {
self.history = history
self.references = references
self.remainingTokenCount = remainingTokenCount
}
}
public protocol ChatGPTMemory {
/// The message history.
var history: [ChatMessage] { get async }
/// Update the message history.
func mutateHistory(_ update: (inout [ChatMessage]) -> Void) async
/// Generate prompt that would be send through the API.
///
/// A memory should make sure that the history in the prompt
/// doesn't exceed the maximum token count.
///
/// The history can be different from the actual history.
func generatePrompt() async -> ChatGPTPrompt
}
public extension ChatGPTMemory {
/// 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] = message
} else {
history.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 }
}
}
func streamToolCallResponse(
id: String,
toolCallId: String,
content: String? = nil,
summary: String? = nil
) async {
await updateMessage(id: id) { message in
if let index = message.toolCallContext?.responses.firstIndex(where: {
$0.id == toolCallId
}) {
if let content {
message.toolCallContext?.responses[index].content = content
}
if let summary {
message.toolCallContext?.responses[index].summary = summary
}
} else {
message.toolCallContext?.responses.append(.init(
id: toolCallId,
content: content ?? "",
summary: summary ?? ""
))
}
}
}
/// Stream a message to the history.
func streamMessage(
id: String,
role: ChatMessage.Role? = nil,
content: String? = nil,
name: String? = nil,
toolCalls: [Int: ChatMessage.ToolCall]? = nil,
summary: String? = nil,
references: [ChatMessage.Reference]? = nil
) async {
if await history.contains(where: { $0.id == id }) {
await updateMessage(id: id) { message in
if let content {
if message.content == nil {
message.content = content
} else {
message.content?.append(content)
}
}
if let role {
message.role = role
}
if let toolCalls {
if var existedToolCalls = message.toolCallContext?.toolCalls {
for pair in toolCalls.sorted(by: { $0.key <= $1.key }) {
let (proposedIndex, toolCall) = pair
let index = {
if toolCall.id.isEmpty { return proposedIndex }
return existedToolCalls.lastIndex(where: { $0.id == toolCall.id })
?? proposedIndex
}()
if index < existedToolCalls.endIndex {
if !toolCall.id.isEmpty {
existedToolCalls[index].id = toolCall.id
}
if !toolCall.type.isEmpty {
existedToolCalls[index].type = toolCall.type
}
existedToolCalls[index].function.name
.append(toolCall.function.name)
existedToolCalls[index].function.arguments
.append(toolCall.function.arguments)
} else {
existedToolCalls.append(toolCall)
}
}
message.toolCallContext?.toolCalls = existedToolCalls
} else {
message.toolCallContext = .init(
toolCalls: toolCalls.sorted(by: { $0.key <= $1.key }).map(\.value),
responses: []
)
}
}
if let summary {
message.summary = summary
}
if let references {
message.references.append(contentsOf: references)
}
if let name {
message.name = name
}
}
} else {
await mutateHistory { history in
history.append(.init(
id: id,
role: role ?? .system,
content: content,
name: name,
toolCallContext: toolCalls.map { calls in
.init(
toolCalls: calls.sorted(by: { $0.key <= $1.key }).map(\.value),
responses: []
)
},
summary: summary,
references: references ?? []
))
}
}
}
/// Clear the history.
func clearHistory() async {
await mutateHistory { $0.removeAll() }
}
}