import Foundation /// The JSON HTTP client for Ollama. The only module that builds `URLRequest`s and owns a /// `URLSession` (SP-4, SP-6). public final class OllamaHTTPClient: OllamaHTTPTransport, Sendable { /// The validated base URL, e.g. `http://127.0.0.1:11434`. public let baseURL: URL let session: URLSession /// Creates a client with an ephemeral session and a redirect-refusing delegate. public init(baseURL: URL, allowRemote: Bool = false) throws { let validated: URL do { validated = try EndpointPolicy.validate(baseURL, allowRemote: allowRemote) } catch let rejection as EndpointRejection { throw OllamaError.endpointRejected(rejection) } self.baseURL = validated session = URLSession( configuration: OllamaSessionFactory.makeConfiguration(), delegate: RedirectRefusingDelegate(), delegateQueue: nil ) } /// Test seam: inject a session with a `URLProtocol` stub. init(baseURL: URL, session: URLSession) throws { let validated: URL do { validated = try EndpointPolicy.validate(baseURL, allowRemote: false) } catch let rejection as EndpointRejection { throw OllamaError.endpointRejected(rejection) } self.baseURL = validated self.session = session } deinit { session.invalidateAndCancel() } /// Sends a request and returns a 2xx response. Non-2xx statuses and transport failures are /// mapped to `OllamaError`. /// /// - Parameter model: the model tag for a 404 body check; pass it for chat/show requests. public func send(_ request: OllamaHTTPRequest, model: String? = nil) async throws -> OllamaHTTPResponse { let url = try makeURL(for: request.path) let urlRequest = try makeURLRequest(request) do { let (data, response) = try await session.data(for: urlRequest) guard let http = response as? HTTPURLResponse else { throw OllamaError.decoding("Non-HTTP response") } if (300 ..< 400).contains(http.statusCode) { throw OllamaError.endpointRejected(.redirect) } guard (200 ..< 300).contains(http.statusCode) else { throw httpError(status: http.statusCode, data: data, model: model) } return OllamaHTTPResponse(status: http.statusCode, body: data) } catch let error as OllamaError { throw error } catch let error as URLError { throw transportError(error, url: url) } catch is CancellationError { throw OllamaError.cancelled } catch { throw OllamaError.decoding("Request failed") } } /// Sends a request and decodes a JSON response. public func sendJSON( _ request: OllamaHTTPRequest, as type: Response.Type, model: String? = nil ) async throws -> Response { let response = try await send(request, model: model) do { return try JSONDecoder().decode(Response.self, from: response.body) } catch { throw OllamaError.decoding("Invalid JSON response") } } /// Streams NDJSON lines from a request. The caller decides when to stop after a `done` line. func stream( _ request: OllamaHTTPRequest, model: String?, onLine: @escaping @Sendable (String) async throws -> StreamLineAction ) async throws { let url = try makeURL(for: request.path) let urlRequest = try makeURLRequest(request) do { let (bytes, response) = try await session.bytes(for: urlRequest) guard let http = response as? HTTPURLResponse else { throw OllamaError.decoding("Non-HTTP response") } try await validateStreamResponse(http, bytes: bytes, model: model) var lines = bytes.lines.makeAsyncIterator() while let line = try await lines.next() { if try await onLine(line) == .stop { break } } } catch let error as OllamaError { throw error } catch let error as URLError { throw transportError(error, url: url) } catch is CancellationError { throw OllamaError.cancelled } catch { throw OllamaError.decoding("Stream failed") } } /// Builds the request URL without producing `//` at the base-path boundary. func makeURL(for path: String) throws -> URL { guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else { throw OllamaError.decoding("Invalid base URL") } let requestPath = path.hasPrefix("/") ? path : "/" + path let basePath = components.path if basePath.isEmpty || basePath == "/" { components.path = requestPath } else if basePath.hasSuffix("/") { components.path = String(basePath.dropLast()) + requestPath } else { components.path = basePath + requestPath } guard let url = components.url else { throw OllamaError.decoding("Invalid request URL") } return url } private func validateStreamResponse( _ http: HTTPURLResponse, bytes: URLSession.AsyncBytes, model: String? ) async throws { if (300 ..< 400).contains(http.statusCode) { throw OllamaError.endpointRejected(.redirect) } guard (200 ..< 300).contains(http.statusCode) else { var data = Data() for try await byte in bytes { guard data.count < 4096 else { break } data.append(byte) } throw httpError(status: http.statusCode, data: data, model: model) } } private func makeURLRequest(_ request: OllamaHTTPRequest) throws -> URLRequest { let url = try makeURL(for: request.path) var urlRequest = URLRequest(url: url) urlRequest.httpMethod = request.method.rawValue urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") if let body = request.body { urlRequest.httpBody = body urlRequest.setValue( request.contentType ?? "application/json", forHTTPHeaderField: "Content-Type" ) } return urlRequest } private func httpError(status: Int, data: Data, model: String?) -> OllamaError { let message = OllamaErrorBody.message(from: data) ?? "" if status == 404, let model, message.localizedCaseInsensitiveContains("not found") { return .modelNotInstalled(model) } if status == 400 { return .badRequest(message) } return .server(status: status, message: message) } private func transportError(_ error: URLError, url: URL) -> OllamaError { switch error.code { case .cancelled: .cancelled case .timedOut: .timeout(.connect) case .cannotConnectToHost, .cannotFindHost, .dnsLookupFailed, .networkConnectionLost, .notConnectedToInternet: .unreachable(url) default: .unreachable(url) } } }