Repository Public License
1import Foundation23/// Any server that speaks the OpenAI Chat Completions protocol at a base URL the user typed: Ollama4/// (`http://localhost:11434/v1`), LM Studio, llama.cpp server, vLLM, a self-hosted gateway.5public struct CompatibleProvider: ChatProvider {6 public let family: ProviderFamily = .compatible78 /// Where and how to reach the server. Non-secret: the optional key comes from the `KeySource`.9 public struct Endpoint: Sendable, Hashable, Codable {10 /// The API root including its version path, e.g. `https://example.com/v1`.11 public var baseURL: String12 /// The user's explicit opt-in to plain HTTP for a host that is not local or on a private network.13 public var allowInsecureHTTP: Bool14 /// Extra non-credential headers (see `EndpointPolicy.validate(headers:)`).15 public var headers: [String: String]1617 public init(baseURL: String, allowInsecureHTTP: Bool = false, headers: [String: String] = [:]) {18 self.baseURL = baseURL; self.allowInsecureHTTP = allowInsecureHTTP; self.headers = headers19 }2021 /// The base URL, if this endpoint passes the HTTPS rule and its headers are acceptable.22 public func validated() throws -> URL {23 let url = try EndpointPolicy.validate(baseURL, allowInsecureHTTP: allowInsecureHTTP)24 try EndpointPolicy.validate(headers: headers)25 return url26 }27 }2829 static let dialect = ChatCompletionsDialect(reasoning: .effortField, requestsUsage: true)3031 public let endpoint: Endpoint32 private let http: ProviderHTTP33 private let apiKey: KeySource3435 public init(endpoint: Endpoint, apiKey: @escaping KeySource = { nil }, environment: ProviderEnvironment = ProviderEnvironment()) {36 self.endpoint = endpoint37 self.http = ProviderHTTP(family: .compatible, environment: environment)38 self.apiKey = apiKey39 }4041 private struct Target { var base: URL; var headers: [String: String]; var key: String? }4243 /// Validated on every use, so a configuration edited into an unsafe state can never send a request.44 private func target() async throws -> Target {45 let base = try endpoint.validated()46 let key = try await resolveKey(apiKey, family: .compatible, required: false)47 var headers: [String: String] = [:]48 for (name, value) in endpoint.headers { headers[name.trimmingCharacters(in: .whitespaces)] = value }49 if let key { headers["Authorization"] = "Bearer \(key)" }50 return Target(base: base, headers: headers, key: key)51 }5253 public func listModels() async throws -> [ModelInfo] {54 let target = try await target()55 let request = ProviderHTTP.request(target.base.appendingPathComponent("models"), headers: target.headers, timeout: http.environment.timeouts.request)56 let json = try await http.json(request, secrets: [target.key].compactMap { $0 })57 return openAIStyleModelEntries(json).compactMap { entry -> ModelInfo? in58 guard let id = entry["id"]?.stringValue ?? entry["name"]?.stringValue ?? entry.stringValue, !id.isEmpty else { return nil }59 // Only what the endpoint reports about itself; most publish ids alone.60 return ModelInfo(id: id, displayName: entry["display_name"]?.stringValue,61 contextLength: entry["context_window"]?.intValue ?? entry["context_length"]?.intValue ?? entry["max_model_len"]?.intValue,62 maxOutputTokens: entry["max_output_tokens"]?.intValue,63 supportsTools: entry["capabilities"]?["tools"]?.boolValue ?? entry["capabilities"]?["function_calling"]?.boolValue,64 supportsImages: entry["capabilities"]?["vision"]?.boolValue,65 createdAt: entry["created"]?.doubleValue.map { Date(timeIntervalSince1970: $0) })66 }67 }6869 public func testConnection() async throws -> ConnectionReport {70 let started = Date()71 let models = try await listModels()72 return ConnectionReport(family: family, summary: "Endpoint reachable. \(models.count) models listed.", modelCount: models.count,73 latencyMilliseconds: Int(Date().timeIntervalSince(started) * 1_000))74 }7576 public func stream(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error> {77 let http = http78 let secrets = SecretBox()79 return makeEventStream(secrets: secrets) { continuation in80 let target = try await target()81 secrets.add(target.key)82 var headers = target.headers83 headers["Accept"] = "text/event-stream"84 let url = target.base.appendingPathComponent("chat/completions")85 let timeout = http.environment.timeouts.streamIdle86 try await runChatCompletionsStream(http: http, request: request, dialect: Self.dialect, secrets: [target.key].compactMap { $0 }, makeRequest: { body in87 ProviderHTTP.request(url, method: "POST", headers: headers, body: body, timeout: timeout)88 }, continuation: continuation)89 }90 }91}92