// Package arteza is the Arteza SDK for Go -- https://arteza.ai/developers/sdks // // Standard library only. 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. // // c, _ := arteza.New(arteza.Options{}) // reads ARTEZA_API_KEY // g, err := c.Run(ctx, "nano-banana-2", arteza.JSON{"prompt": "A red fox in fresh snow"}) // fmt.Println(g.Files()[0].URL) package arteza import ( "bufio" "bytes" "context" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "io" mrand "math/rand" "net/http" "net/url" "os" "strconv" "strings" "time" ) // Version of this SDK. const Version = "0.5.0" // DefaultBaseURL is the production API. const DefaultBaseURL = "https://arteza.ai/api/v1" // JSON is a decoded JSON object. type JSON = map[string]any // Error is an error answered by the API. Branch on Code; Message is English prose and may change. type Error struct { Status int `json:"-"` Code string `json:"code"` Type string `json:"type"` Message string `json:"message"` Param string `json:"param,omitempty"` RequestID string `json:"request_id,omitempty"` DocURL string `json:"doc_url,omitempty"` } func (e *Error) Error() string { s := fmt.Sprintf("arteza %d %s: %s", e.Status, e.Code, e.Message) if e.RequestID != "" { s += " (request " + e.RequestID + ")" } return s } // GenerationFailedError is returned when a generation settles as failed or canceled. Its charge was refunded. type GenerationFailedError struct{ Generation *Generation } func (e *GenerationFailedError) Error() string { return fmt.Sprintf("generation %s %s: %s", e.Generation.ID, e.Generation.Status, e.Generation.ErrorMessage()) } // ErrWaitTimeout is returned by Wait when the generation has not settled in time; it is still running. var ErrWaitTimeout = errors.New("arteza: generation did not settle before the timeout") // File is one output of a generation. type File struct { URL string `json:"url"` Type string `json:"type"` } // Generation as the API returns it. Raw holds every field, including ones added after this SDK version. type Generation struct { ID string `json:"id"` Status string `json:"status"` Model string `json:"model"` Metadata map[string]string `json:"metadata"` Raw JSON `json:"-"` } // Settled reports whether the generation is completed, failed or canceled. func (g *Generation) Settled() bool { return g.Status == "completed" || g.Status == "failed" || g.Status == "canceled" } // Files are the generation's outputs, in the order the model returned them. func (g *Generation) Files() []File { out, _ := g.Raw["output"].(JSON) list, _ := out["files"].([]any) files := make([]File, 0, len(list)) for _, f := range list { if m, ok := f.(JSON); ok { u, _ := m["url"].(string) t, _ := m["type"].(string) files = append(files, File{URL: u, Type: t}) } } return files } // ErrorCode is error.code on a failed generation. func (g *Generation) ErrorCode() string { e, _ := g.Raw["error"].(JSON); s, _ := e["code"].(string); return s } // ErrorMessage is error.message on a failed generation. func (g *Generation) ErrorMessage() string { e, _ := g.Raw["error"].(JSON); s, _ := e["message"].(string); return s } // Options configure a Client. type Options struct { APIKey string // an ark_live_ key on a server, or an ark_tok_ client token; defaults to ARTEZA_API_KEY BaseURL string // defaults to ARTEZA_BASE_URL, then DefaultBaseURL MaxRetries int // defaults to 3 AppName string // appended to the client identifier HTTPClient *http.Client } // Client talks to the Arteza API. type Client struct { apiKey, baseURL, ua string maxRetries int http *http.Client } // New returns a client. func New(o Options) (*Client, error) { key := o.APIKey if key == "" { key = os.Getenv("ARTEZA_API_KEY") } if key == "" { return nil, &Error{Code: "missing_api_key", Type: "authentication_error", Message: "No API key. Set Options.APIKey or ARTEZA_API_KEY. Create one at https://arteza.ai/developers/console"} } base := o.BaseURL if base == "" { base = os.Getenv("ARTEZA_BASE_URL") } if base == "" { base = DefaultBaseURL } retries := o.MaxRetries if retries == 0 { retries = 3 } hc := o.HTTPClient if hc == nil { hc = &http.Client{Timeout: 0} } ua := "arteza-go/" + Version if o.AppName != "" { ua += " " + o.AppName } return &Client{apiKey: key, baseURL: strings.TrimRight(base, "/"), ua: ua, maxRetries: retries, http: hc}, nil } var retryable = map[int]bool{408: true, 425: true, 429: true, 500: true, 502: true, 503: true, 504: true} // Request calls any endpoint and decodes the JSON answer into out (which may be nil). func (c *Client) Request(ctx context.Context, method, path string, body any, idempotencyKey string, out any) error { var payload []byte if body != nil { var err error if payload, err = json.Marshal(body); err != nil { return err } } for attempt := 0; ; attempt++ { req, err := c.newRequest(ctx, method, path, payload) if err != nil { return err } req.Header.Set("Accept", "application/json") if idempotencyKey != "" { req.Header.Set("Idempotency-Key", idempotencyKey) } res, err := c.http.Do(req) if err != nil { if attempt >= c.maxRetries || ctx.Err() != nil { return err } if err := sleep(ctx, backoff(attempt)); err != nil { return err } continue } data, _ := io.ReadAll(res.Body) res.Body.Close() if res.StatusCode >= 200 && res.StatusCode < 300 { if out == nil || len(data) == 0 { return nil } return json.Unmarshal(data, out) } apiErr := toError(res, data) if !retryable[res.StatusCode] || attempt >= c.maxRetries { return apiErr } wait := backoff(attempt) if s, err := strconv.ParseFloat(res.Header.Get("Retry-After"), 64); err == nil { wait = time.Duration(s * float64(time.Second)) } if err := sleep(ctx, wait); err != nil { return err } } } func (c *Client) newRequest(ctx context.Context, method, path string, payload []byte) (*http.Request, error) { u := path if !strings.HasPrefix(path, "http") { u = c.baseURL + path } var body io.Reader if payload != nil { body = bytes.NewReader(payload) } req, err := http.NewRequestWithContext(ctx, method, u, body) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+c.apiKey) req.Header.Set("User-Agent", c.ua) req.Header.Set("X-Arteza-Client", c.ua) if payload != nil { req.Header.Set("Content-Type", "application/json") } return req, nil } func toError(res *http.Response, data []byte) *Error { var w struct { Error *Error `json:"error"` } _ = json.Unmarshal(data, &w) e := w.Error if e == nil { e = &Error{Code: fmt.Sprintf("http_%d", res.StatusCode), Type: "api_error", Message: fmt.Sprintf("HTTP %d", res.StatusCode)} } e.Status = res.StatusCode if e.RequestID == "" { e.RequestID = res.Header.Get("X-Request-Id") } return e } func backoff(attempt int) time.Duration { base := 0.5 * float64(int(1)< 8 { base = 8 } return time.Duration((base/2 + mrand.Float64()*base/2) * float64(time.Second)) } func sleep(ctx context.Context, d time.Duration) error { t := time.NewTimer(d) defer t.Stop() select { case <-ctx.Done(): return ctx.Err() case <-t.C: return nil } } func newUUID() string { b := make([]byte, 16) _, _ = rand.Read(b) b[6] = b[6]&0x0f | 0x40 b[8] = b[8]&0x3f | 0x80 return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) } func query(kv ...string) string { q := url.Values{} for i := 0; i+1 < len(kv); i += 2 { if kv[i+1] != "" { q.Set(kv[i], kv[i+1]) } } if len(q) == 0 { return "" } return "?" + q.Encode() } func decodeGeneration(raw JSON) *Generation { g := &Generation{Raw: raw} b, _ := json.Marshal(raw) _ = json.Unmarshal(b, g) return g } func (c *Client) object(ctx context.Context, method, path string, body any, idem string) (JSON, error) { var out JSON err := c.Request(ctx, method, path, body, idem, &out) return out, err } // ── top level ────────────────────────────────────────────────────────────── // Estimate prices a request without running it. Free. Pass model ("auto" works) or app. func (c *Client) Estimate(ctx context.Context, model, app string, input JSON) (JSON, error) { body := JSON{"input": input} if app != "" { body["app"] = app } else { if model == "" { model = "auto" } body["model"] = model } return c.object(ctx, "POST", "/estimate", body, "") } // Balance returns credits, USD balance and plan. func (c *Client) Balance(ctx context.Context) (JSON, error) { return c.object(ctx, "GET", "/balance", nil, "") } // CreateParams start a generation. Set Model or App. type CreateParams struct { Model string App string Input JSON WebhookURL string Metadata map[string]string IdempotencyKey string // defaults to a new UUID } // Create starts a generation (202). func (c *Client) Create(ctx context.Context, p CreateParams) (*Generation, error) { body := JSON{"input": p.Input} if p.App != "" { body["app"] = p.App } else { m := p.Model if m == "" { m = "auto" } body["model"] = m } if p.WebhookURL != "" { body["webhook_url"] = p.WebhookURL } if p.Metadata != nil { body["metadata"] = p.Metadata } key := p.IdempotencyKey if key == "" { key = newUUID() } raw, err := c.object(ctx, "POST", "/generations", body, key) if err != nil { return nil, err } return decodeGeneration(raw), nil } // Get returns one generation. func (c *Client) Get(ctx context.Context, id string) (*Generation, error) { raw, err := c.object(ctx, "GET", "/generations/"+url.PathEscape(id), nil, "") if err != nil { return nil, err } return decodeGeneration(raw), nil } // List returns a page of generations, newest first, and the cursor for the next page ("" at the end). func (c *Client) List(ctx context.Context, limit int, cursor, model string) ([]*Generation, string, error) { var page struct { Data []JSON `json:"data"` HasMore bool `json:"has_more"` NextCursor string `json:"next_cursor"` } if err := c.Request(ctx, "GET", "/generations"+query("limit", strconv.Itoa(limit), "cursor", cursor, "model", model), nil, "", &page); err != nil { return nil, "", err } out := make([]*Generation, len(page.Data)) for i, raw := range page.Data { out[i] = decodeGeneration(raw) } if !page.HasMore { return out, "", nil } return out, page.NextCursor, nil } // Cancel cancels a queued generation; its charge is refunded. func (c *Client) Cancel(ctx context.Context, id string) (*Generation, error) { raw, err := c.object(ctx, "POST", "/generations/"+url.PathEscape(id)+"/cancel", JSON{}, "") if err != nil { return nil, err } return decodeGeneration(raw), nil } // Delete moves a finished generation to the trash (restorable for 30 days). func (c *Client) Delete(ctx context.Context, id string) error { return c.Request(ctx, "DELETE", "/generations/"+url.PathEscape(id), nil, "", nil) } // Wait polls until the generation settles, backing off from 1s to 5s. // A failed or canceled generation returns *GenerationFailedError. func (c *Client) Wait(ctx context.Context, id string, timeout time.Duration) (*Generation, error) { deadline := time.Now().Add(timeout) interval := time.Second for { g, err := c.Get(ctx, id) if err != nil { return nil, err } if g.Status == "completed" { return g, nil } if g.Settled() { return g, &GenerationFailedError{Generation: g} } if time.Now().After(deadline) { return g, ErrWaitTimeout } if err := sleep(ctx, interval); err != nil { return g, err } if interval = interval * 3 / 2; interval > 5*time.Second { interval = 5 * time.Second } } } // Run creates a generation and waits up to 15 minutes for it. func (c *Client) Run(ctx context.Context, model string, input JSON) (*Generation, error) { g, err := c.Create(ctx, CreateParams{Model: model, Input: input}) if err != nil { return nil, err } return c.Wait(ctx, g.ID, 15*time.Minute) } // RunApp runs one of the studio's apps (GET /v1/apps) and waits for it. func (c *Client) RunApp(ctx context.Context, app string, input JSON) (*Generation, error) { g, err := c.Create(ctx, CreateParams{App: app, Input: input}) if err != nil { return nil, err } return c.Wait(ctx, g.ID, 15*time.Minute) } // Events reads a Server-Sent Events stream, calling fn for each event until the // server closes it, the context ends, or fn returns false. func (c *Client) Events(ctx context.Context, path string, fn func(event string, data JSON) bool) error { req, err := c.newRequest(ctx, "GET", path, nil) if err != nil { return err } req.Header.Set("Accept", "text/event-stream") res, err := c.http.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode != 200 { data, _ := io.ReadAll(res.Body) return toError(res, data) } sc := bufio.NewScanner(res.Body) sc.Buffer(make([]byte, 64*1024), 8*1024*1024) event, data := "message", []string{} for sc.Scan() { line := sc.Text() switch { case line == "": if len(data) > 0 { var obj JSON if json.Unmarshal([]byte(strings.Join(data, "\n")), &obj) == nil && !fn(event, obj) { return nil } } event, data = "message", data[:0] case strings.HasPrefix(line, "event:"): event = strings.TrimSpace(line[6:]) case strings.HasPrefix(line, "data:"): data = append(data, strings.TrimSpace(line[5:])) } } return sc.Err() } // Stream follows one generation live, calling fn on every status change until it settles. func (c *Client) Stream(ctx context.Context, id string, fn func(*Generation)) error { return c.Events(ctx, "/generations/"+url.PathEscape(id)+"/stream", func(ev string, d JSON) bool { if ev == "generation" { fn(decodeGeneration(d)) } return true }) } // AccountEvents follows every generation on the account on one connection (GET /v1/events). // since replays changes after that time (zero for none). Return false from fn to stop. func (c *Client) AccountEvents(ctx context.Context, since time.Time, fn func(*Generation) bool) error { q := "" if !since.IsZero() { q = query("since", since.UTC().Format(time.RFC3339)) } return c.Events(ctx, "/events"+q, func(ev string, d JSON) bool { if ev == "generation" { return fn(decodeGeneration(d)) } return true }) } // Models lists the models (category "" for all). func (c *Client) Models(ctx context.Context, category string) ([]JSON, error) { var page struct{ Data []JSON } err := c.Request(ctx, "GET", "/models"+query("category", category), nil, "", &page) return page.Data, err } // Model returns one model with its input_schema and modes. func (c *Client) Model(ctx context.Context, id string) (JSON, error) { return c.object(ctx, "GET", "/models/"+url.PathEscape(id), nil, "") } // Apps lists the studio's apps (category "" for all). func (c *Client) Apps(ctx context.Context, category string) ([]JSON, error) { var page struct{ Data []JSON } err := c.Request(ctx, "GET", "/apps"+query("category", category), nil, "", &page) return page.Data, err } // Upload stores a local file and returns the URL to pass as a model input. func (c *Client) Upload(ctx context.Context, data []byte, contentType string) (string, error) { var up struct { UploadURL string `json:"upload_url"` URL string `json:"url"` Headers map[string]string `json:"headers"` } if err := c.Request(ctx, "POST", "/uploads", JSON{"content_type": contentType, "size": len(data)}, "", &up); err != nil { return "", err } req, err := http.NewRequestWithContext(ctx, "PUT", up.UploadURL, bytes.NewReader(data)) if err != nil { return "", err } for k, v := range up.Headers { if strings.EqualFold(k, "Content-Length") { continue } req.Header.Set(k, v) } req.ContentLength = int64(len(data)) res, err := c.http.Do(req) if err != nil { return "", err } res.Body.Close() if res.StatusCode < 200 || res.StatusCode >= 300 { return "", &Error{Status: res.StatusCode, Code: "upload_failed", Type: "api_error", Message: "The file could not be stored."} } return up.URL, nil } // TokenParams mint a client token. type TokenParams struct { TTLSeconds int `json:"ttl_seconds,omitempty"` Models []string `json:"models,omitempty"` MaxSpend float64 `json:"max_spend,omitempty"` User string `json:"user,omitempty"` } // CreateToken mints a short-lived client token for a browser or a mobile app (server side, with your API key). func (c *Client) CreateToken(ctx context.Context, p TokenParams) (JSON, error) { return c.object(ctx, "POST", "/tokens", p, "") } // Usage reports spend grouped by day, model, app, key or user. func (c *Client) Usage(ctx context.Context, from, to, groupBy string) (JSON, error) { return c.object(ctx, "GET", "/usage"+query("from", from, "to", to, "group_by", groupBy), nil, "") } // Studio starts a Fashion Studio or AI Influencer job; path is e.g. "fashion/shoots" or "influencer/looks". func (c *Client) Studio(ctx context.Context, path string, body JSON) (JSON, error) { return c.object(ctx, "POST", "/studios/"+path, body, newUUID()) } // VerifyWebhook checks a webhook's Standard Webhooks signature and returns the parsed event. // rawBody is the request body exactly as received; secret is whsec_... from the console. func VerifyWebhook(rawBody []byte, header http.Header, secret string, tolerance time.Duration) (JSON, error) { if tolerance == 0 { tolerance = 5 * time.Minute } id, ts, sigs := header.Get("webhook-id"), header.Get("webhook-timestamp"), header.Get("webhook-signature") bad := func(m string) error { return &Error{Status: 400, Code: "invalid_signature", Type: "webhook_error", Message: m} } if id == "" || ts == "" || sigs == "" { return nil, bad("Missing webhook headers.") } t, err := strconv.ParseInt(ts, 10, 64) if err != nil || time.Since(time.Unix(t, 0)).Abs() > tolerance { return nil, bad("Webhook timestamp is too old.") } key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_")) if err != nil { return nil, bad("The webhook secret is not valid base64.") } mac := hmac.New(sha256.New, key) mac.Write([]byte(id + "." + ts + ".")) mac.Write(rawBody) expected := base64.StdEncoding.EncodeToString(mac.Sum(nil)) for _, part := range strings.Fields(sigs) { if _, sig, ok := strings.Cut(part, ","); ok && hmac.Equal([]byte(sig), []byte(expected)) { var ev JSON if err := json.Unmarshal(rawBody, &ev); err != nil { return nil, err } return ev, nil } } return nil, bad("Webhook signature does not match.") }