SPB Git

Repository Public

ChatAPI+NextGen.swift 10.5 KB 157 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Core/API/ChatAPI+NextGen.swift4//  Description: Endpoints of backend 1.0 « Next Generation »: unified catalogue, providers and keys, model intelligence,5//               branches, timeline, context, constellation, Response Lens, Arena, sync feed.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation1213extension ChatAPI {14    private func loose(_ request: HTTPRequest) async throws -> JSONValue { try await http.decode(JSONValue.self, request) }1516    // MARK: catalogue1718    /// Direct models + the whole OpenRouter catalogue (≈ 450 models): cached by `ModelCatalog`, refreshed on the `model` sync event.19    func catalog() async throws -> ModelsResponse {20        var r = HTTPRequest.get("/api/models", query: [.init(name: "routes", value: "all")]); r.timeout = 6021        return try await http.decode(ModelsResponse.self, r)22    }23    func setModel(_ id: String, hidden: Bool) async throws { _ = try await http.data(.json("PATCH", "/api/models", object: ["id": .string(id), "hidden": .bool(hidden)])) }24    /// Model Favorites Dock (max 8), shared by the three apps.25    func setDock(_ ids: [String]) async throws { _ = try await http.data(.json("PATCH", "/api/models", object: ["dock": .array(ids.prefix(8).map(JSONValue.string))])) }26    func modelDetail(_ id: String) async throws -> ModelDetail {27        var r = HTTPRequest.get("/api/models/detail", query: [.init(name: "id", value: id)]); r.timeout = 4528        guard let d = ModelDetail(try await loose(r)) else { throw APIError.decoding("models/detail") }29        return d30    }31    /// Smart Model Router in advisory mode: proposes, never sends anything.32    func routeSuggestion(text: String, mode: RoutingMode = .auto, hasImages: Bool, wantsTools: Bool) async throws -> RouteSuggestion? {33        RouteSuggestion(try await loose(.json("POST", "/api/models/route-suggest", object: ["text": .string(String(text.prefix(20_000))), "mode": .string(mode == .manual ? "auto" : mode.rawValue), "hasImages": .bool(hasImages), "wantsTools": .bool(wantsTools)])))34    }35    /// Re-reads every provider listing and the OpenRouter catalogue on the server.36    func refreshModels() async throws { var r = HTTPRequest.json("POST", "/api/models/refresh"); r.timeout = 120; _ = try await http.data(r) }3738    // MARK: providers and keys (keys never leave the server; nothing is stored on the device)3940    func providers() async throws -> ProvidersResponse { ProvidersResponse(try await loose(.get("/api/providers"))) }41    /// Validates the key with the provider, stores it encrypted on the server and refreshes the catalogue. The server42    /// asks for a recent passkey verification (403 `reauth_required`): `HTTPClient.perform` runs it and replays once.43    func setProviderKey(_ provider: String, key: String) async throws {44        var r = HTTPRequest.json("PUT", "/api/providers/\(provider)/key", object: ["key": .string(key)]); r.timeout = 9045        _ = try await http.data(r)46    }47    /// Revokes the stored key. Returns true when a key of the server environment takes over.48    func deleteProviderKey(_ provider: String) async throws -> Bool {49        try await loose(HTTPRequest(method: "DELETE", path: "/api/providers/\(provider)/key")).bool("fallback") ?? false50    }51    func testProvider(_ provider: String) async throws -> ProviderCheck {52        var r = HTTPRequest.json("POST", "/api/providers/\(provider)/test"); r.timeout = 6053        let j = try await loose(r)54        return ProviderCheck(ok: j.bool("ok") ?? false, message: j.str("message") ?? "")55    }5657    // MARK: branches, timeline, context, constellation5859    func tree(conversation id: String) async throws -> ConversationTree { ConversationTree(try await loose(.get("/api/conversations/\(id)/tree"))) }60    func timeline(conversation id: String) async throws -> ConversationTimeline { ConversationTimeline(try await loose(.get("/api/conversations/\(id)/timeline"))) }61    func context(conversation id: String, model: String? = nil) async throws -> ContextReport {62        ContextReport(try await loose(.get("/api/conversations/\(id)/context", query: model.map { [.init(name: "model", value: $0)] } ?? [])))63    }64    func fork(conversation id: String, at messageId: String, label: String?) async throws -> Conversation {65        struct R: Decodable { var conversation: Conversation }66        var o: [String: JSONValue] = ["messageId": .string(messageId)]67        if let label = label?.trimmingCharacters(in: .whitespacesAndNewlines), !label.isEmpty { o["label"] = .string(String(label.prefix(80))) }68        return try await http.decode(R.self, .json("POST", "/api/conversations/\(id)/branch", object: o)).conversation69    }70    func constellation(limit: Int = 120, project: String? = nil) async throws -> Constellation {71        var q = [URLQueryItem(name: "limit", value: String(limit))]72        if let project { q.append(.init(name: "project", value: project)) }73        var r = HTTPRequest.get("/api/constellation", query: q); r.timeout = 6074        return Constellation(try await loose(r))75    }76    func search(_ query: String, filters: SearchFilters) async throws -> [SearchHit] {77        struct R: Decodable { var results: [SearchHit] }78        return try await http.decode(R.self, .get("/api/search", query: filters.queryItems(query))).results79    }8081    // MARK: Response Lens8283    func lenses(messageId: String) async throws -> (kinds: [LensKind], stored: [StoredLens]) {84        let j = try await loose(.get("/api/lens", query: [.init(name: "messageId", value: messageId)]))85        let kinds = j.list("kinds").compactMap { k in k.str("id").map { LensKind(id: $0, label: k.str("label") ?? $0, usesWeb: k.bool("usesWeb") ?? false) } }86        return (kinds, j.list("lenses").compactMap(StoredLens.init))87    }88    /// Starts a lens: a real model call (and real web searches for `verify`), streamed, stored per message.89    func openLens(messageId: String, lens: String, modelId: String?) async throws -> HTTPClient.StreamOpening {90        var o: [String: JSONValue] = ["messageId": .string(messageId), "lens": .string(lens)]91        if let modelId { o["modelId"] = .string(modelId) }92        var r = HTTPRequest.json("POST", "/api/lens", object: o); r.timeout = 30093        return try await http.openStream(r)94    }95    func deleteLens(_ id: String) async throws { _ = try await http.data(HTTPRequest(method: "DELETE", path: "/api/lens", query: [.init(name: "id", value: id)])) }9697    // MARK: Arena9899    func openCompare(prompt: String, modelIds: [String], effort: Effort?, projectId: String?, conversationId: String?) async throws -> HTTPClient.StreamOpening {100        var o: [String: JSONValue] = ["prompt": .string(prompt), "modelIds": .array(modelIds.map(JSONValue.string))]101        if let effort { o["settings"] = .object(["effort": .string(effort.rawValue)]) }102        if let projectId { o["projectId"] = .string(projectId) }103        if let conversationId { o["conversationId"] = .string(conversationId) }104        var r = HTTPRequest.json("POST", "/api/compare", object: o); r.timeout = 900105        return try await http.openStream(r)106    }107    func preferCompare(id: String, model: String) async throws { _ = try await http.data(.json("PATCH", "/api/compare", object: ["id": .string(id), "preferredModel": .string(model)])) }108    /// A model-generated opinion on the answers (the server says so in `disclaimer`).109    func judgeCompare(id: String, judgeModel: String) async throws -> ArenaJudgement {110        var r = HTTPRequest.json("POST", "/api/compare/judge", object: ["id": .string(id), "judgeModel": .string(judgeModel)]); r.timeout = 300111        guard let j = (try await loose(r))["judge"].flatMap(ArenaJudgement.init) else { throw APIError.decoding("compare/judge") }112        return j113    }114    /// Brings an Arena answer into a conversation as a new version of its last answer. No model is called again.115    func adopt(conversation id: String, comparisonId: String, modelId: String) async throws {116        _ = try await http.data(.json("POST", "/api/conversations/\(id)/adopt", object: ["comparisonId": .string(comparisonId), "modelId": .string(modelId)]))117    }118    func exportCompare(id: String, format: String) async throws -> Data {119        try await http.data(HTTPRequest(path: "/api/compare/export", query: [.init(name: "id", value: id), .init(name: "format", value: format)], accept: "*/*"))120    }121122    // MARK: sync123124    /// Long-lived change feed. The stream stays open; the server sends a comment every 20 s.125    func openEvents(after: Int) async throws -> HTTPClient.StreamOpening {126        var r = HTTPRequest.get("/api/events", query: [.init(name: "after", value: String(after))]); r.timeout = 90127        return try await http.openStream(r)128    }129    func sync(after: Int) async throws -> SyncPull { SyncPull(try await loose(.get("/api/sync", query: [.init(name: "after", value: String(after))]))) }130131    // MARK: prompts, projects, settings132133    func createPrompt(title: String, body: String, tags: [String], favorite: Bool) async throws {134        _ = try await http.data(.json("POST", "/api/prompts", object: ["title": .string(title), "body": .string(body), "tags": .array(tags.map(JSONValue.string)), "favorite": .bool(favorite)]))135    }136    func updatePrompt(_ id: String, title: String? = nil, body: String? = nil, tags: [String]? = nil, favorite: Bool? = nil) async throws {137        var o: [String: JSONValue] = [:]138        if let title { o["title"] = .string(title) }139        if let body { o["body"] = .string(body) }140        if let tags { o["tags"] = .array(tags.map(JSONValue.string)) }141        if let favorite { o["favorite"] = .bool(favorite) }142        _ = try await http.data(.json("PATCH", "/api/prompts/\(id)", object: o))143    }144    /// `.some(nil)` clears a field (instructions, default model).145    func updateProject(_ id: String, name: String? = nil, description: String?? = nil, instructions: String?? = nil, defaultModel: String?? = nil, color: String?? = nil) async throws -> Project {146        struct R: Decodable { var project: Project }147        var o: [String: JSONValue] = [:]148        if let name { o["name"] = .string(name) }149        if let v = description { o["description"] = v.map(JSONValue.string) ?? .null }150        if let v = instructions { o["instructions"] = v.map(JSONValue.string) ?? .null }151        if let v = defaultModel { o["defaultModel"] = v.map(JSONValue.string) ?? .null }152        if let v = color { o["color"] = v.map(JSONValue.string) ?? .null }153        return try await http.decode(R.self, .json("PATCH", "/api/projects/\(id)", object: o)).project154    }155    func deleteProject(_ id: String) async throws { _ = try await http.data(HTTPRequest(method: "DELETE", path: "/api/projects/\(id)")) }156}157
Files main
Menu

Theme