// Arteza SDK for Kotlin (Android and the JVM) -- https://arteza.ai/developers/sdks // // One file, no dependencies: java.net.HttpURLConnection and a small JSON codec, // so it drops into an Android app or any JVM 11+ project as it is. // Calls are blocking: run them off the main thread (Dispatchers.IO, an executor). // // val arteza = Arteza(apiKey = clientToken) // in an app: a client token from YOUR server // val g = arteza.run("nano-banana-2", mapOf("prompt" to "A red fox in fresh snow")) // println(g.files.first().url) // // 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. @file:Suppress("UNCHECKED_CAST") package ai.arteza import java.io.ByteArrayOutputStream import java.io.IOException import java.net.HttpURLConnection import java.net.URI import java.net.URLEncoder import java.util.Base64 import java.util.UUID import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec import kotlin.math.abs import kotlin.math.min import kotlin.math.pow import kotlin.random.Random typealias JsonObject = Map /** An error answered by the API. Branch on [code]; [message] is English prose and may change. */ class ArtezaException( val status: Int, val code: String, val type: String, override val message: String, val param: String? = null, val requestId: String? = null, val docUrl: String? = null, ) : RuntimeException("Arteza $status $code: $message" + (requestId?.let { " (request $it)" } ?: "")) /** A generation that settled as failed or canceled. Its charge was refunded. */ class GenerationFailedException(val generation: Generation) : RuntimeException("Generation ${generation.id} ${generation.status}: ${generation.errorMessage ?: generation.errorCode ?: ""}") /** wait() gave up before the generation settled; it is still running. */ class WaitTimeoutException(val generation: Generation) : RuntimeException("Generation ${generation.id} is still ${generation.status}") /** A generation as the API returns it. [raw] holds every field, including ones added after this SDK version. */ class Generation(val raw: JsonObject) { val id: String get() = raw["id"] as? String ?: "" val status: String get() = raw["status"] as? String ?: "" val model: String get() = raw["model"] as? String ?: "" val isSettled: Boolean get() = status in setOf("completed", "failed", "canceled") data class File(val url: String, val type: String) val files: List get() = (((raw["output"] as? JsonObject)?.get("files")) as? List ?: emptyList()) .mapNotNull { f -> (f["url"] as? String)?.let { File(it, f["type"] as? String ?: "file") } } val errorCode: String? get() = (raw["error"] as? JsonObject)?.get("code") as? String val errorMessage: String? get() = (raw["error"] as? JsonObject)?.get("message") as? String val errorRetryable: Boolean get() = (raw["error"] as? JsonObject)?.get("retryable") as? Boolean ?: false val metadata: Map get() = raw["metadata"] as? Map ?: emptyMap() override fun toString() = "Generation($id, $status)" } class Arteza( apiKey: String? = null, baseUrl: String? = null, val timeoutMs: Int = 60_000, val maxRetries: Int = 3, appName: String? = null, ) { companion object { const val VERSION = "0.5.0" const val DEFAULT_BASE_URL = "https://arteza.ai/api/v1" private val RETRYABLE = setOf(408, 425, 429, 500, 502, 503, 504) } private val apiKey: String = apiKey ?: System.getenv("ARTEZA_API_KEY") ?: throw ArtezaException(0, "missing_api_key", "authentication_error", "No API key. Pass apiKey, or set ARTEZA_API_KEY. Create one at https://arteza.ai/developers/console") val baseUrl: String = (baseUrl ?: System.getenv("ARTEZA_BASE_URL") ?: DEFAULT_BASE_URL).trimEnd('/') private val userAgent = "arteza-kotlin/$VERSION" + (appName?.let { " $it" } ?: "") val models = Models(); val apps = Apps(); val generations = Generations() val uploads = Uploads(); val tokens = Tokens(); val usage = Usage(); val studios = Studios() // ── transport ────────────────────────────────────────────────────────── /** Any endpoint: `arteza.request("GET", "/studios")`. Returns the decoded JSON. */ fun request(method: String, path: String, body: Any? = null, idempotencyKey: String? = null): Any? { val payload = body?.let { Json.write(it).toByteArray(Charsets.UTF_8) } var attempt = 0 while (true) { val conn = open(method, path) try { conn.setRequestProperty("Accept", "application/json") idempotencyKey?.let { conn.setRequestProperty("Idempotency-Key", it) } if (payload != null) { conn.doOutput = true conn.setRequestProperty("Content-Type", "application/json") conn.outputStream.use { it.write(payload) } } val status = conn.responseCode if (status in 200..299) { val text = conn.inputStream.use { it.readBytes() }.toString(Charsets.UTF_8) return if (text.isBlank()) emptyMap() else Json.parse(text) } val err = errorOf(conn, status) if (status !in RETRYABLE || attempt >= maxRetries) throw err Thread.sleep(((conn.getHeaderField("Retry-After")?.toDoubleOrNull() ?: backoff(attempt)) * 1000).toLong()) } catch (e: IOException) { if (attempt >= maxRetries) throw e Thread.sleep((backoff(attempt) * 1000).toLong()) } finally { conn.disconnect() } attempt++ } } internal fun obj(method: String, path: String, body: Any? = null, idem: String? = null): JsonObject = request(method, path, body, idem) as? JsonObject ?: emptyMap() /** A Server-Sent Events stream as (event, data) pairs; [onEvent] returns false to stop early. Blocks until the server closes. */ fun events(path: String, onEvent: (event: String, data: JsonObject) -> Boolean) { val conn = open("GET", path, readTimeoutMs = 330_000) try { conn.setRequestProperty("Accept", "text/event-stream") val status = conn.responseCode if (status != 200) throw errorOf(conn, status) conn.inputStream.bufferedReader(Charsets.UTF_8).use { r -> var event = "message"; val data = StringBuilder() while (true) { val line = r.readLine() ?: break when { line.isEmpty() -> { if (data.isNotEmpty()) { val parsed = Json.parse(data.toString()) as? JsonObject ?: emptyMap() if (!onEvent(event, parsed)) return } event = "message"; data.setLength(0) } line.startsWith("event:") -> event = line.substring(6).trim() line.startsWith("data:") -> { if (data.isNotEmpty()) data.append('\n'); data.append(line.substring(5).trim()) } } } } } finally { conn.disconnect() } } private fun open(method: String, path: String, readTimeoutMs: Int = timeoutMs): HttpURLConnection { val url = URI(if (path.startsWith("http")) path else baseUrl + path).toURL() return (url.openConnection() as HttpURLConnection).apply { requestMethod = method connectTimeout = timeoutMs readTimeout = readTimeoutMs setRequestProperty("Authorization", "Bearer $apiKey") setRequestProperty("User-Agent", userAgent) setRequestProperty("X-Arteza-Client", userAgent) } } private fun errorOf(conn: HttpURLConnection, status: Int): ArtezaException { val text = try { conn.errorStream?.use { it.readBytes() }?.toString(Charsets.UTF_8) } catch (_: IOException) { null } val e = (text?.let { runCatching { Json.parse(it) }.getOrNull() } as? JsonObject)?.get("error") as? JsonObject ?: emptyMap() return ArtezaException(status, e["code"] as? String ?: "http_$status", e["type"] as? String ?: "api_error", e["message"] as? String ?: "HTTP $status", e["param"] as? String, e["request_id"] as? String ?: conn.getHeaderField("X-Request-Id"), e["doc_url"] as? String) } private fun backoff(attempt: Int): Double { val base = min(8.0, 0.5 * 2.0.pow(attempt)) return base / 2 + Random.nextDouble() * base / 2 } internal fun query(vararg items: Pair): String { val q = items.filter { it.second != null }.joinToString("&") { "${it.first}=${URLEncoder.encode(it.second, "UTF-8")}" } return if (q.isEmpty()) "" else "?$q" } // ── top level ───────────────────────────────────────────────────────── /** Price a request without running it. Free. */ fun estimate(model: String? = null, app: String? = null, input: Map): JsonObject = obj("POST", "/estimate", if (app != null) mapOf("app" to app, "input" to input) else mapOf("model" to (model ?: "auto"), "input" to input)) /** Credits, USD balance and plan. */ fun balance(): JsonObject = obj("GET", "/balance") /** Create a generation and wait for it. Throws GenerationFailedException if it fails (it was refunded). */ fun run(model: String, input: Map, webhookUrl: String? = null, metadata: Map? = null, timeoutMs: Long = 900_000): Generation = generations.wait(generations.create(model = model, input = input, webhookUrl = webhookUrl, metadata = metadata).id, timeoutMs) /** Run one of the studio's apps (GET /v1/apps) and wait for it. */ fun runApp(app: String, input: Map, timeoutMs: Long = 900_000): Generation = generations.wait(generations.create(app = app, input = input).id, timeoutMs) // ── resources ───────────────────────────────────────────────────────── inner class Models { fun list(category: String? = null): List = obj("GET", "/models" + query("category" to category))["data"] as? List ?: emptyList() fun retrieve(id: String): JsonObject = obj("GET", "/models/$id") } inner class Apps { fun list(category: String? = null): List = obj("GET", "/apps" + query("category" to category))["data"] as? List ?: emptyList() fun retrieve(id: String): JsonObject = obj("GET", "/apps/$id") } inner class Generations { /** Start a generation (202). Pass [model] or [app]. Carries an Idempotency-Key, so retries never charge twice. */ fun create(model: String? = null, app: String? = null, input: Map, webhookUrl: String? = null, metadata: Map? = null, idempotencyKey: String = UUID.randomUUID().toString()): Generation { val body = linkedMapOf("input" to input) if (app != null) body["app"] = app else body["model"] = model ?: "auto" webhookUrl?.let { body["webhook_url"] = it } metadata?.let { body["metadata"] = it } return Generation(obj("POST", "/generations", body, idempotencyKey)) } fun retrieve(id: String) = Generation(obj("GET", "/generations/$id")) fun list(limit: Int = 20, cursor: String? = null, model: String? = null): Pair, String?> { val j = obj("GET", "/generations" + query("limit" to limit.toString(), "cursor" to cursor, "model" to model)) val data = (j["data"] as? List ?: emptyList()).map(::Generation) return data to (if (j["has_more"] == true) j["next_cursor"] as? String else null) } /** Cancel a queued generation; its charge is refunded. */ fun cancel(id: String) = Generation(obj("POST", "/generations/$id/cancel", emptyMap())) /** Move a finished generation to the trash (restorable for 30 days). */ fun delete(id: String): JsonObject = obj("DELETE", "/generations/$id") /** Poll until settled, backing off from 1s to 5s. Throws GenerationFailedException on failed/canceled. */ fun wait(id: String, timeoutMs: Long = 900_000): Generation { val deadline = System.currentTimeMillis() + timeoutMs var interval = 1000L while (true) { val g = retrieve(id) if (g.status == "completed") return g if (g.isSettled) throw GenerationFailedException(g) if (System.currentTimeMillis() > deadline) throw WaitTimeoutException(g) Thread.sleep(interval) interval = min(5000L, (interval * 1.5).toLong()) } } /** Follow one generation live: [onUpdate] gets it on every status change, ending with the settled one. */ fun stream(id: String, onUpdate: (Generation) -> Unit) = events("/generations/$id/stream") { e, d -> if (e == "generation") onUpdate(Generation(d)); true } /** Every generation on the account, live, on one connection (GET /v1/events). Return false from [onUpdate] to stop. */ fun events(since: String? = null, onUpdate: (Generation) -> Boolean) = this@Arteza.events("/events" + query("since" to since)) { e, d -> if (e == "generation") onUpdate(Generation(d)) else true } } inner class Uploads { /** Upload bytes (an image, video or audio file) and return the `url` to pass as a model input. */ fun upload(data: ByteArray, contentType: String): String { val up = obj("POST", "/uploads", mapOf("content_type" to contentType, "size" to data.size)) val conn = URI(up["upload_url"] as String).toURL().openConnection() as HttpURLConnection try { conn.requestMethod = "PUT"; conn.doOutput = true (up["headers"] as? Map ?: emptyMap()).forEach { (k, v) -> conn.setRequestProperty(k, v) } conn.outputStream.use { it.write(data) } if (conn.responseCode !in 200..299) throw ArtezaException(conn.responseCode, "upload_failed", "api_error", "The file could not be stored.") } finally { conn.disconnect() } return up["url"] as String } } inner class Tokens { /** Mint a short-lived client token (server side, with your API key). */ fun create(ttlSeconds: Int? = null, models: List? = null, maxSpend: Double? = null, user: String? = null): JsonObject = obj("POST", "/tokens", buildMap { ttlSeconds?.let { put("ttl_seconds", it) }; models?.let { put("models", it) } maxSpend?.let { put("max_spend", it) }; user?.let { put("user", it) } }) } inner class Usage { fun get(from: String? = null, to: String? = null, groupBy: String = "day"): JsonObject = obj("GET", "/usage" + query("from" to from, "to" to to, "group_by" to groupBy)) } /** Fashion Studio and AI Influencer. Bodies are the JSON the docs show (developers/docs/studios). */ inner class Studios { fun list(): JsonObject = obj("GET", "/studios") fun catalog(studio: String, kind: String? = null): JsonObject = obj("GET", "/studios/$studio/catalog" + query("kind" to kind)) fun start(path: String, body: Map): JsonObject = obj("POST", "/studios/$path", body, UUID.randomUUID().toString()) fun job(id: String): JsonObject = obj("GET", "/studios/jobs/$id") } } /** Verify a webhook (Standard Webhooks headers) and return its parsed event. [rawBody] is the body exactly as received. */ fun verifyWebhook(rawBody: String, headers: Map, secret: String, toleranceSeconds: Long = 300): JsonObject { val h = headers.mapKeys { it.key.lowercase() } fun bad(msg: String) = ArtezaException(400, "invalid_signature", "webhook_error", msg) val id = h["webhook-id"] ?: throw bad("Missing webhook headers.") val ts = h["webhook-timestamp"] ?: throw bad("Missing webhook headers.") val sigs = h["webhook-signature"] ?: throw bad("Missing webhook headers.") if (abs(System.currentTimeMillis() / 1000 - (ts.toLongOrNull() ?: 0)) > toleranceSeconds) throw bad("Webhook timestamp is too old.") val key = Base64.getDecoder().decode(secret.removePrefix("whsec_")) val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(key, "HmacSHA256")) } val expected = Base64.getEncoder().encodeToString(mac.doFinal("$id.$ts.$rawBody".toByteArray(Charsets.UTF_8))) val ok = sigs.split(" ").any { part -> val sig = part.substringAfter(",", "") sig.length == expected.length && java.security.MessageDigest.isEqual(sig.toByteArray(), expected.toByteArray()) } if (!ok) throw bad("Webhook signature does not match.") return Json.parse(rawBody) as? JsonObject ?: emptyMap() } /** A small, strict JSON codec, so the SDK needs no dependency. Objects are LinkedHashMap, arrays List, numbers Long or Double. */ object Json { fun parse(s: String): Any? = Parser(s).run { val v = value(); ws(); if (i != s.length) err(); v } fun write(v: Any?): String = StringBuilder().also { write(v, it) }.toString() private fun write(v: Any?, sb: StringBuilder) { when (v) { null -> sb.append("null") is String -> { sb.append('"'); v.forEach { c -> when (c) { '"' -> sb.append("\\\""); '\\' -> sb.append("\\\\"); '\n' -> sb.append("\\n"); '\r' -> sb.append("\\r"); '\t' -> sb.append("\\t") else -> if (c < ' ') sb.append(String.format("\\u%04x", c.code)) else sb.append(c) } }; sb.append('"') } is Boolean, is Int, is Long, is Short, is Byte -> sb.append(v.toString()) is Double -> sb.append(if (v % 1.0 == 0.0 && abs(v) < 1e15) v.toLong().toString() else v.toString()) is Float -> write(v.toDouble(), sb) is Number -> sb.append(v.toString()) is Map<*, *> -> { sb.append('{'); var first = true for ((k, x) in v) { if (!first) sb.append(','); first = false; write(k.toString(), sb); sb.append(':'); write(x, sb) }; sb.append('}') } is Iterable<*> -> { sb.append('['); var first = true; for (x in v) { if (!first) sb.append(','); first = false; write(x, sb) }; sb.append(']') } is Array<*> -> write(v.toList(), sb) else -> write(v.toString(), sb) } } private class Parser(val s: String) { var i = 0 fun err(): Nothing = throw IllegalArgumentException("Invalid JSON at $i") fun ws() { while (i < s.length && s[i].isWhitespace()) i++ } fun value(): Any? { ws(); if (i >= s.length) err() return when (s[i]) { '{' -> { i++; val m = LinkedHashMap(); ws() if (s[i] == '}') { i++; return m } while (true) { ws(); val k = str(); ws(); if (s[i++] != ':') err(); m[k] = value(); ws() when (s[i++]) { ',' -> continue; '}' -> return m; else -> err() } } ; @Suppress("UNREACHABLE_CODE") m } '[' -> { i++; val l = ArrayList(); ws() if (s[i] == ']') { i++; return l } while (true) { l.add(value()); ws(); when (s[i++]) { ',' -> continue; ']' -> return l; else -> err() } } ; @Suppress("UNREACHABLE_CODE") l } '"' -> str() 't' -> lit("true", true); 'f' -> lit("false", false); 'n' -> lit("null", null) else -> num() } } fun lit(w: String, v: Any?): Any? { if (!s.startsWith(w, i)) err(); i += w.length; return v } fun num(): Any { val st = i while (i < s.length && (s[i].isDigit() || s[i] in "+-.eE")) i++ val t = s.substring(st, i); if (t.isEmpty()) err() return if (t.any { it in ".eE" }) t.toDouble() else t.toLongOrNull() ?: t.toDouble() } fun str(): String { if (s[i] != '"') err(); i++; val sb = StringBuilder() while (true) { if (i >= s.length) err(); val c = s[i++] when (c) { '"' -> return sb.toString() '\\' -> { when (val e = s[i++]) { 'n' -> sb.append('\n'); 't' -> sb.append('\t'); 'r' -> sb.append('\r'); 'b' -> sb.append('\b'); 'f' -> sb.append('\u000C') 'u' -> { sb.append(s.substring(i, i + 4).toInt(16).toChar()); i += 4 }; else -> sb.append(e) } } else -> sb.append(c) } } } } }