SPB Git

Repository Public

ChatStreamEvent.swift 8.0 KB 156 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Chat9// File             : SPChat-iOS/Core/Streaming/ChatStreamEvent.swift10// Description      : Typed events of a generation run, decoded from the11//                    backend's SSE vocabulary.12// Module           : SPChat-iOS13// Repository       : https://git.spboucher.ai/sp-chat-ios14// Created          : 2026-11-1915// Last Modified    : 2026-11-1916//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation9091enum ChatStreamEvent: Sendable, Equatable {92    case run(id: String)93    /// The server trimmed its replay buffer: reload the conversation, then continue with live events.94    case resync95    case conversation(id: String, created: Bool, userMessageId: String?, regenerated: String?, edited: String?)96    case start(messageId: String, model: String?, provider: String?, routing: MessageRouting?, applied: AppliedParams?)97    case text(String)98    case reasoning(String)99    case toolCall(ToolCall)100    case toolResult(id: String, status: ToolCallStatus, output: JSONValue?, error: String?, durationMs: Int?)101    case part(MessagePart)102    case artifacts([Artifact])103    case usage(usage: TokenUsage?, costUsd: Double?, latencyMs: Int?, ttftMs: Int?, exactCost: Bool)104    case followups(messageId: String?, suggestions: [String])105    case status(status: String, error: String?, code: String?)106    case meta(servedBy: String?, retrying: String?)107    case title(String)108    case warning(String)109    case error(message: String, code: String?, partial: Bool)110    case done(status: String?)111    case end112    case unknown(String)113114    init(sse: SSEEvent) {115        let json = (try? JSONDecoder().decode(JSONValue.self, from: Data(sse.data.utf8))) ?? .null116        func str(_ k: String) -> String? { json[k]?.stringValue }117        func decode<T: Decodable>(_ type: T.Type, _ v: JSONValue?) -> T? {118            guard let v, !v.isNull, let d = try? JSONEncoder().encode(v) else { return nil }119            return try? JSONDecoder().decode(T.self, from: d)120        }121        switch sse.event {122        case "run": self = .run(id: str("runId") ?? "")123        case "resync": self = .resync124        case "conversation":125            self = .conversation(id: str("id") ?? "", created: json["created"]?.boolValue ?? false, userMessageId: str("userMessageId"), regenerated: str("regenerated"), edited: str("edited"))126        case "start":127            self = .start(messageId: str("messageId") ?? "", model: str("model"), provider: str("provider"), routing: decode(MessageRouting.self, json["routing"]), applied: decode(AppliedParams.self, json["applied"]))128        case "text": self = .text(str("delta") ?? "")129        case "reasoning": self = .reasoning(str("delta") ?? "")130        case "tool_call":131            self = .toolCall(ToolCall(id: str("id") ?? "", name: str("name") ?? "outil", input: json["input"] ?? .null, status: ToolCallStatus(rawValue: str("status") ?? "") ?? .running))132        case "tool_result":133            self = .toolResult(id: str("id") ?? "", status: ToolCallStatus(rawValue: str("status") ?? "") ?? .ok, output: json["output"], error: str("error"), durationMs: json["durationMs"]?.intValue)134        case "part": self = decode(MessagePart.self, json).map(ChatStreamEvent.part) ?? .unknown("part")135        case "artifacts":136            // [{id, title, type, language}] — rows created for substantial code blocks of the answer137            let list: [Artifact] = (json.arrayValue ?? []).compactMap { a in138                guard let id = a["id"]?.stringValue else { return nil }139                return Artifact(id: id, rootId: id, version: 1, type: a["type"]?.stringValue ?? "text", language: a["language"]?.stringValue, title: a["title"]?.stringValue ?? "Artefact", saved: false, messageId: nil, content: nil)140            }141            self = .artifacts(list)142        case "usage":143            self = .usage(usage: decode(TokenUsage.self, json["usage"]), costUsd: json["costUsd"]?.doubleValue, latencyMs: json["latencyMs"]?.intValue, ttftMs: json["ttftMs"]?.intValue, exactCost: json["exactCost"]?.boolValue ?? false)144        case "followups": self = .followups(messageId: str("messageId"), suggestions: (json["suggestions"]?.arrayValue ?? []).compactMap(\.stringValue))145        case "status": self = .status(status: str("status") ?? "complete", error: str("error"), code: str("code"))146        case "meta": self = .meta(servedBy: str("servedBy"), retrying: json["retrying"].flatMap { $0.stringValue ?? $0.intValue.map(String.init) })147        case "title": self = .title(str("title") ?? "")148        case "warning": self = .warning(str("message") ?? "")149        case "error": self = .error(message: str("message") ?? String(localized: "Erreur"), code: str("code"), partial: json["partial"]?.boolValue ?? false)150        case "done": self = .done(status: str("status"))151        case "end": self = .end152        default: self = .unknown(sse.event)153        }154    }155}156
Files main
Menu

Theme