SPB Git

Repository Public License

ChatModel.swift 16.8 KB 383 lines swift

1import Foundation2import NavigatorCore34// MARK: - Families56/// The five kinds of provider the user can configure.7public enum ProviderFamily: String, Sendable, Hashable, Codable, CaseIterable {8    case anthropic9    case openAI = "openai"10    case openRouter = "openrouter"11    /// Any OpenAI-compatible endpoint: Ollama, LM Studio, llama.cpp server, vLLM, a self-hosted gateway.12    case compatible13    /// A model running on this device through a `LocalModelRuntime`.14    case local1516    public var displayName: String {17        switch self {18        case .anthropic: "Anthropic"19        case .openAI: "OpenAI"20        case .openRouter: "OpenRouter"21        case .compatible: "Compatible endpoint"22        case .local: "On this device"23        }24    }2526    /// Whether a request cannot be sent without an API key.27    public var requiresKey: Bool {28        switch self {29        case .anthropic, .openAI, .openRouter: true30        case .compatible, .local: false31        }32    }3334    /// The service root used when a configuration has no base URL of its own. `nil` where the user must supply one.35    public var defaultBaseURL: URL? {36        switch self {37        case .anthropic: URL(string: "https://api.anthropic.com/v1")38        case .openAI: URL(string: "https://api.openai.com/v1")39        case .openRouter: URL(string: "https://openrouter.ai/api/v1")40        case .compatible, .local: nil41        }42    }4344    /// Model ids offered as suggestions before the live list has been fetched. They are suggestions only: the model45    /// field is free-form and `ChatProvider.listModels()` is the source of truth. Reviewed 2026-11-25.46    public var suggestedModels: [String] {47        switch self {48        case .anthropic: ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-2"]49        case .openAI: ["gpt-6.2-sol", "gpt-6.2-astra", "gpt-6.1-terra", "gpt-6-luna"]50        case .openRouter: ["openrouter/auto"]51        case .compatible: []52        case .local: [LocalModelIdentifier.appleSystemModel]53        }54    }55}5657// MARK: - Messages5859public enum ChatRole: String, Sendable, Hashable, Codable {60    case system, user, assistant, tool61}6263/// Image bytes sent to a model (page screenshots). Sent inline as base64; nothing is uploaded elsewhere.64public struct ImageContent: Sendable, Hashable, Codable {65    public var data: Data66    /// `image/png`, `image/jpeg`, `image/webp` or `image/gif`.67    public var mimeType: String6869    public init(data: Data, mimeType: String = "image/png") {70        self.data = data; self.mimeType = mimeType71    }7273    var dataURL: String { "data:\(mimeType);base64,\(data.base64EncodedString())" }74}7576public enum ContentPart: Sendable, Hashable, Codable {77    case text(String)78    case image(ImageContent)79}8081/// A function the model may ask the app to run.82public struct ToolDefinition: Sendable, Hashable, Codable {83    public var name: String84    public var description: String85    /// JSON Schema of the arguments object (`{"type": "object", "properties": …}`).86    public var parameters: JSONValue8788    public init(name: String, description: String, parameters: JSONValue = ["type": "object", "properties": [:]]) {89        self.name = name; self.description = description; self.parameters = parameters90    }91}9293/// A call the model made. Arguments come from the model: validate them against the tool's schema before acting.94public struct ToolCall: Sendable, Hashable, Codable, Identifiable {95    public var id: String96    public var name: String97    /// The parsed arguments object. `.object([:])` when the model sent none; `.null` when what it sent was not a JSON98    /// object (see `hasValidArguments`), in which case the tool must not run.99    public var arguments: JSONValue100    /// The argument text exactly as streamed.101    public var rawArguments: String102    /// Opaque data the provider wants back with this call on the next request (Anthropic thinking blocks,103    /// OpenRouter reasoning details). Keep it attached to the assistant message; never show or edit it.104    public var providerState: JSONValue?105106    public init(id: String, name: String, arguments: JSONValue, rawArguments: String? = nil, providerState: JSONValue? = nil) {107        self.id = id; self.name = name; self.arguments = arguments108        self.rawArguments = rawArguments ?? arguments.serialized()109        self.providerState = providerState110    }111112    /// Builds a call from streamed argument text.113    public init(id: String, name: String, streamedArguments text: String, providerState: JSONValue? = nil) {114        let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)115        let parsed: JSONValue116        if trimmed.isEmpty { parsed = .object([:]) }117        else if let value = JSONValue.parse(trimmed), value.objectValue != nil { parsed = value }118        else { parsed = .null }119        self.init(id: id, name: name, arguments: parsed, rawArguments: text, providerState: providerState)120    }121122    public var hasValidArguments: Bool { arguments.objectValue != nil }123}124125public struct ChatMessage: Sendable, Hashable, Codable {126    public var role: ChatRole127    public var parts: [ContentPart]128    /// Assistant turns only: the calls the model made in this turn.129    public var toolCalls: [ToolCall]130    /// Tool turns only: the call this message answers.131    public var toolCallID: String?132    /// Tool turns only: the tool failed and `parts` describe the failure.133    public var isError: Bool134135    public init(role: ChatRole, parts: [ContentPart], toolCalls: [ToolCall] = [], toolCallID: String? = nil, isError: Bool = false) {136        self.role = role; self.parts = parts; self.toolCalls = toolCalls; self.toolCallID = toolCallID; self.isError = isError137    }138139    public static func system(_ text: String) -> ChatMessage { ChatMessage(role: .system, parts: [.text(text)]) }140141    public static func user(_ text: String, images: [ImageContent] = []) -> ChatMessage {142        ChatMessage(role: .user, parts: (text.isEmpty ? [] : [.text(text)]) + images.map(ContentPart.image))143    }144145    public static func assistant(_ text: String, toolCalls: [ToolCall] = []) -> ChatMessage {146        ChatMessage(role: .assistant, parts: text.isEmpty ? [] : [.text(text)], toolCalls: toolCalls)147    }148149    /// The result of running `toolCallID`. Images (a screenshot taken by a tool) are allowed.150    public static func toolResult(toolCallID: String, _ text: String, images: [ImageContent] = [], isError: Bool = false) -> ChatMessage {151        ChatMessage(role: .tool, parts: [.text(text)] + images.map(ContentPart.image), toolCallID: toolCallID, isError: isError)152    }153154    /// All text parts joined.155    public var text: String {156        parts.compactMap { if case .text(let text) = $0 { text } else { nil } }.joined()157    }158159    public var images: [ImageContent] {160        parts.compactMap { if case .image(let image) = $0 { image } else { nil } }161    }162}163164// MARK: - Request165166/// How much the model should reason before answering, where the provider has such a control.167public enum ReasoningEffort: String, Sendable, Hashable, Codable, CaseIterable {168    case low, medium, high169}170171public struct GenerationOptions: Sendable, Hashable, Codable {172    /// Upper bound on generated tokens. `nil` uses the configuration's limit, then the adapter's default.173    public var maxOutputTokens: Int?174    /// Sampling temperature. Not every provider accepts it: Anthropic's current API version rejects sampling175    /// parameters, so the Anthropic adapter never sends it; OpenAI-style servers that refuse it get the request again176    /// without it.177    public var temperature: Double?178    /// At most four are sent.179    public var stop: [String]180    /// `nil` leaves the provider's default.181    public var reasoningEffort: ReasoningEffort?182183    public init(maxOutputTokens: Int? = nil, temperature: Double? = nil, stop: [String] = [], reasoningEffort: ReasoningEffort? = nil) {184        self.maxOutputTokens = maxOutputTokens; self.temperature = temperature; self.stop = stop; self.reasoningEffort = reasoningEffort185    }186}187188public struct ChatRequest: Sendable, Hashable, Codable {189    /// The provider's own model id, passed through unchanged.190    public var model: String191    /// The system prompt. `.system` messages in `messages` are appended to it.192    public var system: String?193    public var messages: [ChatMessage]194    public var tools: [ToolDefinition]195    public var options: GenerationOptions196197    public init(model: String, system: String? = nil, messages: [ChatMessage], tools: [ToolDefinition] = [], options: GenerationOptions = GenerationOptions()) {198        self.model = model; self.system = system; self.messages = messages; self.tools = tools; self.options = options199    }200201    /// `system` plus every `.system` message, in order.202    var combinedSystem: String? {203        let pieces = ([system] + messages.filter { $0.role == .system }.map(\.text))204            .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }205        return pieces.isEmpty ? nil : pieces.joined(separator: "\n\n")206    }207208    var conversation: [ChatMessage] { messages.filter { $0.role != .system } }209}210211// MARK: - Usage212213/// Token counts as the provider reported them. Every field is optional: a count the provider did not report is214/// `nil`, never zero and never estimated.215public struct ProviderUsage: Sendable, Hashable, Codable {216    /// All input tokens, including those read from or written to a prompt cache.217    public var inputTokens: Int?218    public var outputTokens: Int?219    /// Part of `inputTokens` served from the provider's prompt cache.220    public var cacheReadTokens: Int?221    /// Part of `inputTokens` written to the provider's prompt cache.222    public var cacheWriteTokens: Int?223    /// Part of `outputTokens` spent on reasoning.224    public var reasoningTokens: Int?225    /// The cost the provider itself reported for this response (OpenRouter), in US dollars.226    public var reportedCostUSD: Double?227228    public init(inputTokens: Int? = nil, outputTokens: Int? = nil, cacheReadTokens: Int? = nil, cacheWriteTokens: Int? = nil,229                reasoningTokens: Int? = nil, reportedCostUSD: Double? = nil) {230        self.inputTokens = inputTokens; self.outputTokens = outputTokens; self.cacheReadTokens = cacheReadTokens231        self.cacheWriteTokens = cacheWriteTokens; self.reasoningTokens = reasoningTokens; self.reportedCostUSD = reportedCostUSD232    }233234    /// `false` when the provider reported neither input nor output tokens: usage is unknown.235    public var isReported: Bool { inputTokens != nil || outputTokens != nil }236237    /// Later reports replace earlier ones field by field (providers send running totals, not increments).238    public func merged(with later: ProviderUsage) -> ProviderUsage {239        ProviderUsage(inputTokens: later.inputTokens ?? inputTokens, outputTokens: later.outputTokens ?? outputTokens,240                      cacheReadTokens: later.cacheReadTokens ?? cacheReadTokens, cacheWriteTokens: later.cacheWriteTokens ?? cacheWriteTokens,241                      reasoningTokens: later.reasoningTokens ?? reasoningTokens, reportedCostUSD: later.reportedCostUSD ?? reportedCostUSD)242    }243244    /// The shared `TokenUsage` of NavigatorCore, or `nil` when usage is unknown (so a caller cannot mistake245    /// "unknown" for "zero tokens").246    public func tokenUsage(estimatedCostUSD: Double? = nil) -> TokenUsage? {247        guard isReported else { return nil }248        return TokenUsage(inputTokens: inputTokens ?? 0, outputTokens: outputTokens ?? 0, estimatedCostUSD: estimatedCostUSD)249    }250}251252// MARK: - Stream events253254public enum FinishReason: String, Sendable, Hashable, Codable {255    case endOfTurn256    case toolCalls257    case maxTokens258    case stopSequence259    /// The provider declined to answer or filtered the output.260    case contentFilter261    /// The provider gave no reason, or one this build does not know.262    case unknown263}264265public struct ResponseStart: Sendable, Hashable, Codable {266    public var responseID: String?267    /// The model the provider says it used (may differ from the requested id on routers and aliases).268    public var model: String?269270    public init(responseID: String? = nil, model: String? = nil) {271        self.responseID = responseID; self.model = model272    }273}274275/// One step of a streamed response. Order: `started`, then deltas, tool calls and usage in any order, then exactly one276/// `finished`. A stream that fails throws a `ProviderError` instead of finishing.277public enum ChatEvent: Sendable, Hashable {278    case started(ResponseStart)279    case textDelta(String)280    /// Reasoning text or a summary of it, when the provider exposes one. Never part of the answer.281    case reasoningDelta(String)282    case toolCallStarted(id: String, name: String)283    case toolCallArgumentsDelta(id: String, fragment: String)284    case toolCallCompleted(ToolCall)285    /// Running totals reported by the provider; the last one is final.286    case usage(ProviderUsage)287    case finished(FinishReason)288}289290/// A whole response assembled from its events.291public struct ChatResponse: Sendable, Hashable {292    public var start: ResponseStart?293    public var text = ""294    public var reasoning = ""295    public var toolCalls: [ToolCall] = []296    /// `nil` when the provider reported no usage.297    public var usage: ProviderUsage?298    public var finishReason: FinishReason = .unknown299300    public init() {}301302    public mutating func apply(_ event: ChatEvent) {303        switch event {304        case .started(let start): self.start = start305        case .textDelta(let delta): text += delta306        case .reasoningDelta(let delta): reasoning += delta307        case .toolCallStarted, .toolCallArgumentsDelta: break308        case .toolCallCompleted(let call): toolCalls.append(call)309        case .usage(let reported): usage = usage?.merged(with: reported) ?? reported310        case .finished(let reason): finishReason = reason311        }312    }313314    /// The assistant turn to append to the conversation before sending tool results.315    public var assistantMessage: ChatMessage { .assistant(text, toolCalls: toolCalls) }316}317318// MARK: - Models and connection319320public struct ModelInfo: Sendable, Hashable, Codable, Identifiable {321    public var id: String322    public var displayName: String323    public var contextLength: Int?324    public var maxOutputTokens: Int?325    /// `nil` when the provider's list does not say. Only an explicit statement is recorded; nothing is inferred326    /// from a model's name.327    public var supportsTools: Bool?328    public var supportsImages: Bool?329    /// A live price published by the provider's model list (OpenRouter). `nil` elsewhere.330    public var price: ModelPrice?331    public var createdAt: Date?332333    public init(id: String, displayName: String? = nil, contextLength: Int? = nil, maxOutputTokens: Int? = nil,334                supportsTools: Bool? = nil, supportsImages: Bool? = nil, price: ModelPrice? = nil, createdAt: Date? = nil) {335        self.id = id; self.displayName = displayName ?? id; self.contextLength = contextLength; self.maxOutputTokens = maxOutputTokens336        self.supportsTools = supportsTools; self.supportsImages = supportsImages; self.price = price; self.createdAt = createdAt337    }338}339340/// The outcome of a successful `testConnection()`. A failed test throws a `ProviderError`.341public struct ConnectionReport: Sendable, Hashable, Codable {342    public var family: ProviderFamily343    /// One sentence for the settings screen.344    public var summary: String345    public var modelCount: Int?346    /// Remaining credit in US dollars, where the provider reports it (OpenRouter).347    public var remainingCreditUSD: Double?348    public var latencyMilliseconds: Int349350    public init(family: ProviderFamily, summary: String, modelCount: Int? = nil, remainingCreditUSD: Double? = nil, latencyMilliseconds: Int) {351        self.family = family; self.summary = summary; self.modelCount = modelCount352        self.remainingCreditUSD = remainingCreditUSD; self.latencyMilliseconds = latencyMilliseconds353    }354}355356// MARK: - Provider357358/// A configured source of chat completions.359public protocol ChatProvider: Sendable {360    var family: ProviderFamily { get }361362    /// Streams one response. The request starts when this is called. Cancelling the consuming task, or dropping the363    /// stream, cancels the HTTP request immediately. Failures are thrown as `ProviderError`.364    func stream(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error>365366    /// The models this key or endpoint can use, as the provider lists them.367    func listModels() async throws -> [ModelInfo]368369    /// Checks that the key or endpoint works, without generating any text.370    func testConnection() async throws -> ConnectionReport371}372373extension ChatProvider {374    /// Runs `stream` to its end and returns the assembled response.375    public func complete(_ request: ChatRequest) async throws -> ChatResponse {376        var response = ChatResponse()377        for try await event in stream(request) { response.apply(event) }378        // A cancelled consumer sees the stream end early rather than throw.379        if Task.isCancelled { throw ProviderError.cancelled }380        return response381    }382}383
Files main
Menu

Theme