import Foundation import SprachmittlerTestSupport import Testing @testable import SprachmittlerOllama @Suite("Ollama chat client", .serialized) struct OllamaChatClientTests { @Test func streamsSplitLinesAndFinalMetrics() async throws { let first = Data(#"{"message":{"role":"assistant","content":"Hallo"},"done":false}"#.utf8) let second = Data(#"{"message":{"role":"assistant","content":" Welt"},"done":false}"#.utf8) let final = Data(( #"{"message":{"role":"assistant","content":""},"done":true,"# + #""done_reason":"stop","total_duration":123,"eval_count":2}"# ).utf8) let cut = first.count / 2 ChatStubURLProtocol.reset(.init(chunks: [ Data(first.prefix(cut)), Data(first.suffix(from: cut)) + Data("\n".utf8), second + Data("\n".utf8), final + Data("\n".utf8), ])) defer { ChatStubURLProtocol.reset() } let events = try await collect(chatClient().chat(request())) #expect(events.contains(.delta("Hallo"))) #expect(events.contains(.delta(" Welt"))) guard let last = events.last, case let .done(reason, metrics) = last else { Issue.record("missing done event") return } #expect(reason == "stop") #expect(metrics.totalDuration == 123) #expect(metrics.evalCount == 2) } @Test func reportsStopAndLengthFromFixtures() async throws { let cases = [ ("chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-en-de.ndjson", "stop"), ("chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-truncated.ndjson", "length"), ] for (fixtureName, expectedReason) in cases { try ChatStubURLProtocol.reset(.init(chunks: chunks(from: fixtureName))) let events = try await collect(chatClient().chat(request())) guard let last = events.last, case let .done(reason, _) = last else { Issue.record("missing done event for \(fixtureName)") continue } #expect(reason == expectedReason) } ChatStubURLProtocol.reset() } @Test func streamEndingWithoutDoneFails() async throws { let delta = Data(#"{"message":{"content":"Hallo"},"done":false}"#.utf8) + Data("\n".utf8) ChatStubURLProtocol.reset(.init(chunks: [delta])) defer { ChatStubURLProtocol.reset() } do { _ = try await collect(chatClient().chat(request())) Issue.record("expected missing done error") } catch let error as OllamaError { #expect(error == .decoding("Stream ended without a done event")) } } @Test func midStreamErrorLineFailsTheStream() async throws { ChatStubURLProtocol.reset(.init(chunks: [ Data(#"{"message":{"content":"Hallo"},"done":false}"#.utf8) + Data("\n".utf8), Data(#"{"error":"model 'missing' not found"}"#.utf8) + Data("\n".utf8), ])) defer { ChatStubURLProtocol.reset() } do { _ = try await collect(chatClient().chat(request(model: "missing"))) Issue.record("expected error") } catch let error as OllamaError { #expect(error == .modelNotInstalled("missing")) } } @Test func firstTokenTimeoutFires() async throws { let sleeper = ManualSleeper() ChatStubURLProtocol.reset(.init(chunks: [], hangAfterChunks: true)) defer { ChatStubURLProtocol.reset() } let client = try chatClient(sleeper: sleeper, timeouts: testTimeouts) let task = Task { try await collect(client.chat(request())) } await sleeper.waitUntilPending(.seconds(1)) for _ in 0 ..< 1000 { if ChatStubURLProtocol.started() { break } await Task.yield() } await sleeper.advance(matching: .seconds(1)) do { _ = try await task.value Issue.record("expected first-token timeout") } catch let error as OllamaError { #expect(error == .timeout(.firstToken)) } for _ in 0 ..< 1000 { if ChatStubURLProtocol.stopped() { break } await Task.yield() } #expect(ChatStubURLProtocol.stopped()) } @Test func idleTimeoutFiresAfterFirstDelta() async throws { let sleeper = ManualSleeper() let delta = Data(#"{"message":{"content":"Hallo"},"done":false}"#.utf8) + Data("\n".utf8) ChatStubURLProtocol.reset(.init(chunks: [delta], hangAfterChunks: true)) defer { ChatStubURLProtocol.reset() } let client = try chatClient(sleeper: sleeper, timeouts: testTimeouts) let task = Task { try await collect(client.chat(request())) } await sleeper.waitUntilPending(.seconds(2)) await sleeper.advance(matching: .seconds(2)) do { _ = try await task.value Issue.record("expected idle timeout") } catch let error as OllamaError { #expect(error == .timeout(.idle)) } } @Test func totalTimeoutFires() async throws { let sleeper = ManualSleeper() ChatStubURLProtocol.reset(.init(chunks: [], hangAfterChunks: true)) defer { ChatStubURLProtocol.reset() } let client = try chatClient(sleeper: sleeper, timeouts: testTimeouts) let task = Task { try await collect(client.chat(request())) } await sleeper.waitUntilPending(.seconds(3)) await sleeper.advance(matching: .seconds(3)) do { _ = try await task.value Issue.record("expected total timeout") } catch let error as OllamaError { #expect(error == .timeout(.total)) } } @Test func cancelMidStreamStopsURLTask() async throws { let sleeper = ManualSleeper() let delta = Data(#"{"message":{"content":"Hallo"},"done":false}"#.utf8) + Data("\n".utf8) ChatStubURLProtocol.reset(.init(chunks: [delta], hangAfterChunks: true)) defer { ChatStubURLProtocol.reset() } let client = try chatClient(sleeper: sleeper, timeouts: testTimeouts) let task = Task { try await collect(client.chat(request())) } await sleeper.waitUntilPending(.seconds(2)) task.cancel() do { _ = try await task.value } catch { // The consumer task is cancelled; the stream is expected to throw. } for _ in 0 ..< 1000 { if ChatStubURLProtocol.stopped() { break } await Task.yield() } #expect(ChatStubURLProtocol.stopped()) } @Test func encodesExactChatRequest() throws { let data = try JSONEncoder().encode(request()) let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) #expect(Set(object.keys) == ["model", "messages", "stream", "keep_alive", "options"]) #expect(object["stream"] as? Bool == true) #expect(object["system"] == nil) #expect(object["images"] == nil) #expect(object["think"] == nil) let options = try #require(object["options"] as? [String: Any]) #expect( Set(options.keys) == ["temperature", "top_p", "top_k", "repeat_penalty", "num_predict", "num_ctx"] ) let messages = try #require(object["messages"] as? [[String: Any]]) #expect(messages.count == 1) #expect(messages[0]["role"] as? String == "user") } private var testTimeouts: ChatTimeouts { ChatTimeouts(firstToken: .seconds(1), idle: .seconds(2), total: .seconds(3)) } private func request(model: String = "test-model") -> ChatRequest { ChatRequest( model: model, messages: [ChatMessage(content: "Hello.")], keepAlive: "5m", options: ChatOptions( temperature: 0.7, topP: 0.6, topK: 20, repeatPenalty: 1.05, numPredict: 4096, numCtx: 8192 ) ) } private func chatClient( sleeper: ManualSleeper = ManualSleeper(), timeouts: ChatTimeouts = .standard ) throws -> OllamaChatClient { try OllamaChatClient(http: makeClient(), sleeper: sleeper, timeouts: timeouts) } private func collect( _ stream: AsyncThrowingStream ) async throws -> [ChatEvent] { var events: [ChatEvent] = [] for try await event in stream { events.append(event) } return events } private func chunks(from fixtureName: String) throws -> [Data] { let base = try #require(Bundle.module.resourceURL) let url = base.appendingPathComponent("Fixtures/\(fixtureName)") let text = try String(contentsOf: url, encoding: .utf8) return text.split(separator: "\n", omittingEmptySubsequences: true) .map { Data($0.utf8) + Data("\n".utf8) } } private func makeClient() throws -> OllamaHTTPClient { let url = try #require(URL(string: "http://127.0.0.1:11434")) let configuration = OllamaSessionFactory.makeConfiguration() configuration.protocolClasses = [ChatStubURLProtocol.self] let session = URLSession( configuration: configuration, delegate: RedirectRefusingDelegate(), delegateQueue: nil ) return try OllamaHTTPClient(baseURL: url, session: session) } }