SPB Git

Repository Public

ChatCompletions.swift 26.3 KB 457 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraProviders/Sources/ChatCompletions.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AstraCore89import Foundation9091// The Chat Completions wire format (`POST …/chat/completions`, `data:` chunks ending with `[DONE]`),92// shared by OpenRouter, user-configured OpenAI-compatible endpoints and the keyed providers built on `KeyedChatCompletions`93// (Mistral, DeepSeek, Moonshot, Cerebras, DeepInfra).9495struct ChatCompletionsDialect: Sendable {96    enum Reasoning: Sendable {97        /// OpenRouter: `"reasoning": {"effort": …}`.98        case object99        /// Common OpenAI-compatible spelling: `"reasoning_effort": "low" | "medium" | "high"`.100        case effortField101        /// `reasoning_effort` where the provider also documents `"none"` to switch reasoning off (Mistral, Cerebras, DeepInfra).102        case effortFieldWithNone103        /// The encoder writes nothing; the dialect's `prepare` hook sets the provider's own fields (DeepSeek, Moonshot `thinking`).104        case managed105    }106    /// What a tool-calling turn must carry back in the next request, kept in `ToolCall.providerState` of the turn's first call.107    enum Replay: Sendable, Equatable {108        case none109        /// The turn's reasoning text, returned and replayed in the same assistant-message field110        /// (`reasoning_content` on DeepSeek and Moonshot, `reasoning` on Cerebras).111        case reasoningField(format: String, field: String)112        /// Mistral: the turn's `thinking` chunks, replayed as a typed chunk at the head of the assistant `content`.113        case thinkingChunks(format: String)114        /// OpenRouter: the `reasoning_details` array, replayed unmodified and in order.115        case reasoningDetails(format: String)116    }117    var reasoning: Reasoning118    var replay = Replay.none119    /// `stream_options: {"include_usage": true}`; OpenRouter always sends usage and ignores the option.120    var requestsUsage: Bool121    var includesRouting: Bool122    /// Name of the output cap: `max_tokens`, or `max_completion_tokens` where the provider documents that spelling.123    var maxTokensKey = "max_tokens"124    /// Name of the sampling seed (`random_seed` on Mistral, which rejects `seed`); nil when the provider has none.125    var seedKey: String? = "seed"126    /// Last edit of the encoded body: provider-specific fields that the shared encoder does not know.127    var prepare: (@Sendable (GenerationRequest, inout [String: JSONValue]) -> Void)?128    /// Provider-specific parameter fallback, tried before the generic one. Returns true when the body was changed and is worth resending.129    var adjust: (@Sendable (ProviderHTTP.Failure, inout [String: JSONValue]) -> Bool)?130    /// Rewrites a failure into the status class it really is (a provider that answers 400 for an unknown model, for instance).131    var normalize: @Sendable (ProviderHTTP.Failure) -> ProviderHTTP.Failure = { $0 }132}133134enum ChatCompletionsEncoder {135    static func body(_ request: GenerationRequest, dialect: ChatCompletionsDialect) -> [String: JSONValue] {136        var messages: [JSONValue] = []137        if let system = request.system?.trimmingCharacters(in: .whitespacesAndNewlines), !system.isEmpty {138            messages.append(["role": "system", "content": .string(system)])139        }140        for message in request.messages { messages.append(wire(message, replay: dialect.replay)) }141        var body: [String: JSONValue] = ["model": .string(request.model.modelID), "messages": .array(messages), "stream": true]142        if dialect.requestsUsage { body["stream_options"] = ["include_usage": true] }143        if !request.tools.isEmpty {144            body["tools"] = .array(request.tools.map { tool in145                ["type": "function", "function": ["name": .string(tool.name), "description": .string(tool.summary), "parameters": tool.parameters]]146            })147        }148        let p = request.parameters149        if let v = p.maxOutputTokens { body[dialect.maxTokensKey] = .number(Double(v)) }150        if let v = p.temperature { body["temperature"] = .number(v) }151        if let v = p.topP { body["top_p"] = .number(v) }152        if let v = p.seed, let key = dialect.seedKey { body[key] = .number(Double(v)) }153        if !p.stop.isEmpty { body["stop"] = .array(p.stop.prefix(4).map(JSONValue.string)) }154        if let effort = p.reasoning {155            switch dialect.reasoning {156            case .object: body["reasoning"] = ["effort": .string(effort == .off ? "none" : effort.rawValue)]157            case .effortField: if effort != .off { body["reasoning_effort"] = .string(effort.rawValue) }158            case .effortFieldWithNone: body["reasoning_effort"] = .string(effort == .off ? "none" : effort.rawValue)159            case .managed: break160            }161        }162        if dialect.includesRouting, let routing = request.routing, !routing.isDefault {163            var provider: [String: JSONValue] = [:]164            if !routing.providerOrder.isEmpty { provider["order"] = .array(routing.providerOrder.map(JSONValue.string)) }165            if !routing.allowFallbacks { provider["allow_fallbacks"] = false }166            if routing.denyDataCollection { provider["data_collection"] = "deny" }167            if !provider.isEmpty { body["provider"] = .object(provider) }168            let fallbacks = routing.fallbackModels.filter { $0 != request.model.modelID }169            if !fallbacks.isEmpty { body["models"] = .array(fallbacks.map(JSONValue.string)) }170        }171        dialect.prepare?(request, &body)172        return body173    }174175    static func wire(_ message: PromptMessage, replay: ChatCompletionsDialect.Replay = .none) -> JSONValue {176        switch message.role {177        case .user:178            if message.images.isEmpty { return ["role": "user", "content": .string(message.text)] }179            var parts: [JSONValue] = []180            if !message.text.isEmpty { parts.append(["type": "text", "text": .string(message.text)]) }181            parts += message.images.map { ["type": "image_url", "image_url": ["url": .string(dataURL($0))]] }182            return ["role": "user", "content": .array(parts)]183        case .assistant:184            var out: [String: JSONValue] = ["role": "assistant", "content": message.text.isEmpty && !message.toolCalls.isEmpty ? .null : .string(message.text)]185            if !message.toolCalls.isEmpty {186                out["tool_calls"] = .array(message.toolCalls.map { call in187                    ["id": .string(call.id), "type": "function", "function": ["name": .string(call.name), "arguments": .string(ToolArguments.wireText(call.arguments))]]188                })189                // What the provider asked to see again with this turn. A call without state (an older conversation,190                // another provider's turn) adds nothing and the message keeps its plain shape.191                switch replay {192                case .none: break193                case .reasoningField(let format, let field):194                    if let text = ProviderState.payload(message.toolCalls, format: format)?.stringValue { out[field] = .string(text) }195                case .thinkingChunks(let format):196                    if let text = ProviderState.payload(message.toolCalls, format: format)?.stringValue {197                        var chunks: [JSONValue] = [["type": "thinking", "thinking": [["type": "text", "text": .string(text)]]]]198                        if !message.text.isEmpty { chunks.append(["type": "text", "text": .string(message.text)]) }199                        out["content"] = .array(chunks)200                    }201                case .reasoningDetails(let format):202                    if let details = ProviderState.payload(message.toolCalls, format: format), details.arrayValue != nil { out["reasoning_details"] = details }203                }204            }205            return .object(out)206        case .tool:207            let text = message.toolIsError ? "Error: " + message.text : message.text208            return ["role": "tool", "tool_call_id": .string(message.toolCallID ?? ""), "content": .string(text)]209        }210    }211212    /// Edits the body after a parameter rejection by a compatible server. Returns false when nothing can be routed around.213    static func adjust(_ failure: ProviderHTTP.Failure, _ body: inout [String: JSONValue]) -> Bool {214        let message = (failure.body.message ?? "").lowercased()215        // Newer OpenAI-style servers want `max_completion_tokens` and say so.216        if failure.status == 400, message.contains("max_completion_tokens"), let value = body["max_tokens"] {217            body.removeValue(forKey: "max_tokens")218            body["max_completion_tokens"] = value219            return true220        }221        var candidates: [UnsupportedParameter.Candidate] = []222        for key in ["stream_options", "reasoning_effort", "reasoning", "thinking", "seed", "random_seed", "top_p", "temperature", "stop"] where body[key] != nil {223            candidates.append(.init(key, key == "stream_options" ? ["include_usage"] : []))224        }225        guard let hit = UnsupportedParameter.detect(failure, candidates: candidates) else { return false }226        body.removeValue(forKey: hit)227        return true228    }229}230231/// Turns chat-completion chunks into `StreamEvent`s. One instance per response.232struct ChatCompletionsStreamDecoder {233    private struct Call { var id: String; var name: String; var arguments = ""; var started = false }234235    let modelID: String236    let replay: ChatCompletionsDialect.Replay237    private(set) var started = false238    private(set) var finished = false239    private(set) var sawEvents = false240    private var calls: [Int: Call] = [:]241    /// Where fragments addressed to a wire index go. A server that reuses an index for a new call gets a fresh slot.242    private var slots: [Int: Int] = [:]243    private var lastSlot: Int?244    private var finishReason: String?245    private var emittedCalls = false246    private var responseID: String?247    /// Reasoning of this turn, kept only to be handed back with its tool calls.248    private var replayText = ""249    private var replayDetails: [JSONValue] = []250251    init(modelID: String, replay: ChatCompletionsDialect.Replay = .none) { self.modelID = modelID; self.replay = replay }252253    /// The state the turn's first tool call carries, in the dialect's format.254    private func turnState() -> JSONValue? {255        switch replay {256        case .none: return nil257        case .reasoningField(let format, _), .thinkingChunks(let format): return ProviderState.make(format, .string(replayText))258        case .reasoningDetails(let format): return ProviderState.make(format, .array(replayDetails))259        }260    }261262    /// Streamed `reasoning_details` chunks of one entry (same `index` and `type`) are joined: text, summary and data are263    /// concatenated in arrival order, every other field keeps the last value sent.264    private mutating func merge(details: [JSONValue]) {265        for chunk in details {266            guard case .object(let fields) = chunk else { continue }267            let position = replayDetails.lastIndex { $0["index"] == fields["index"] && $0["type"] == fields["type"] && fields["index"] != nil }268            guard let position, case .object(var merged) = replayDetails[position] else { replayDetails.append(chunk); continue }269            for (key, value) in fields {270                if ["text", "summary", "data"].contains(key), let old = merged[key]?.stringValue, let new = value.stringValue { merged[key] = .string(old + new) }271                else if !value.isNull || merged[key] == nil { merged[key] = value }272            }273            replayDetails[position] = .object(merged)274        }275    }276277    /// Feeds the `data:` payload of one SSE event.278    mutating func consume(_ data: String) throws -> [StreamEvent] {279        let trimmed = data.trimmingCharacters(in: .whitespaces)280        if trimmed.isEmpty { return [] }281        sawEvents = true282        if trimmed == "[DONE]" { return finish() }283        guard let json = JSONValue.parse(trimmed) else { throw AstraError.decoding("a stream chunk was not valid JSON") }284        return try consume(json)285    }286287    mutating func consume(_ json: JSONValue) throws -> [StreamEvent] {288        guard !finished else { return [] }289        if let error = json["error"], !error.isNull { throw Self.streamError(error, modelID: modelID) }290        var out: [StreamEvent] = []291        if !started {292            started = true293            responseID = json["id"]?.stringValue294            out.append(.messageStarted(MessageStart(responseID: responseID, reportedModel: json["model"]?.stringValue, servedBy: json["provider"]?.stringValue)))295        }296        for choice in json["choices"]?.arrayValue ?? [] where (choice["index"]?.intValue ?? 0) == 0 {297            // Streaming servers use `delta`; a server that ignored `stream` answers with a whole `message`.298            let delta = choice["delta"] ?? choice["message"]299            if let text = delta?["reasoning"]?.stringValue ?? delta?["reasoning_content"]?.stringValue, !text.isEmpty { out.append(.reasoningSummaryDelta(text)) }300            if let text = delta?["content"]?.stringValue, !text.isEmpty { out.append(.textDelta(text)) }301            switch replay {302            case .reasoningField(_, let field): if let text = delta?[field]?.stringValue { replayText += text }303            case .reasoningDetails: if let details = delta?["reasoning_details"]?.arrayValue { merge(details: details) }304            case .none, .thinkingChunks: break305            }306            // Mistral reasoning models send `content` as typed chunks: `{"type": "thinking", "thinking": [{"type": "text", "text"}]}`307            // carries the reasoning trace, `{"type": "text", "text"}` the answer. Other chunk types (references, files) are not text.308            for chunk in delta?["content"]?.arrayValue ?? [] {309                switch chunk["type"]?.stringValue {310                case "thinking":311                    let text = chunk["thinking"]?.arrayValue?.compactMap { $0["text"]?.stringValue }.joined() ?? chunk["thinking"]?.stringValue ?? ""312                    if !text.isEmpty { out.append(.reasoningSummaryDelta(text)) }313                    if case .thinkingChunks = replay { replayText += text }314                case "text":315                    if let text = chunk["text"]?.stringValue, !text.isEmpty { out.append(.textDelta(text)) }316                default: break317                }318            }319            if let text = delta?["refusal"]?.stringValue, !text.isEmpty { out.append(.textDelta(text)) }320            let fragments = delta?["tool_calls"]?.arrayValue ?? []321            for (position, fragment) in fragments.enumerated() {322                let newID = fragment["id"]?.stringValue.flatMap { $0.isEmpty ? nil : $0 }323                // The wire index when given; the position inside the chunk when a chunk carries several calls; otherwise the324                // call this fragment continues (the last one), or a new one when it brings its own id.325                let wire: Int326                if let given = fragment["index"]?.intValue { wire = given }327                else if fragments.count > 1 { wire = position }328                else if let newID, let known = calls.first(where: { $0.value.id == newID })?.key { wire = slots.first { $0.value == known }?.key ?? known }329                else if newID != nil { wire = (slots.keys.max() ?? -1) + 1 }330                else { wire = slots.first { $0.value == lastSlot }?.key ?? 0 }331                var index = slots[wire] ?? wire332                // A different id at an occupied index is a new call, not more arguments for the old one.333                if let newID, let existing = calls[index], !existing.id.isEmpty, existing.id != newID, existing.started {334                    index = (calls.keys.max() ?? -1) + 1335                }336                slots[wire] = index; lastSlot = index337                var call = calls[index] ?? Call(id: "", name: "")338                if let newID, call.id.isEmpty { call.id = newID }339                if let name = fragment["function"]?["name"]?.stringValue, !name.isEmpty, call.name.isEmpty { call.name = name }340                // Arguments are a JSON string in the protocol; some compatible servers send the object itself.341                let raw = fragment["function"]?["arguments"]342                let arguments = raw?.stringValue ?? (raw?.objectValue != nil ? raw?.serialized() : nil) ?? ""343                if !call.started, !call.name.isEmpty {344                    // Some servers never send an id: synthesise one that is stable within the response.345                    if call.id.isEmpty { call.id = "call_\(responseID ?? "astra")_\(index)" }346                    call.started = true347                    emittedCalls = true348                    out.append(.toolCallStarted(id: call.id, name: call.name))349                    if !call.arguments.isEmpty { out.append(.toolCallDelta(id: call.id, argumentsFragment: call.arguments)) }350                }351                call.arguments += arguments352                if call.started, !arguments.isEmpty { out.append(.toolCallDelta(id: call.id, argumentsFragment: arguments)) }353                calls[index] = call354            }355            if let reason = choice["finish_reason"]?.stringValue, !reason.isEmpty {356                if reason == "error" { throw AstraError.server(status: 502, message: "The provider ended the answer with an error.") }357                finishReason = reason358            }359            // Moonshot reports usage inside the finishing choice rather than at the top level.360            if let usage = Self.usage(choice["usage"]) { out.append(.usage(usage)) }361        }362        if let usage = Self.usage(json["usage"]) { out.append(.usage(usage)) }363        return out364    }365366    /// Ends the message: closes open tool calls and emits the single terminal event. Safe to call more than once.367    mutating func finish() -> [StreamEvent] {368        guard !finished else { return [] }369        finished = true370        var out: [StreamEvent] = []371        if !started { started = true; out.append(.messageStarted(MessageStart())) }372        var state = turnState()373        for index in calls.keys.sorted() {374            guard let call = calls[index], call.started else { continue }375            out.append(.toolCallCompleted(ToolCall(id: call.id, name: call.name, arguments: ToolArguments.parse(call.arguments), providerState: state)))376            state = nil     // turn-level state rides on the first call only377        }378        out.append(.messageCompleted(stopReason()))379        return out380    }381382    /// True once the provider has said how the message ended, even if `[DONE]` never arrives.383    var hasFinishReason: Bool { finishReason != nil }384385    private func stopReason() -> StopReason {386        switch finishReason {387        // A turn that announces tool calls but delivered none that can run (the name never arrived) did not end properly.388        case "tool_calls", "function_call":389            if emittedCalls { return .toolCalls }390            return calls.values.contains { !$0.started } ? .unknown : .toolCalls391        case "stop", "end_turn", "eos": return emittedCalls ? .toolCalls : .endOfTurn392        case "length", "max_tokens": return .maxTokens393        case "content_filter": return .contentFilter394        case "stop_sequence": return .stopSequence395        case nil: return emittedCalls ? .toolCalls : .unknown396        default: return .unknown397        }398    }399400    /// `prompt_tokens` is the whole prompt; cached and cache-write counts are subsets. `cost` is OpenRouter's own figure in US dollars.401    /// Cached input is `prompt_tokens_details.cached_tokens`; DeepSeek also sends `prompt_cache_hit_tokens`, Moonshot a flat `cached_tokens`.402    static func usage(_ json: JSONValue?) -> TokenUsage? {403        guard let json, json.objectValue != nil else { return nil }404        return TokenUsage(inputTokens: json["prompt_tokens"]?.intValue, outputTokens: json["completion_tokens"]?.intValue,405                          cachedInputTokens: json["prompt_tokens_details"]?["cached_tokens"]?.intValue ?? json["prompt_cache_hit_tokens"]?.intValue406                              ?? json["cached_tokens"]?.intValue,407                          cacheWriteTokens: json["prompt_tokens_details"]?["cache_write_tokens"]?.intValue,408                          reasoningTokens: json["completion_tokens_details"]?["reasoning_tokens"]?.intValue,409                          reportedCostUSD: json["cost"]?.doubleValue)410    }411412    /// An `error` object inside a 200 stream: its numeric `code` is an HTTP status (OpenRouter), otherwise classify by type.413    static func streamError(_ error: JSONValue, modelID: String) -> AstraError {414        let body = ProviderErrorBody.parse(.object(["error": error]))415        var status = error["code"]?.intValue ?? error["status"]?.intValue ?? 0416        if !(400..<600).contains(status) {417            let code = (body.code ?? "").lowercased()418            status = code.contains("rate_limit") ? 429 : code.contains("overloaded") || code.contains("unavailable") ? 503 : code.contains("context_length") || code.contains("invalid") ? 400 : 502419        }420        return mapHTTPError(status: status, code: body.code, message: body.message, retryAfter: nil, model: modelID)421    }422}423424/// Drives one chat-completions generation: request (with parameter fallback), chunk decoding, terminal-event guarantee.425func runChatCompletionsStream(http: ProviderHTTP, request: GenerationRequest, dialect: ChatCompletionsDialect, secrets: [String],426                              makeRequest: (JSONValue) throws -> URLRequest, continuation: EventContinuation) async throws {427    let modelID = request.model.modelID428    let body = ChatCompletionsEncoder.body(request, dialect: dialect)429    let (_, lines) = try await http.openAdjusting(body: body, modelID: modelID, secrets: secrets, makeRequest: makeRequest, normalize: dialect.normalize) { failure, body in430        if let adjust = dialect.adjust, adjust(failure, &body) { return true }431        return ChatCompletionsEncoder.adjust(failure, &body)432    }433    var parser = SSEParser()434    var decoder = ChatCompletionsStreamDecoder(modelID: modelID, replay: dialect.replay)435    var plain = ""   // a body that is not SSE at all (an error or a whole completion sent as JSON with status 200)436    for try await line in lines {437        if !decoder.sawEvents, !line.isEmpty, !line.hasPrefix("data:"), !line.hasPrefix(":"), !line.hasPrefix("event:"), !line.hasPrefix("id:"), !line.hasPrefix("retry:") {438            if plain.utf8.count < 4_000_000 { plain += line + "\n" }439            continue440        }441        guard let event = parser.feed(line) else { continue }442        for out in try decoder.consume(event.data) { continuation.yield(out) }443        if decoder.finished { return }444    }445    if let event = parser.finish() { for out in try decoder.consume(event.data) { continuation.yield(out) } }446    try Task.checkCancellation()447    if decoder.finished { return }448    if !decoder.sawEvents, let json = JSONValue.parse(plain) {449        for out in try decoder.consume(json) { continuation.yield(out) }450        for out in decoder.finish() { continuation.yield(out) }451        return452    }453    // Some servers close the connection after the final chunk without sending [DONE].454    guard decoder.hasFinishReason else { throw AstraError.network("The connection closed before the answer was complete.") }455    for out in decoder.finish() { continuation.yield(out) }456}457
Files main
Menu

Theme