forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatGPTService.swift
More file actions
207 lines (180 loc) · 6.76 KB
/
ChatGPTService.swift
File metadata and controls
207 lines (180 loc) · 6.76 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import AsyncAlgorithms
import Foundation
public protocol ChatGPTServiceType {
func send(content: String, summary: String?) async throws -> AsyncThrowingStream<String, Error>
func stopReceivingMessage() async
func clearHistory() async
func mutateSystemPrompt(_ newPrompt: String) async
func mutateHistory(_ mutate: (inout [ChatMessage]) -> Void) async
func markReceivingMessage(_ receiving: Bool) async
}
public enum ChatGPTServiceError: Error, LocalizedError {
case endpointIncorrect
case responseInvalid
public var errorDescription: String? {
switch self {
case .endpointIncorrect:
return "ChatGPT endpoint is incorrect"
case .responseInvalid:
return "Response is invalid"
}
}
}
public struct ChatGPTError: Error, Codable, LocalizedError {
public var error: ErrorContent
public init(error: ErrorContent) {
self.error = error
}
public struct ErrorContent: Codable {
public var message: String
public var type: String
public var param: String?
public var code: String?
public init(message: String, type: String, param: String? = nil, code: String? = nil) {
self.message = message
self.type = type
self.param = param
self.code = code
}
}
public var errorDescription: String? {
error.message
}
}
public actor ChatGPTService: ChatGPTServiceType, ObservableObject {
public var temperature: Double
public var model: String
public var endpoint: String
public var apiKey: String
public var systemPrompt: String
public var maxToken: Int
public var history: [ChatMessage] = [] {
didSet { objectWillChange.send() }
}
public internal(set) var isReceivingMessage = false {
didSet { objectWillChange.send() }
}
var uuidGenerator: () -> String = { UUID().uuidString }
var cancelTask: Cancellable?
var buildCompletionStreamAPI: CompletionStreamAPIBuilder = OpenAICompletionStreamAPI.init
public init(
systemPrompt: String,
apiKey: String,
endpoint: String? = nil,
model: String? = nil,
temperature: Double = 1,
maxToken: Int = 2048
) {
self.systemPrompt = systemPrompt
self.apiKey = apiKey
self.model = model ?? "gpt-3.5-turbo"
self.temperature = temperature
self.maxToken = maxToken
self.endpoint = endpoint ?? "https://api.openai.com/v1/chat/completions"
}
public func send(
content: String,
summary: String? = nil
) async throws -> AsyncThrowingStream<String, Error> {
guard !isReceivingMessage else { throw CancellationError() }
guard let url = URL(string: endpoint) else { throw ChatGPTServiceError.endpointIncorrect }
let newMessage = ChatMessage(
id: uuidGenerator(),
role: .user,
content: content,
summary: summary
)
history.append(newMessage)
let requestBody = CompletionRequestBody(
model: model,
messages: combineHistoryWithSystemPrompt(),
temperature: temperature,
stream: true,
max_tokens: maxToken
)
isReceivingMessage = true
do {
let api = buildCompletionStreamAPI(apiKey, url, requestBody)
return AsyncThrowingStream<String, Error> { continuation in
Task {
do {
let (trunks, cancel) = try await api()
cancelTask = cancel
for try await trunk in trunks {
guard let delta = trunk.choices.first?.delta else { continue }
if history.last?.id == trunk.id {
if let role = delta.role {
history[history.endIndex - 1].role = role
}
if let content = delta.content {
history[history.endIndex - 1].content.append(content)
}
} else {
history.append(.init(
id: trunk.id,
role: delta.role ?? .assistant,
content: delta.content ?? ""
))
}
if let content = delta.content {
continuation.yield(content)
}
}
continuation.finish()
isReceivingMessage = false
} catch let error as CancellationError {
isReceivingMessage = false
continuation.finish(throwing: error)
} catch let error as NSError where error.code == NSURLErrorCancelled {
isReceivingMessage = false
continuation.finish(throwing: error)
} catch {
history.append(.init(
role: .assistant,
content: error.localizedDescription
))
isReceivingMessage = false
continuation.finish(throwing: error)
}
}
}
}
}
public func stopReceivingMessage() {
cancelTask?()
cancelTask = nil
isReceivingMessage = false
}
public func clearHistory() {
stopReceivingMessage()
history = []
}
public func mutateSystemPrompt(_ newPrompt: String) {
systemPrompt = newPrompt
}
public func mutateHistory(_ mutate: (inout [ChatMessage]) -> Void) async {
mutate(&history)
}
public func markReceivingMessage(_ receiving: Bool) {
isReceivingMessage = receiving
}
}
extension ChatGPTService {
func changeBuildCompletionStreamAPI(_ builder: @escaping CompletionStreamAPIBuilder) {
buildCompletionStreamAPI = builder
}
func changeUUIDGenerator(_ generator: @escaping () -> String) {
uuidGenerator = generator
}
func combineHistoryWithSystemPrompt() -> [CompletionRequestBody.Message] {
if history.count > 5 {
return [.init(role: .system, content: systemPrompt)] +
history[history.endIndex - 5..<history.endIndex].map {
.init(role: $0.role, content: $0.content)
}
}
return [.init(role: .system, content: systemPrompt)] + history.map {
.init(role: $0.role, content: $0.content)
}
}
}