|
| 1 | +import AIModel |
| 2 | +import Foundation |
| 3 | +import Preferences |
| 4 | + |
| 5 | +public actor OllamaService { |
| 6 | + var apiKey: String |
| 7 | + var endpoint: URL |
| 8 | + var requestBody: ChatCompletionsRequestBody |
| 9 | + var model: ChatModel |
| 10 | + |
| 11 | + public enum ResponseFormat: String { |
| 12 | + case none = "" |
| 13 | + case json |
| 14 | + } |
| 15 | + |
| 16 | + init( |
| 17 | + apiKey: String, |
| 18 | + model: ChatModel, |
| 19 | + endpoint: URL, |
| 20 | + requestBody: ChatCompletionsRequestBody |
| 21 | + ) { |
| 22 | + self.apiKey = apiKey |
| 23 | + self.endpoint = endpoint |
| 24 | + self.requestBody = requestBody |
| 25 | + self.model = model |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +extension OllamaService: ChatCompletionsAPI { |
| 30 | + func callAsFunction() async throws -> ChatCompletionResponseBody { |
| 31 | + fatalError() |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +extension OllamaService: ChatCompletionsStreamAPI { |
| 36 | + typealias CompletionSequence = AsyncMapSequence<ResponseStream<OllamaService.ChatCompletionResponseChunk>, ChatCompletionsStreamDataChunk> |
| 37 | + |
| 38 | + func callAsFunction() async throws -> CompletionSequence { |
| 39 | + let requestBody = ChatCompletionRequestBody( |
| 40 | + model: model.info.modelName, |
| 41 | + messages: requestBody.messages.map { message in |
| 42 | + .init(role: { |
| 43 | + switch message.role { |
| 44 | + case .assistant: |
| 45 | + return .assistant |
| 46 | + case .user: |
| 47 | + return .user |
| 48 | + case .system: |
| 49 | + return .system |
| 50 | + case .function: |
| 51 | + return .user |
| 52 | + } |
| 53 | + }(), content: message.content) |
| 54 | + }, |
| 55 | + stream: true, |
| 56 | + options: .init( |
| 57 | + temperature: requestBody.temperature, |
| 58 | + stop: requestBody.stop, |
| 59 | + num_predict: requestBody.max_tokens |
| 60 | + ), |
| 61 | + keep_alive: nil, |
| 62 | + format: nil |
| 63 | + ) |
| 64 | + |
| 65 | + var request = URLRequest(url: endpoint) |
| 66 | + request.httpMethod = "POST" |
| 67 | + let encoder = JSONEncoder() |
| 68 | + request.httpBody = try encoder.encode(requestBody) |
| 69 | + request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 70 | + let (result, response) = try await URLSession.shared.bytes(for: request) |
| 71 | + |
| 72 | + guard let response = response as? HTTPURLResponse else { |
| 73 | + throw CancellationError() |
| 74 | + } |
| 75 | + |
| 76 | + guard response.statusCode == 200 else { |
| 77 | + let text = try await result.lines.reduce(into: "") { partialResult, current in |
| 78 | + partialResult += current |
| 79 | + } |
| 80 | + throw Error.otherError(text) |
| 81 | + } |
| 82 | + |
| 83 | + let stream = ResponseStream(result: result) { |
| 84 | + let chunk = try JSONDecoder().decode( |
| 85 | + ChatCompletionResponseChunk.self, |
| 86 | + from: $0.data(using: .utf8) ?? Data() |
| 87 | + ) |
| 88 | + return .init(chunk: chunk, done: chunk.done) |
| 89 | + } |
| 90 | + |
| 91 | + let sequence = stream.map { chunk in |
| 92 | + ChatCompletionsStreamDataChunk( |
| 93 | + id: UUID().uuidString, |
| 94 | + object: chunk.model, |
| 95 | + model: chunk.model, |
| 96 | + choices: [ |
| 97 | + .init( |
| 98 | + delta: .init( |
| 99 | + role: { |
| 100 | + switch chunk.message?.role { |
| 101 | + case .none: |
| 102 | + return nil |
| 103 | + case .assistant: |
| 104 | + return .assistant |
| 105 | + case .user: |
| 106 | + return .user |
| 107 | + case .system: |
| 108 | + return .system |
| 109 | + } |
| 110 | + }(), |
| 111 | + content: chunk.message?.content |
| 112 | + ) |
| 113 | + ), |
| 114 | + ] |
| 115 | + ) |
| 116 | + } |
| 117 | + |
| 118 | + return sequence |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +extension OllamaService { |
| 123 | + struct Message: Codable, Equatable { |
| 124 | + public enum Role: String, Codable { |
| 125 | + case user |
| 126 | + case assistant |
| 127 | + case system |
| 128 | + } |
| 129 | + |
| 130 | + /// The role of the message. |
| 131 | + public var role: Role |
| 132 | + /// The content of the message. |
| 133 | + public var content: String |
| 134 | + } |
| 135 | + |
| 136 | + enum Error: Swift.Error, LocalizedError { |
| 137 | + case decodeError(Swift.Error) |
| 138 | + case otherError(String) |
| 139 | + |
| 140 | + public var errorDescription: String? { |
| 141 | + switch self { |
| 142 | + case let .decodeError(error): |
| 143 | + return error.localizedDescription |
| 144 | + case let .otherError(message): |
| 145 | + return message |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +// MARK: - Chat Completion API |
| 152 | + |
| 153 | +/// https://github.com/ollama/ollama/blob/main/docs/api.md#chat-request-streaming |
| 154 | +extension OllamaService { |
| 155 | + struct ChatCompletionRequestBody: Codable { |
| 156 | + struct Options: Codable { |
| 157 | + var temperature: Double? |
| 158 | + var stop: [String]? |
| 159 | + var num_predict: Int? |
| 160 | + var top_k: Int? |
| 161 | + var top_p: Double? |
| 162 | + } |
| 163 | + |
| 164 | + var model: String |
| 165 | + var messages: [Message] |
| 166 | + var stream: Bool |
| 167 | + var options: Options |
| 168 | + var keep_alive: String? |
| 169 | + var format: String? |
| 170 | + } |
| 171 | + |
| 172 | + struct ChatCompletionResponseChunk: Decodable { |
| 173 | + var model: String |
| 174 | + var message: Message? |
| 175 | + var response: String? |
| 176 | + var done: Bool |
| 177 | + var total_duration: Int64? |
| 178 | + var load_duration: Int64? |
| 179 | + var prompt_eval_count: Int? |
| 180 | + var prompt_eval_duration: Int64? |
| 181 | + var eval_count: Int? |
| 182 | + var eval_duration: Int64? |
| 183 | + } |
| 184 | +} |
| 185 | + |
0 commit comments