/// Arteza SDK for Dart and Flutter -- https://arteza.ai/developers/sdks /// /// One file, no dependencies (dart:io, dart:convert): Flutter on iOS, Android /// and desktop, and Dart on the server. async/await. /// /// final arteza = Arteza(apiKey: clientToken); // in an app: a client token from YOUR server /// final g = 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) 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. library arteza; import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:math'; import 'dart:typed_data'; typedef Json = Map; /// An error answered by the API. Branch on [code]; [message] is English prose and may change. class ArtezaException implements Exception { final int status; final String code; final String type; final String message; final String? param; final String? requestId; final String? docUrl; ArtezaException(this.status, this.code, this.type, this.message, {this.param, this.requestId, this.docUrl}); @override String toString() => 'Arteza $status $code: $message${requestId != null ? ' (request $requestId)' : ''}'; } /// A generation that settled as failed or canceled. Its charge was refunded. class GenerationFailedException implements Exception { final Generation generation; GenerationFailedException(this.generation); @override String toString() => 'Generation ${generation.id} ${generation.status}: ${generation.errorMessage ?? generation.errorCode ?? ''}'; } /// [Generations.wait] gave up before the generation settled; it is still running. class WaitTimeoutException implements Exception { final Generation generation; WaitTimeoutException(this.generation); } class GenerationFile { final String url; final String type; const GenerationFile(this.url, this.type); } /// A generation as the API returns it. [raw] holds every field, including ones added after this SDK version. class Generation { final Json raw; Generation(this.raw); String get id => raw['id'] as String? ?? ''; String get status => raw['status'] as String? ?? ''; String get model => raw['model'] as String? ?? ''; bool get isSettled => const {'completed', 'failed', 'canceled'}.contains(status); List get files => ((raw['output'] as Map?)?['files'] as List? ?? const []) .whereType() .where((f) => f['url'] is String) .map((f) => GenerationFile(f['url'] as String, f['type'] as String? ?? 'file')) .toList(); String? get errorCode => (raw['error'] as Map?)?['code'] as String?; String? get errorMessage => (raw['error'] as Map?)?['message'] as String?; bool get errorRetryable => (raw['error'] as Map?)?['retryable'] as bool? ?? false; Map get metadata => ((raw['metadata'] as Map?) ?? const {}).map((k, v) => MapEntry('$k', '$v')); @override String toString() => 'Generation($id, $status)'; } class Arteza { static const version = '0.5.0'; static const defaultBaseUrl = 'https://arteza.ai/api/v1'; static const _retryable = {408, 425, 429, 500, 502, 503, 504}; final String baseUrl; final Duration timeout; final int maxRetries; final String _apiKey; final String _userAgent; final HttpClient _http; final _rand = Random(); late final models = Models._(this); late final apps = Apps._(this); late final generations = Generations._(this); late final uploads = Uploads._(this); late final tokens = Tokens._(this); late final usage = Usage._(this); late final studios = Studios._(this); /// [apiKey] is an `ark_live_` key on a server, or an `ark_tok_` client token in an app. Arteza({String? apiKey, String? baseUrl, this.timeout = const Duration(seconds: 60), this.maxRetries = 3, String? appName, HttpClient? httpClient}) : _apiKey = apiKey ?? Platform.environment['ARTEZA_API_KEY'] ?? '', baseUrl = (baseUrl ?? Platform.environment['ARTEZA_BASE_URL'] ?? defaultBaseUrl).replaceAll(RegExp(r'/+$'), ''), _userAgent = 'arteza-dart/$version${appName != null ? ' $appName' : ''}', _http = httpClient ?? HttpClient() { if (_apiKey.isEmpty) { 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'); } } /// Close the underlying connection pool when you are done with this client. void close() => _http.close(); // ── transport ────────────────────────────────────────────────────────── /// Any endpoint: `await arteza.request('GET', '/studios')`. Returns the decoded JSON. Future request(String method, String path, {Object? body, String? idempotencyKey}) async { final payload = body == null ? null : utf8.encode(jsonEncode(body)); var attempt = 0; while (true) { try { final req = await _open(method, path).timeout(timeout); req.headers.set(HttpHeaders.acceptHeader, 'application/json'); if (idempotencyKey != null) req.headers.set('Idempotency-Key', idempotencyKey); if (payload != null) { req.headers.contentType = ContentType.json; req.contentLength = payload.length; req.add(payload); } final res = await req.close().timeout(timeout); final text = await utf8.decodeStream(res); if (res.statusCode >= 200 && res.statusCode < 300) return text.isEmpty ? {} : jsonDecode(text); final err = _error(res, text); if (!_retryable.contains(res.statusCode) || attempt >= maxRetries) throw err; final retryAfter = double.tryParse(res.headers.value('retry-after') ?? ''); await Future.delayed(Duration(milliseconds: ((retryAfter ?? _backoff(attempt)) * 1000).round())); } on SocketException { if (attempt >= maxRetries) rethrow; await Future.delayed(Duration(milliseconds: (_backoff(attempt) * 1000).round())); } on TimeoutException { if (attempt >= maxRetries) rethrow; await Future.delayed(Duration(milliseconds: (_backoff(attempt) * 1000).round())); } attempt++; } } Future _obj(String method, String path, {Object? body, String? idem}) async => ((await request(method, path, body: body, idempotencyKey: idem)) as Map?)?.cast() ?? {}; /// A Server-Sent Events stream of (event, data) pairs, until the server closes it. Stream<(String, Json)> events(String path) async* { final req = await _open('GET', path); req.headers.set(HttpHeaders.acceptHeader, 'text/event-stream'); final res = await req.close(); if (res.statusCode != 200) throw _error(res, await utf8.decodeStream(res)); var event = 'message'; final data = []; await for (final line in res.transform(utf8.decoder).transform(const LineSplitter())) { if (line.isEmpty) { if (data.isNotEmpty) yield (event, (jsonDecode(data.join('\n')) as Map).cast()); event = 'message'; data.clear(); } else if (line.startsWith('event:')) { event = line.substring(6).trim(); } else if (line.startsWith('data:')) { data.add(line.substring(5).trim()); } } } Future _open(String method, String path) async { final req = await _http.openUrl(method, Uri.parse(path.startsWith('http') ? path : '$baseUrl$path')); req.headers.set(HttpHeaders.authorizationHeader, 'Bearer $_apiKey'); req.headers.set(HttpHeaders.userAgentHeader, _userAgent); req.headers.set('X-Arteza-Client', _userAgent); return req; } ArtezaException _error(HttpClientResponse res, String text) { Map e = const {}; try { e = ((jsonDecode(text) as Map?)?['error'] as Map?) ?? const {}; } catch (_) {} return ArtezaException(res.statusCode, e['code'] as String? ?? 'http_${res.statusCode}', e['type'] as String? ?? 'api_error', e['message'] as String? ?? 'HTTP ${res.statusCode}', param: e['param'] as String?, requestId: e['request_id'] as String? ?? res.headers.value('x-request-id'), docUrl: e['doc_url'] as String?); } double _backoff(int attempt) { final base = min(8.0, 0.5 * pow(2, attempt)); return base / 2 + _rand.nextDouble() * base / 2; } static String _query(Map q) { final items = q.entries.where((e) => e.value != null).map((e) => '${Uri.encodeQueryComponent(e.key)}=${Uri.encodeQueryComponent(e.value!)}'); return items.isEmpty ? '' : '?${items.join('&')}'; } static String _uuid() { final r = Random.secure(); final b = List.generate(16, (_) => r.nextInt(256)); b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80; final h = b.map((x) => x.toRadixString(16).padLeft(2, '0')).join(); return '${h.substring(0, 8)}-${h.substring(8, 12)}-${h.substring(12, 16)}-${h.substring(16, 20)}-${h.substring(20)}'; } // ── top level ───────────────────────────────────────────────────────── /// Price a request without running it. Free. Future estimate({String? model, String? app, required Json input}) => _obj('POST', '/estimate', body: app != null ? {'app': app, 'input': input} : {'model': model ?? 'auto', 'input': input}); /// Credits, USD balance and plan. Future balance() => _obj('GET', '/balance'); /// Create a generation and wait for it. Throws [GenerationFailedException] if it fails (it was refunded). Future run(String model, Json input, {String? webhookUrl, Map? metadata, Duration timeout = const Duration(minutes: 15)}) async { final g = await generations.create(model: model, input: input, webhookUrl: webhookUrl, metadata: metadata); return generations.wait(g.id, timeout: timeout); } /// Run one of the studio's apps (GET /v1/apps) and wait for it. Future runApp(String app, Json input, {Duration timeout = const Duration(minutes: 15)}) async { final g = await generations.create(app: app, input: input); return generations.wait(g.id, timeout: timeout); } } class Models { final Arteza _c; Models._(this._c); Future> list({String? category}) async => ((await _c._obj('GET', '/models${Arteza._query({'category': category})}'))['data'] as List? ?? const []).cast().map((m) => m.cast()).toList(); Future retrieve(String id) => _c._obj('GET', '/models/$id'); } class Apps { final Arteza _c; Apps._(this._c); Future> list({String? category}) async => ((await _c._obj('GET', '/apps${Arteza._query({'category': category})}'))['data'] as List? ?? const []).cast().map((m) => m.cast()).toList(); Future retrieve(String id) => _c._obj('GET', '/apps/$id'); } class Generations { final Arteza _c; Generations._(this._c); /// Start a generation (202). Pass [model] or [app]. Carries an Idempotency-Key, so retries never charge twice. Future create({String? model, String? app, required Json input, String? webhookUrl, Map? metadata, String? idempotencyKey}) async { final body = {'input': input}; if (app != null) { body['app'] = app; } else { body['model'] = model ?? 'auto'; } if (webhookUrl != null) body['webhook_url'] = webhookUrl; if (metadata != null) body['metadata'] = metadata; return Generation(await _c._obj('POST', '/generations', body: body, idem: idempotencyKey ?? Arteza._uuid())); } Future retrieve(String id) async => Generation(await _c._obj('GET', '/generations/$id')); Future<({List data, String? nextCursor})> list({int limit = 20, String? cursor, String? model}) async { final j = await _c._obj('GET', '/generations${Arteza._query({'limit': '$limit', 'cursor': cursor, 'model': model})}'); final data = (j['data'] as List? ?? const []).cast().map((m) => Generation(m.cast())).toList(); return (data: data, nextCursor: j['has_more'] == true ? j['next_cursor'] as String? : null); } /// Cancel a queued generation; its charge is refunded. Future cancel(String id) async => Generation(await _c._obj('POST', '/generations/$id/cancel', body: const {})); /// Move a finished generation to the trash (restorable for 30 days). Future delete(String id) => _c._obj('DELETE', '/generations/$id'); /// Poll until settled, backing off from 1s to 5s. Throws [GenerationFailedException] on failed/canceled. Future wait(String id, {Duration timeout = const Duration(minutes: 15)}) async { final deadline = DateTime.now().add(timeout); var interval = 1000; while (true) { final g = await retrieve(id); if (g.status == 'completed') return g; if (g.isSettled) throw GenerationFailedException(g); if (DateTime.now().isAfter(deadline)) throw WaitTimeoutException(g); await Future.delayed(Duration(milliseconds: interval)); interval = min(5000, (interval * 1.5).round()); } } /// Follow one generation live: yields it on every status change, ending with the settled one. Stream stream(String id) => _c.events('/generations/$id/stream').where((e) => e.$1 == 'generation').map((e) => Generation(e.$2)); /// Every generation on the account, live, on one connection (GET /v1/events). Stream events({DateTime? since}) => _c .events('/events${Arteza._query({'since': since?.toUtc().toIso8601String()})}') .where((e) => e.$1 == 'generation') .map((e) => Generation(e.$2)); } class Uploads { final Arteza _c; Uploads._(this._c); /// Upload bytes (an image, video or audio file) and return the `url` to pass as a model input. Future upload(Uint8List data, String contentType) async { final up = await _c._obj('POST', '/uploads', body: {'content_type': contentType, 'size': data.length}); final req = await _c._http.putUrl(Uri.parse(up['upload_url'] as String)); (up['headers'] as Map? ?? const {}).forEach((k, v) => req.headers.set('$k', '$v')); req.add(data); final res = await req.close(); await res.drain(); if (res.statusCode < 200 || res.statusCode >= 300) { throw ArtezaException(res.statusCode, 'upload_failed', 'api_error', 'The file could not be stored.'); } return up['url'] as String; } } class Tokens { final Arteza _c; Tokens._(this._c); /// Mint a short-lived client token (server side, with your API key). Future create({int? ttlSeconds, List? models, num? maxSpend, String? user}) => _c._obj('POST', '/tokens', body: { if (ttlSeconds != null) 'ttl_seconds': ttlSeconds, if (models != null) 'models': models, if (maxSpend != null) 'max_spend': maxSpend, if (user != null) 'user': user, }); } class Usage { final Arteza _c; Usage._(this._c); Future get({String? from, String? to, String groupBy = 'day'}) => _c._obj('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). class Studios { final Arteza _c; Studios._(this._c); Future list() => _c._obj('GET', '/studios'); Future catalog(String studio, {String? kind}) => _c._obj('GET', '/studios/$studio/catalog${Arteza._query({'kind': kind})}'); Future start(String path, Json body) => _c._obj('POST', '/studios/$path', body: body, idem: Arteza._uuid()); Future job(String id) => _c._obj('GET', '/studios/jobs/$id'); }