forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOlamaChatCompletionsService.swift
More file actions
248 lines (223 loc) · 7.5 KB
/
OlamaChatCompletionsService.swift
File metadata and controls
248 lines (223 loc) · 7.5 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
239
240
241
242
243
244
245
246
247
import AIModel
import Foundation
import Preferences
public actor OllamaChatCompletionsService {
var apiKey: String
var endpoint: URL
var requestBody: ChatCompletionsRequestBody
var model: ChatModel
public enum ResponseFormat: String {
case none = ""
case json
}
init(
apiKey: String,
model: ChatModel,
endpoint: URL,
requestBody: ChatCompletionsRequestBody
) {
self.apiKey = apiKey
self.endpoint = endpoint
self.requestBody = requestBody
self.model = model
}
}
extension OllamaChatCompletionsService: ChatCompletionsAPI {
func callAsFunction() async throws -> ChatCompletionResponseBody {
let requestBody = ChatCompletionRequestBody(
model: model.info.modelName,
messages: requestBody.messages.map { message in
.init(role: {
switch message.role {
case .assistant:
return .assistant
case .user:
return .user
case .system:
return .system
case .tool:
return .user
}
}(), content: message.content)
},
stream: false,
options: .init(
temperature: requestBody.temperature,
stop: requestBody.stop,
num_predict: requestBody.maxTokens
),
keep_alive: nil,
format: nil
)
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
let encoder = JSONEncoder()
request.httpBody = try encoder.encode(requestBody)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let (result, response) = try await URLSession.shared.data(for: request)
guard let response = response as? HTTPURLResponse else {
throw CancellationError()
}
guard response.statusCode == 200 else {
let text = String(data: result, encoding: .utf8)
throw Error.otherError(text ?? "Unknown error")
}
let body = try JSONDecoder().decode(
ChatCompletionResponseChunk.self,
from: result
)
return .init(
object: body.model,
model: body.model,
message: body.message.map { message in
.init(
role: {
switch message.role {
case .assistant:
return .assistant
case .user:
return .user
case .system:
return .system
}
}(),
content: message.content
)
} ?? .init(role: .assistant, content: ""),
otherChoices: [],
finishReason: ""
)
}
}
extension OllamaChatCompletionsService: ChatCompletionsStreamAPI {
func callAsFunction() async throws
-> AsyncThrowingStream<ChatCompletionsStreamDataChunk, Swift.Error>
{
let requestBody = ChatCompletionRequestBody(
model: model.info.modelName,
messages: requestBody.messages.map { message in
.init(role: {
switch message.role {
case .assistant:
return .assistant
case .user:
return .user
case .system:
return .system
case .tool:
return .user
}
}(), content: message.content)
},
stream: true,
options: .init(
temperature: requestBody.temperature,
stop: requestBody.stop,
num_predict: requestBody.maxTokens
),
keep_alive: nil,
format: nil
)
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
let encoder = JSONEncoder()
request.httpBody = try encoder.encode(requestBody)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let (result, response) = try await URLSession.shared.bytes(for: request)
guard let response = response as? HTTPURLResponse else {
throw CancellationError()
}
guard response.statusCode == 200 else {
let text = try await result.lines.reduce(into: "") { partialResult, current in
partialResult += current
}
throw Error.otherError(text)
}
let stream = ResponseStream(result: result) {
let chunk = try JSONDecoder().decode(
ChatCompletionResponseChunk.self,
from: $0.data(using: .utf8) ?? Data()
)
return .init(chunk: chunk, done: chunk.done)
}
let sequence = stream.map { chunk in
ChatCompletionsStreamDataChunk(
id: UUID().uuidString,
object: chunk.model,
model: chunk.model,
message: .init(
role: {
switch chunk.message?.role {
case .none:
return nil
case .assistant:
return .assistant
case .user:
return .user
case .system:
return .system
}
}(),
content: chunk.message?.content
)
)
}
return sequence.toStream()
}
}
extension OllamaChatCompletionsService {
struct Message: Codable, Equatable {
public enum Role: String, Codable {
case user
case assistant
case system
}
/// The role of the message.
public var role: Role
/// The content of the message.
public var content: String
}
enum Error: Swift.Error, LocalizedError {
case decodeError(Swift.Error)
case otherError(String)
public var errorDescription: String? {
switch self {
case let .decodeError(error):
return error.localizedDescription
case let .otherError(message):
return message
}
}
}
}
// MARK: - Chat Completion API
/// https://github.com/ollama/ollama/blob/main/docs/api.md#chat-request-streaming
extension OllamaChatCompletionsService {
struct ChatCompletionRequestBody: Codable {
struct Options: Codable {
var temperature: Double?
var stop: [String]?
var num_predict: Int?
var top_k: Int?
var top_p: Double?
}
var model: String
var messages: [Message]
var stream: Bool
var options: Options
var keep_alive: String?
var format: String?
}
struct ChatCompletionResponseChunk: Decodable {
var model: String
var message: Message?
var response: String?
var done: Bool
var total_duration: Int64?
var load_duration: Int64?
var prompt_eval_count: Int?
var prompt_eval_duration: Int64?
var eval_count: Int?
var eval_duration: Int64?
}
}