forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompletionStreamAPI.swift
More file actions
239 lines (216 loc) · 7.37 KB
/
CompletionStreamAPI.swift
File metadata and controls
239 lines (216 loc) · 7.37 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import AsyncAlgorithms
import Foundation
import Preferences
import AIModel
typealias CompletionStreamAPIBuilder = (String, ChatModel, URL, CompletionRequestBody)
-> CompletionStreamAPI
protocol CompletionStreamAPI {
func callAsFunction() async throws -> (
trunkStream: AsyncThrowingStream<CompletionStreamDataTrunk, Error>,
cancel: Cancellable
)
}
public enum FunctionCallStrategy: Encodable, Equatable {
/// Forbid the bot to call any function.
case none
/// Let the bot choose what function to call.
case auto
/// Force the bot to call a function with the given name.
case name(String)
struct CallFunctionNamed: Codable {
var name: String
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .none:
try container.encode("none")
case .auto:
try container.encode("auto")
case let .name(name):
try container.encode(CallFunctionNamed(name: name))
}
}
}
/// https://platform.openai.com/docs/api-reference/chat/create
struct CompletionRequestBody: Encodable, Equatable {
struct Message: Codable, Equatable {
/// The role of the message.
var role: ChatMessage.Role
/// The content of the message.
var content: String
/// When we want to reply to a function call with the result, we have to provide the
/// name of the function call, and include the result in `content`.
///
/// - important: It's required when the role is `function`.
var name: String?
/// When the bot wants to call a function, it will reply with a function call in format:
/// ```json
/// {
/// "name": "weather",
/// "arguments": "{ \"location\": \"earth\" }"
/// }
/// ```
var function_call: CompletionRequestBody.MessageFunctionCall?
}
struct MessageFunctionCall: Codable, Equatable {
/// The name of the
var name: String
/// A JSON string.
var arguments: String?
}
struct Function: Codable {
var name: String
var description: String
/// JSON schema.
var arguments: String
}
var model: String
var messages: [Message]
var temperature: Double?
var top_p: Double?
var n: Double?
var stream: Bool?
var stop: [String]?
var max_tokens: Int?
var presence_penalty: Double?
var frequency_penalty: Double?
var logit_bias: [String: Double]?
var user: String?
/// Pass nil to let the bot decide.
var function_call: FunctionCallStrategy?
var functions: [ChatGPTFunctionSchema]?
init(
model: String,
messages: [Message],
temperature: Double? = nil,
top_p: Double? = nil,
n: Double? = nil,
stream: Bool? = nil,
stop: [String]? = nil,
max_tokens: Int? = nil,
presence_penalty: Double? = nil,
frequency_penalty: Double? = nil,
logit_bias: [String: Double]? = nil,
user: String? = nil,
function_call: FunctionCallStrategy? = nil,
functions: [ChatGPTFunctionSchema] = []
) {
self.model = model
self.messages = messages
self.temperature = temperature
self.top_p = top_p
self.n = n
self.stream = stream
self.stop = stop
self.max_tokens = max_tokens
self.presence_penalty = presence_penalty
self.frequency_penalty = frequency_penalty
self.logit_bias = logit_bias
self.user = user
if UserDefaults.shared.value(for: \.disableFunctionCalling) {
self.function_call = nil
self.functions = nil
} else {
self.function_call = function_call
self.functions = functions.isEmpty ? nil : functions
}
}
}
struct CompletionStreamDataTrunk: Codable {
var id: String?
var object: String?
var model: String?
var choices: [Choice]?
struct Choice: Codable {
var delta: Delta?
var index: Int?
var finish_reason: String?
struct Delta: Codable {
struct FunctionCall: Codable {
var name: String?
var arguments: String?
}
var role: ChatMessage.Role?
var content: String?
var function_call: FunctionCall?
}
}
}
struct OpenAICompletionStreamAPI: CompletionStreamAPI {
var apiKey: String
var endpoint: URL
var requestBody: CompletionRequestBody
var model: ChatModel
init(
apiKey: String,
model: ChatModel,
endpoint: URL,
requestBody: CompletionRequestBody
) {
self.apiKey = apiKey
self.endpoint = endpoint
self.requestBody = requestBody
self.requestBody.stream = true
self.model = model
}
func callAsFunction() async throws -> (
trunkStream: AsyncThrowingStream<CompletionStreamDataTrunk, Error>,
cancel: Cancellable
) {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
let encoder = JSONEncoder()
request.httpBody = try encoder.encode(requestBody)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if !apiKey.isEmpty {
switch model.format {
case .openAI, .openAICompatible:
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
case .azureOpenAI:
request.setValue(apiKey, forHTTPHeaderField: "api-key")
}
}
let (result, response) = try await URLSession.shared.bytes(for: request)
guard let response = response as? HTTPURLResponse else {
throw ChatGPTServiceError.responseInvalid
}
guard response.statusCode == 200 else {
let text = try await result.lines.reduce(into: "") { partialResult, current in
partialResult += current
}
guard let data = text.data(using: .utf8)
else { throw ChatGPTServiceError.responseInvalid }
let decoder = JSONDecoder()
let error = try? decoder.decode(ChatGPTError.self, from: data)
throw error ?? ChatGPTServiceError.responseInvalid
}
var receivingDataTask: Task<Void, Error>?
let stream = AsyncThrowingStream<CompletionStreamDataTrunk, Error> { continuation in
receivingDataTask = Task {
do {
for try await line in result.lines {
if Task.isCancelled { break }
let prefix = "data: "
guard line.hasPrefix(prefix),
let content = line.dropFirst(prefix.count).data(using: .utf8),
let trunk = try? JSONDecoder()
.decode(CompletionStreamDataTrunk.self, from: content)
else { continue }
continuation.yield(trunk)
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
}
return (
stream,
Cancellable {
result.task.cancel()
receivingDataTask?.cancel()
}
)
}
}