import Foundation /// The streaming Ollama chat client. One task reads NDJSON lines; a timeout controller guards /// first-token, idle and total phases. public struct OllamaChatClient: OllamaChatting, Sendable { private let http: OllamaHTTPClient private let sleeper: any AsyncSleeper private let timeouts: ChatTimeouts /// Creates a chat client. public init( http: OllamaHTTPClient, sleeper: any AsyncSleeper = ContinuousClockSleeper(), timeouts: ChatTimeouts = .standard ) { self.http = http self.sleeper = sleeper self.timeouts = timeouts } /// Streams deltas and one final `done` event. Throws `OllamaError` on failure. public func chat(_ request: ChatRequest) -> AsyncThrowingStream { AsyncThrowingStream { continuation in let context = ChatStreamContext(continuation: continuation) let task = Task { await context.waitForStart() await run(request, context: context) } Task { await context.setTask(task) } continuation.onTermination = { @Sendable _ in task.cancel() Task { await context.cancel() } } } } private func run(_ request: ChatRequest, context: ChatStreamContext) async { if Task.isCancelled { await context.cancel() return } let phase = ChatTimeoutController(sleeper: sleeper) let total = ChatTimeoutController(sleeper: sleeper) do { let body = try JSONEncoder().encode(request) let httpRequest = OllamaHTTPRequest(method: .post, path: "/api/chat", body: body) await phase.schedule(.firstToken, after: timeouts.firstToken) { phase in Task { await context.fail(OllamaError.timeout(phase)) } } await total.schedule(.total, after: timeouts.total) { phase in Task { await context.fail(OllamaError.timeout(phase)) } } try await http.stream(httpRequest, model: request.model) { line in try await handle( line, request: request, context: context, phase: phase, total: total ) } await context.finishIfDone() } catch let error as OllamaError { if case .cancelled = error { await context.cancel() } else { await context.fail(error) } } catch is CancellationError { await context.cancel() } catch { await context.fail(OllamaError.decoding("Stream failed")) } await phase.cancel() await total.cancel() } private func handle( _ line: String, request: ChatRequest, context: ChatStreamContext, phase: ChatTimeoutController, total: ChatTimeoutController ) async throws -> StreamLineAction { let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return .continueStream } guard let data = trimmed.data(using: .utf8) else { throw OllamaError.decoding("Invalid stream line") } let object: StreamLine do { object = try JSONDecoder().decode(StreamLine.self, from: data) } catch { throw OllamaError.decoding("Invalid stream line") } if let message = object.error, !message.isEmpty { throw streamError(message, model: request.model) } if let content = object.message?.content, !content.isEmpty { await phase.schedule(.idle, after: timeouts.idle) { phase in Task { await context.fail(OllamaError.timeout(phase)) } } await context.emit(.delta(content)) } if object.done == true { await phase.cancel() await total.cancel() // Unknown done_reason values are passed through unchanged. Logging them at .info // needs an injected logger in M2/M4. await context.markDone() await context.emit(.done(reason: object.doneReason, metrics: object.metrics)) await context.finish() return .stop } return .continueStream } private func streamError(_ message: String, model: String) -> OllamaError { if message.localizedCaseInsensitiveContains("not found") { return .modelNotInstalled(model) } return .server(status: 0, message: message) } } /// One NDJSON object from `/api/chat`. private struct StreamLine: Decodable { struct Message: Decodable { let content: String? } let message: Message? let done: Bool? let doneReason: String? let error: String? let totalDuration: Int64? let loadDuration: Int64? let promptEvalCount: Int? let promptEvalDuration: Int64? let evalCount: Int? let evalDuration: Int64? var metrics: ChatMetrics { ChatMetrics( totalDuration: totalDuration, loadDuration: loadDuration, promptEvalCount: promptEvalCount, promptEvalDuration: promptEvalDuration, evalCount: evalCount, evalDuration: evalDuration ) } private enum CodingKeys: String, CodingKey { case message case done case doneReason = "done_reason" case error case totalDuration = "total_duration" case loadDuration = "load_duration" case promptEvalCount = "prompt_eval_count" case promptEvalDuration = "prompt_eval_duration" case evalCount = "eval_count" case evalDuration = "eval_duration" } }