// Arteza SDK for Swift -- https://arteza.ai/developers/sdks // // One file, no dependencies (Foundation + CryptoKit). async/await. // // let arteza = try Arteza(apiKey: token) // in an app: a client token from YOUR server // let g = try await arteza.run("nano-banana-2", ["prompt": "A red fox in fresh snow"]) // print(g.files.first?.url ?? "") // // In an app, never ship your API key: your server mints a short-lived client // token (POST /v1/tokens, or `tokens.create` in the Node/Python SDKs) and the app // uses that. Requests that fail with 408/425/429/5xx or a network error are // retried with backoff, honouring Retry-After, and every create carries an // Idempotency-Key so a retry never charges twice. import Foundation #if canImport(CryptoKit) import CryptoKit #endif #if canImport(FoundationNetworking) import FoundationNetworking #endif public typealias JSON = [String: Any] // MARK: - Errors /// An error answered by the API. Branch on `code`; `message` is English prose and may change. public struct ArtezaError: Error, CustomStringConvertible { public let status: Int public let code: String public let type: String public let message: String public let param: String? public let requestId: String? public let docURL: String? public var description: String { "Arteza \(status) \(code): \(message)" + (requestId.map { " (request \($0))" } ?? "") } } /// A generation that settled as failed or canceled. Its charge was refunded. public struct GenerationFailedError: Error, CustomStringConvertible { public let generation: Generation public var code: String { generation.errorCode ?? generation.status } public var retryable: Bool { generation.errorRetryable } public var description: String { "Generation \(generation.id) \(generation.status): \(generation.errorMessage ?? code)" } } /// `wait` gave up before the generation settled; it is still running. public struct WaitTimeoutError: Error { public let generation: Generation } // MARK: - Generation /// A generation as the API returns it. `raw` holds every field, including ones /// added after this SDK version. public struct Generation { public let raw: JSON public init(_ raw: JSON) { self.raw = raw } public var id: String { raw["id"] as? String ?? "" } public var status: String { raw["status"] as? String ?? "" } public var model: String { raw["model"] as? String ?? "" } public var isSettled: Bool { ["completed", "failed", "canceled"].contains(status) } public struct File { public let url: String; public let type: String } public var files: [File] { let out = (raw["output"] as? JSON)?["files"] as? [JSON] ?? [] return out.compactMap { f in (f["url"] as? String).map { File(url: $0, type: f["type"] as? String ?? "file") } } } public var errorCode: String? { (raw["error"] as? JSON)?["code"] as? String } public var errorMessage: String? { (raw["error"] as? JSON)?["message"] as? String } public var errorRetryable: Bool { (raw["error"] as? JSON)?["retryable"] as? Bool ?? false } public var metadata: [String: String] { raw["metadata"] as? [String: String] ?? [:] } } // MARK: - Client public final class Arteza { public static let version = "0.5.0" public static let defaultBaseURL = URL(string: "https://arteza.ai/api/v1")! public let baseURL: URL public let maxRetries: Int public let timeout: TimeInterval private let apiKey: String private let session: URLSession private let userAgent: String public lazy var models = Models(self) public lazy var apps = Apps(self) public lazy var generations = Generations(self) public lazy var uploads = Uploads(self) public lazy var tokens = Tokens(self) public lazy var usage = Usage(self) public lazy var studios = Studios(self) /// - Parameter apiKey: an `ark_live_` key on a server, or an `ark_tok_` client token in an app. public init(apiKey: String? = nil, baseURL: URL? = nil, timeout: TimeInterval = 60, maxRetries: Int = 3, appName: String? = nil, session: URLSession = .shared) throws { guard let key = apiKey ?? ProcessInfo.processInfo.environment["ARTEZA_API_KEY"], !key.isEmpty else { throw ArtezaError(status: 0, code: "missing_api_key", type: "authentication_error", message: "No API key. Pass apiKey, or set ARTEZA_API_KEY. Create one at https://arteza.ai/developers/console", param: nil, requestId: nil, docURL: nil) } self.apiKey = key self.baseURL = baseURL ?? ProcessInfo.processInfo.environment["ARTEZA_BASE_URL"].flatMap(URL.init(string:)) ?? Arteza.defaultBaseURL self.timeout = timeout self.maxRetries = maxRetries self.session = session self.userAgent = "arteza-swift/\(Arteza.version)" + (appName.map { " \($0)" } ?? "") } // MARK: transport /// Any endpoint: `try await arteza.request("GET", "/studios")`. Returns the decoded JSON. @discardableResult public func request(_ method: String, _ path: String, body: Any? = nil, idempotencyKey: String? = nil) async throws -> Any { var req = URLRequest(url: url(path), timeoutInterval: timeout) req.httpMethod = method req.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") req.setValue("application/json", forHTTPHeaderField: "Accept") req.setValue(userAgent, forHTTPHeaderField: "X-Arteza-Client") if let body { req.httpBody = try JSONSerialization.data(withJSONObject: body) req.setValue("application/json", forHTTPHeaderField: "Content-Type") } if let idempotencyKey { req.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") } var attempt = 0 while true { do { let (data, res) = try await session.data(for: req) let http = res as! HTTPURLResponse if (200..<300).contains(http.statusCode) { return data.isEmpty ? [:] as JSON : try JSONSerialization.jsonObject(with: data) } let err = Arteza.error(http, data) guard [408, 425, 429, 500, 502, 503, 504].contains(http.statusCode), attempt < maxRetries else { throw err } let wait = (http.value(forHTTPHeaderField: "Retry-After")).flatMap(Double.init) ?? Arteza.backoff(attempt) try await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000)) } catch let e as URLError where attempt < maxRetries && e.code != .cancelled { try await Task.sleep(nanoseconds: UInt64(Arteza.backoff(attempt) * 1_000_000_000)) } attempt += 1 } } func json(_ method: String, _ path: String, body: Any? = nil, idempotencyKey: String? = nil) async throws -> JSON { (try await request(method, path, body: body, idempotencyKey: idempotencyKey)) as? JSON ?? [:] } /// A Server-Sent Events stream as (event, data) pairs, until the server closes it. public func events(_ path: String) -> AsyncThrowingStream<(event: String, data: JSON), Error> { AsyncThrowingStream { continuation in let task = Task { do { var req = URLRequest(url: url(path), timeoutInterval: 330) req.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") req.setValue("text/event-stream", forHTTPHeaderField: "Accept") req.setValue(userAgent, forHTTPHeaderField: "X-Arteza-Client") let (bytes, res) = try await session.bytes(for: req) let http = res as! HTTPURLResponse guard http.statusCode == 200 else { var data = Data() for try await b in bytes { data.append(b) } throw Arteza.error(http, data) } var event = "message", lines: [String] = [] for try await line in bytes.lines { if line.hasPrefix("event:") { event = line.dropFirst(6).trimmingCharacters(in: .whitespaces) } else if line.hasPrefix("data:") { lines.append(line.dropFirst(5).trimmingCharacters(in: .whitespaces)) } else if line.isEmpty || line.hasPrefix(":") { continue } // `bytes.lines` drops the blank separator line, so a data line closes the event. if !lines.isEmpty, let d = lines.joined(separator: "\n").data(using: .utf8), let obj = try? JSONSerialization.jsonObject(with: d) as? JSON { continuation.yield((event, obj)) event = "message"; lines = [] } } continuation.finish() } catch { continuation.finish(throwing: error) } } continuation.onTermination = { _ in task.cancel() } } } // MARK: top level /// Price a request without running it. Free. public func estimate(model: String? = nil, app: String? = nil, input: JSON) async throws -> JSON { try await json("POST", "/estimate", body: app.map { ["app": $0, "input": input] } ?? ["model": model ?? "auto", "input": input]) } /// Credits, USD balance and plan. public func balance() async throws -> JSON { try await json("GET", "/balance") } /// Create a generation and wait for it. Throws GenerationFailedError if it fails (it was refunded). public func run(_ model: String, _ input: JSON, webhookURL: String? = nil, metadata: [String: String]? = nil, timeout: TimeInterval = 900) async throws -> Generation { let g = try await generations.create(model: model, input: input, webhookURL: webhookURL, metadata: metadata) return try await generations.wait(g.id, timeout: timeout) } /// Run one of the studio's apps (GET /v1/apps) and wait for it. public func runApp(_ app: String, _ input: JSON, timeout: TimeInterval = 900) async throws -> Generation { let g = try await generations.create(app: app, input: input) return try await generations.wait(g.id, timeout: timeout) } // MARK: helpers func url(_ path: String) -> URL { path.hasPrefix("http") ? URL(string: path)! : URL(string: baseURL.absoluteString + path)! } static func backoff(_ attempt: Int) -> Double { let base = min(8.0, 0.5 * pow(2.0, Double(attempt))) return base / 2 + Double.random(in: 0...(base / 2)) } static func error(_ http: HTTPURLResponse, _ data: Data) -> ArtezaError { let e = ((try? JSONSerialization.jsonObject(with: data)) as? JSON)?["error"] as? JSON ?? [:] return ArtezaError(status: http.statusCode, code: e["code"] as? String ?? "http_\(http.statusCode)", type: e["type"] as? String ?? "api_error", message: e["message"] as? String ?? "HTTP \(http.statusCode)", param: e["param"] as? String, requestId: e["request_id"] as? String ?? http.value(forHTTPHeaderField: "X-Request-Id"), docURL: e["doc_url"] as? String) } static func query(_ items: [String: String?]) -> String { var c = URLComponents() c.queryItems = items.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name } return c.queryItems?.isEmpty == false ? "?" + (c.percentEncodedQuery ?? "") : "" } // MARK: resources public struct Models { let c: Arteza; init(_ c: Arteza) { self.c = c } public func list(category: String? = nil) async throws -> [JSON] { (try await c.json("GET", "/models" + Arteza.query(["category": category])))["data"] as? [JSON] ?? [] } public func retrieve(_ id: String) async throws -> JSON { try await c.json("GET", "/models/\(id)") } } public struct Apps { let c: Arteza; init(_ c: Arteza) { self.c = c } public func list(category: String? = nil) async throws -> [JSON] { (try await c.json("GET", "/apps" + Arteza.query(["category": category])))["data"] as? [JSON] ?? [] } public func retrieve(_ id: String) async throws -> JSON { try await c.json("GET", "/apps/\(id)") } } public struct Generations { let c: Arteza; init(_ c: Arteza) { self.c = c } /// Start a generation (202). Pass `model` or `app`. Carries an Idempotency-Key, so retries never charge twice. public func create(model: String? = nil, app: String? = nil, input: JSON, webhookURL: String? = nil, metadata: [String: String]? = nil, idempotencyKey: String = UUID().uuidString) async throws -> Generation { var body: JSON = ["input": input] if let app { body["app"] = app } else { body["model"] = model ?? "auto" } if let webhookURL { body["webhook_url"] = webhookURL } if let metadata { body["metadata"] = metadata } return Generation(try await c.json("POST", "/generations", body: body, idempotencyKey: idempotencyKey)) } public func retrieve(_ id: String) async throws -> Generation { Generation(try await c.json("GET", "/generations/\(id)")) } public func list(limit: Int = 20, cursor: String? = nil, model: String? = nil) async throws -> (data: [Generation], nextCursor: String?) { let j = try await c.json("GET", "/generations" + Arteza.query(["limit": String(limit), "cursor": cursor, "model": model])) return ((j["data"] as? [JSON] ?? []).map(Generation.init), (j["has_more"] as? Bool == true) ? j["next_cursor"] as? String : nil) } /// Cancel a queued generation; its charge is refunded. public func cancel(_ id: String) async throws -> Generation { Generation(try await c.json("POST", "/generations/\(id)/cancel", body: [String: Any]())) } /// Move a finished generation to the trash (restorable for 30 days). public func delete(_ id: String) async throws -> JSON { try await c.json("DELETE", "/generations/\(id)") } /// Poll until settled, backing off from 1s to 5s. Throws GenerationFailedError on failed/canceled. public func wait(_ id: String, timeout: TimeInterval = 900) async throws -> Generation { let deadline = Date().addingTimeInterval(timeout) var interval = 1.0 while true { let g = try await retrieve(id) if g.status == "completed" { return g } if g.isSettled { throw GenerationFailedError(generation: g) } if Date() > deadline { throw WaitTimeoutError(generation: g) } try await Task.sleep(nanoseconds: UInt64(interval * 1_000_000_000)) interval = min(5, interval * 1.5) } } /// Follow one generation live: yields it on every status change, ending with the settled one. public func stream(_ id: String) -> AsyncThrowingStream { let source = c.events("/generations/\(id)/stream") return AsyncThrowingStream { cont in let t = Task { do { for try await e in source where e.event == "generation" { cont.yield(Generation(e.data)) }; cont.finish() } catch { cont.finish(throwing: error) } } cont.onTermination = { _ in t.cancel() } } } /// Every generation on the account, live, on one connection (GET /v1/events). /// Pass `since` to replay changes after that moment. public func events(since: Date? = nil) -> AsyncThrowingStream { let q = since.map { Arteza.query(["since": ISO8601DateFormatter().string(from: $0)]) } ?? "" let source = c.events("/events" + q) return AsyncThrowingStream { cont in let t = Task { do { for try await e in source where e.event == "generation" { cont.yield(Generation(e.data)) }; cont.finish() } catch { cont.finish(throwing: error) } } cont.onTermination = { _ in t.cancel() } } } } public struct Uploads { let c: Arteza; init(_ c: Arteza) { self.c = c } /// Upload bytes (an image, video or audio file) and return the `url` to pass as a model input. public func upload(_ data: Data, contentType: String) async throws -> String { let up = try await c.json("POST", "/uploads", body: ["content_type": contentType, "size": data.count]) guard let put = (up["upload_url"] as? String).flatMap(URL.init(string:)), let url = up["url"] as? String else { throw ArtezaError(status: 0, code: "invalid_response", type: "api_error", message: "The upload answer had no upload_url.", param: nil, requestId: nil, docURL: nil) } var req = URLRequest(url: put) req.httpMethod = "PUT" for (k, v) in up["headers"] as? [String: String] ?? [:] { req.setValue(v, forHTTPHeaderField: k) } let (_, res) = try await c.session.upload(for: req, from: data) guard let http = res as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { throw ArtezaError(status: (res as? HTTPURLResponse)?.statusCode ?? 0, code: "upload_failed", type: "api_error", message: "The file could not be stored.", param: nil, requestId: nil, docURL: nil) } return url } } public struct Tokens { let c: Arteza; init(_ c: Arteza) { self.c = c } /// Mint a short-lived client token (server side, with your API key). public func create(ttlSeconds: Int? = nil, models: [String]? = nil, maxSpend: Double? = nil, user: String? = nil) async throws -> JSON { var b: JSON = [:] if let ttlSeconds { b["ttl_seconds"] = ttlSeconds } if let models { b["models"] = models } if let maxSpend { b["max_spend"] = maxSpend } if let user { b["user"] = user } return try await c.json("POST", "/tokens", body: b) } } public struct Usage { let c: Arteza; init(_ c: Arteza) { self.c = c } public func get(from: String? = nil, to: String? = nil, groupBy: String = "day") async throws -> JSON { try await c.json("GET", "/usage" + Arteza.query(["from": from, "to": to, "group_by": groupBy])) } } /// Fashion Studio and AI Influencer. Bodies are the JSON the docs show (developers/docs/studios). public struct Studios { let c: Arteza; init(_ c: Arteza) { self.c = c } public func list() async throws -> JSON { try await c.json("GET", "/studios") } public func catalog(_ studio: String, kind: String? = nil) async throws -> JSON { try await c.json("GET", "/studios/\(studio)/catalog" + Arteza.query(["kind": kind])) } public func start(_ path: String, _ body: JSON) async throws -> JSON { try await c.json("POST", "/studios/\(path)", body: body, idempotencyKey: UUID().uuidString) } public func job(_ id: String) async throws -> JSON { try await c.json("GET", "/studios/jobs/\(id)") } } } // MARK: - Webhooks #if canImport(CryptoKit) /// Verify a webhook (Standard Webhooks headers) and return its parsed event. /// - Parameters: rawBody is the request body exactly as received; secret is `whsec_...` from the console. public func verifyWebhook(rawBody: Data, headers: [String: String], secret: String, tolerance: TimeInterval = 300) throws -> JSON { let h = Dictionary(uniqueKeysWithValues: headers.map { ($0.key.lowercased(), $0.value) }) guard let id = h["webhook-id"], let ts = h["webhook-timestamp"], let sigs = h["webhook-signature"], let t = Double(ts) else { throw ArtezaError(status: 400, code: "invalid_signature", type: "webhook_error", message: "Missing webhook headers.", param: nil, requestId: nil, docURL: nil) } guard abs(Date().timeIntervalSince1970 - t) <= tolerance else { throw ArtezaError(status: 400, code: "invalid_signature", type: "webhook_error", message: "Webhook timestamp is too old.", param: nil, requestId: nil, docURL: nil) } let keyData = Data(base64Encoded: secret.hasPrefix("whsec_") ? String(secret.dropFirst(6)) : secret) ?? Data() var signed = Data("\(id).\(ts).".utf8); signed.append(rawBody) let expected = Data(HMAC.authenticationCode(for: signed, using: SymmetricKey(data: keyData))).base64EncodedString() let ok = sigs.split(separator: " ").contains { part in let sig = part.split(separator: ",", maxSplits: 1).last.map(String.init) ?? "" return sig.count == expected.count && zip(sig.utf8, expected.utf8).reduce(0) { $0 | ($1.0 ^ $1.1) } == 0 } guard ok else { throw ArtezaError(status: 400, code: "invalid_signature", type: "webhook_error", message: "Webhook signature does not match.", param: nil, requestId: nil, docURL: nil) } return (try JSONSerialization.jsonObject(with: rawBody)) as? JSON ?? [:] } #endif