|
| 1 | +import CopilotForXcodeKit |
| 2 | +import Foundation |
| 3 | +import Fundamental |
| 4 | + |
| 5 | +public actor OllamaService { |
| 6 | + let url: URL |
| 7 | + let endpoint: Endpoint |
| 8 | + let modelName: String |
| 9 | + let maxToken: Int |
| 10 | + let temperature: Double |
| 11 | + let stopWords: [String] |
| 12 | + let keepAlive: String |
| 13 | + let format: ResponseFormat |
| 14 | + |
| 15 | + public enum ResponseFormat: String { |
| 16 | + case none = "" |
| 17 | + case json = "json" |
| 18 | + } |
| 19 | + |
| 20 | + public enum Endpoint { |
| 21 | + case completion |
| 22 | + case chatCompletion |
| 23 | + } |
| 24 | + |
| 25 | + init( |
| 26 | + url: String? = nil, |
| 27 | + endpoint: Endpoint, |
| 28 | + modelName: String, |
| 29 | + maxToken: Int? = nil, |
| 30 | + temperature: Double = 0.2, |
| 31 | + stopWords: [String] = [], |
| 32 | + keepAlive: String = "", |
| 33 | + format: ResponseFormat = .none |
| 34 | + ) { |
| 35 | + self.url = url.flatMap(URL.init(string:)) ?? { |
| 36 | + switch endpoint { |
| 37 | + case .chatCompletion: |
| 38 | + URL(string: "https://127.0.0.1:11434/api/chat")! |
| 39 | + case .completion: |
| 40 | + URL(string: "https://127.0.0.1:11434/api/generate")! |
| 41 | + } |
| 42 | + }() |
| 43 | + |
| 44 | + self.endpoint = endpoint |
| 45 | + self.modelName = modelName |
| 46 | + self.maxToken = maxToken ?? 4096 |
| 47 | + self.temperature = temperature |
| 48 | + self.stopWords = stopWords |
| 49 | + self.keepAlive = keepAlive |
| 50 | + self.format = format |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +extension OllamaService: CodeCompletionServiceType { |
| 55 | + typealias CompletionSequence = AsyncThrowingCompactMapSequence< |
| 56 | + ResponseStream<OllamaService.ChatCompletionResponseChunk>, |
| 57 | + String |
| 58 | + > |
| 59 | + |
| 60 | + func getCompletion( |
| 61 | + _ request: PromptStrategy |
| 62 | + ) async throws -> CompletionSequence { |
| 63 | + switch endpoint { |
| 64 | + case .chatCompletion: |
| 65 | + let messages = createMessages(from: request) |
| 66 | + CodeCompletionLogger.logger.logPrompt(messages.map { |
| 67 | + ($0.content, $0.role.rawValue) |
| 68 | + }) |
| 69 | + let stream = try await sendMessages(messages) |
| 70 | + return stream.compactMap { $0.message?.content } |
| 71 | + case .completion: |
| 72 | + let prompt = createPrompt(from: request) |
| 73 | + CodeCompletionLogger.logger.logPrompt([(prompt, "user")]) |
| 74 | + let stream = try await sendPrompt(prompt) |
| 75 | + return stream.compactMap { $0.response } |
| 76 | + } |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +extension OllamaService { |
| 81 | + struct Message: Codable, Equatable { |
| 82 | + public enum Role: String, Codable { |
| 83 | + case user |
| 84 | + case assistant |
| 85 | + case system |
| 86 | + } |
| 87 | + |
| 88 | + /// The role of the message. |
| 89 | + public var role: Role |
| 90 | + /// The content of the message. |
| 91 | + public var content: String |
| 92 | + } |
| 93 | + |
| 94 | + enum Error: Swift.Error, LocalizedError { |
| 95 | + case decodeError(Swift.Error) |
| 96 | + case otherError(String) |
| 97 | + |
| 98 | + public var errorDescription: String? { |
| 99 | + switch self { |
| 100 | + case let .decodeError(error): |
| 101 | + return error.localizedDescription |
| 102 | + case let .otherError(message): |
| 103 | + return message |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +// MARK: - Chat Completion API |
| 110 | + |
| 111 | +/// https://github.com/ollama/ollama/blob/main/docs/api.md#chat-request-streaming |
| 112 | +extension OllamaService { |
| 113 | + struct ChatCompletionRequestBody: Codable { |
| 114 | + struct Options: Codable { |
| 115 | + var temperature: Double |
| 116 | + var stop: [String] |
| 117 | + var num_predict: Int |
| 118 | + var top_k: Int? |
| 119 | + var top_p: Double? |
| 120 | + } |
| 121 | + |
| 122 | + var model: String |
| 123 | + var messages: [Message] |
| 124 | + var stream: Bool |
| 125 | + var options: Options |
| 126 | + var keep_alive: String? |
| 127 | + var format: String? |
| 128 | + } |
| 129 | + |
| 130 | + struct ChatCompletionResponseChunk: Decodable { |
| 131 | + var model: String |
| 132 | + var message: Message? |
| 133 | + var response: String? |
| 134 | + var done: Bool |
| 135 | + var total_duration: Int64? |
| 136 | + var load_duration: Int64? |
| 137 | + var prompt_eval_count: Int? |
| 138 | + var prompt_eval_duration: Int64? |
| 139 | + var eval_count: Int? |
| 140 | + var eval_duration: Int64? |
| 141 | + } |
| 142 | + |
| 143 | + func createMessages(from request: PromptStrategy) -> [Message] { |
| 144 | + let strategy = DefaultTruncateStrategy(maxTokenLimit: max( |
| 145 | + maxToken / 3 * 2, |
| 146 | + maxToken - 300 - 20 |
| 147 | + )) |
| 148 | + let prompts = strategy.createTruncatedPrompt(promptStrategy: request) |
| 149 | + return [ |
| 150 | + .init(role: .system, content: request.systemPrompt), |
| 151 | + ] + prompts.map { prompt in |
| 152 | + switch prompt.role { |
| 153 | + case .user: |
| 154 | + return .init(role: .user, content: prompt.content) |
| 155 | + case .assistant: |
| 156 | + return .init(role: .assistant, content: prompt.content) |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + func sendMessages(_ messages: [Message]) async throws |
| 162 | + -> ResponseStream<ChatCompletionResponseChunk> |
| 163 | + { |
| 164 | + let requestBody = ChatCompletionRequestBody( |
| 165 | + model: modelName, |
| 166 | + messages: messages, |
| 167 | + stream: true, |
| 168 | + options: .init( |
| 169 | + temperature: temperature, |
| 170 | + stop: stopWords, |
| 171 | + num_predict: 300 |
| 172 | + ), |
| 173 | + keep_alive: keepAlive.isEmpty ? nil : keepAlive, |
| 174 | + format: format == .none ? nil : format.rawValue |
| 175 | + ) |
| 176 | + |
| 177 | + var request = URLRequest(url: url) |
| 178 | + request.httpMethod = "POST" |
| 179 | + let encoder = JSONEncoder() |
| 180 | + request.httpBody = try encoder.encode(requestBody) |
| 181 | + request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 182 | + let (result, response) = try await URLSession.shared.bytes(for: request) |
| 183 | + |
| 184 | + guard let response = response as? HTTPURLResponse else { |
| 185 | + throw CancellationError() |
| 186 | + } |
| 187 | + |
| 188 | + guard response.statusCode == 200 else { |
| 189 | + let text = try await result.lines.reduce(into: "") { partialResult, current in |
| 190 | + partialResult += current |
| 191 | + } |
| 192 | + throw Error.otherError(text) |
| 193 | + } |
| 194 | + |
| 195 | + return ResponseStream(result: result) |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +// MARK: - Completion API |
| 200 | + |
| 201 | +extension OllamaService { |
| 202 | + struct CompletionRequestBody: Codable { |
| 203 | + var model: String |
| 204 | + var prompt: String |
| 205 | + var stream: Bool |
| 206 | + var options: ChatCompletionRequestBody.Options |
| 207 | + var keep_alive: String? |
| 208 | + var format: String? |
| 209 | + } |
| 210 | + |
| 211 | + func createPrompt(from request: PromptStrategy) -> String { |
| 212 | + let strategy = DefaultTruncateStrategy(maxTokenLimit: max( |
| 213 | + maxToken / 3 * 2, |
| 214 | + maxToken - 300 - 20 |
| 215 | + )) |
| 216 | + let prompts = strategy.createTruncatedPrompt(promptStrategy: request) |
| 217 | + return ([request.systemPrompt] + prompts.map(\.content)).joined(separator: "\n\n") |
| 218 | + } |
| 219 | + |
| 220 | + func sendPrompt(_ prompt: String) async throws -> ResponseStream<ChatCompletionResponseChunk> { |
| 221 | + let requestBody = CompletionRequestBody( |
| 222 | + model: modelName, |
| 223 | + prompt: prompt, |
| 224 | + stream: true, |
| 225 | + options: .init( |
| 226 | + temperature: temperature, |
| 227 | + stop: stopWords, |
| 228 | + num_predict: 300 |
| 229 | + ), |
| 230 | + keep_alive: keepAlive.isEmpty ? nil : keepAlive, |
| 231 | + format: format == .none ? nil : format.rawValue |
| 232 | + ) |
| 233 | + |
| 234 | + var request = URLRequest(url: url) |
| 235 | + request.httpMethod = "POST" |
| 236 | + let encoder = JSONEncoder() |
| 237 | + request.httpBody = try encoder.encode(requestBody) |
| 238 | + request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 239 | + let (result, response) = try await URLSession.shared.bytes(for: request) |
| 240 | + |
| 241 | + guard let response = response as? HTTPURLResponse else { |
| 242 | + throw CancellationError() |
| 243 | + } |
| 244 | + |
| 245 | + guard response.statusCode == 200 else { |
| 246 | + let text = try await result.lines.reduce(into: "") { partialResult, current in |
| 247 | + partialResult += current |
| 248 | + } |
| 249 | + throw Error.otherError(text) |
| 250 | + } |
| 251 | + |
| 252 | + return ResponseStream(result: result) |
| 253 | + } |
| 254 | + |
| 255 | + func countToken(_ message: Message) -> Int { |
| 256 | + message.content.count |
| 257 | + } |
| 258 | +} |
| 259 | + |
0 commit comments