SPB Git

Repository Public

NotesAPI+AINext.swift 6.2 KB 103 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/NotesAPI+AINext.swift3// Description: Routes of the 3.0 AI workstream (API-NEXT-AI §1, §3, §6, §7): the model catalogue, inline actions with4//              the new ids, voice transcription, smart database properties. (The synopsis is in NotesAPI+Knowledge.)5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension NotesAPI {11    // MARK: - Models1213    /// `GET /api/ai/models` — the catalogue: models (with creator, route, prices, capabilities and availability on a14    /// 3.0 server), providers, creators. Rules of a picker: group by `creator`, show the route badge, never offer a15    /// model whose `available` is false; "Auto" = send `model: nil`.16    public func aiModelCatalog(_ query: AIModelQuery = AIModelQuery()) async throws -> AIModelCatalog {17        var items: [URLQueryItem] = []18        if query.all { items.append(URLQueryItem(name: "all", value: "1")) }19        if let provider = query.provider { items.append(URLQueryItem(name: "provider", value: provider)) }20        if let creator = query.creator { items.append(URLQueryItem(name: "creator", value: creator)) }21        if query.availableOnly { items.append(URLQueryItem(name: "available", value: "1")) }22        if let text = query.text { items.append(URLQueryItem(name: "q", value: text)) }23        if query.includeUnavailable { items.append(URLQueryItem(name: "unavailable", value: "1")) }24        return try await client.decode(AIModelCatalog.self, .get("/api/ai/models", query: items))25    }2627    // MARK: - Inline actions2829    /// `POST /api/ai/action` with any action id (3.0: `coherence`, `questions`, `synthesis`, `structure`, `links`),30    /// streamed — **a paid model call**. Same error and cancellation rules as `aiAction(_: AIActionRequest)`; also31    /// `400 no_text`. `links` sends no `.text` event: its suggestions arrive in one `result` event32    /// (`AIEvent.linkSuggestions`), then `.done`.33    public func aiAction(_ call: AIActionCall) async throws -> AsyncThrowingStream<AIEvent, Error> {34        let (_, bytes) = try await client.openStream(.json(.post, "/api/ai/action", body: call))35        return Self.events(from: bytes)36    }3738    // MARK: - Voice3940    private struct TranscribeBody: Encodable {41        var summarize: Bool?42        var force: Bool?43    }4445    /// `POST /api/audio/<attachmentId>/transcribe` — queues the transcription (**a paid call**, never retried46    /// automatically). `202` when a job was queued (`queued == true`), `200` with the current state when a transcript47    /// exists or is pending. `415 not_audio`, `413 too_large` (> 25 MB), `503 not_configured | queue_unavailable`.48    /// - Parameters:49    ///   - summarize: also produce the summary (on a finished transcript without summary: queues the summary only).50    ///   - force: transcribe again.51    public func transcribeAudio(attachmentID: String, summarize: Bool? = nil, force: Bool? = nil) async throws -> AudioTranscription {52        try await client.decode(AudioTranscription.self, .json(.post, "/api/audio/\(HTTPRequest.segment(attachmentID))/transcribe", body: TranscribeBody(summarize: summarize, force: force)))53    }5455    /// `GET /api/audio/<attachmentId>` — the state of the transcript (`status: "none"` when never requested).56    /// Poll every 2–3 s while `isPending`.57    public func audioTranscription(attachmentID: String) async throws -> AudioTranscription {58        try await client.decode(AudioTranscription.self, .get("/api/audio/\(HTTPRequest.segment(attachmentID))"))59    }6061    // MARK: - Smart database properties6263    /// `GET /api/databases/<id>/ai/config` — the AI properties of a database with their configuration and run counters.64    public func databaseAIConfig(databaseID: String) async throws -> DatabaseAIConfig {65        try await client.decode(DatabaseAIConfig.self, .get("/api/databases/\(HTTPRequest.segment(databaseID))/ai/config"))66    }6768    private struct DatabaseAIConfigBody: Encodable {69        var propertyId: String70        var ai: DatabaseAISettingsPatch71    }7273    /// `PUT /api/databases/<id>/ai/config` `{propertyId, ai}` — partial, merged. `400 not_ai_property`, `404`.74    public func setDatabaseAIConfig(databaseID: String, propertyID: String, _ settings: DatabaseAISettingsPatch) async throws -> DatabaseAIProperty {75        try await client.decode(DatabaseAIProperty.self, .json(.put, "/api/databases/\(HTTPRequest.segment(databaseID))/ai/config", body: DatabaseAIConfigBody(propertyId: propertyID, ai: settings)))76    }7778    private struct DatabaseAIRunBody: Encodable {79        var propertyId: String80        var rowId: String?81        var rowIds: [String]?82        var force: Bool?83    }8485    /// `POST /api/databases/<id>/ai` `{propertyId, rowId | rowIds, force?}` — queues the AI cells (**paid model86    /// calls**). A cell typed by hand is skipped unless the property is `managed` or `force` is true (`skipped`).87    /// - Parameter rowIDs: 1…200 rows (a single id is sent as `rowId`).88    public func runDatabaseAI(databaseID: String, propertyID: String, rowIDs: [String], force: Bool? = nil) async throws -> DatabaseAIRunResult {89        let body = DatabaseAIRunBody(propertyId: propertyID, rowId: rowIDs.count == 1 ? rowIDs[0] : nil, rowIds: rowIDs.count == 1 ? nil : rowIDs, force: force)90        return try await client.decode(DatabaseAIRunResult.self, .json(.post, "/api/databases/\(HTTPRequest.segment(databaseID))/ai", body: body))91    }9293    /// `GET /api/databases/<id>/ai/runs` — the run log, newest first (≤ 500).94    public func databaseAIRuns(databaseID: String, _ filter: DatabaseAIRunFilter = DatabaseAIRunFilter()) async throws -> [DatabaseAIRun] {95        var items: [URLQueryItem] = []96        if let propertyId = filter.propertyId { items.append(URLQueryItem(name: "propertyId", value: propertyId)) }97        if let rowId = filter.rowId { items.append(URLQueryItem(name: "rowId", value: rowId)) }98        if let status = filter.status { items.append(URLQueryItem(name: "status", value: status)) }99        if let limit = filter.limit { items.append(URLQueryItem(name: "limit", value: String(limit))) }100        return try await client.decode([DatabaseAIRun].self, .get("/api/databases/\(HTTPRequest.segment(databaseID))/ai/runs", query: items))101    }102}103
Files main
Menu

Theme