spicyapiDocs
Main content

Go SDK reference

Official Go SDK (github.com/spicyapi-ai/spicy-go) using the standard library: quote tasks, upload files, poll history, and verify webhooks.

spicy-go is the official Go SDK for SpicyAPI. It puts image, video and audio generation behind one *spicy.Client: it attaches your API key, decodes the response envelope into typed structs, waits for a task with bounded back-off, uploads local files in one call and gives every failure a single error type you can match with errors.As.

It requires Go 1.23 or newer and uses the standard library only. That is deliberate: this package goes into your dependency graph, and every module it drags in is one more thing for you to audit.

Is this the right tool?

You want to…Use
Call SpicyAPI from your own Go codeThis SDK
Call it from Node.js or TypeScriptThe TypeScript SDK
Call it from Python, PHP or JavaThe Python, PHP or Java SDK
Generate things from a terminal without writing codeThe CLI
Let an AI assistant call SpicyAPI for youThe MCP server and the Agent Skill
Use a chat or text modelAn established Go client for the OpenAI, Anthropic or Gemini formats — see Text and streaming

Install it

Add the module at the current release:

go get github.com/spicyapi-ai/spicy-go@v0.3.0

Then put your key in the environment, so it never appears in your code or your shell history file:

export SPICY_API_KEY="sk-spicy-..."

Your first result

Ask for the price, decide, create the task, wait, read the files. Quoting is free and reserves nothing.

client, err := spicy.New(spicy.Options{}) // reads SPICY_API_KEY from the environment
if err != nil {
    return err
}

request := spicy.CreateTaskInput{
    Model: "MODEL_ID_FROM_CATALOG",
    Input: map[string]any{"prompt": "a lantern in fog"},
}

quote, err := client.Quote(ctx, request)
if err != nil {
    return err
}
log.Printf("this will cost at most %s", quote.MaxCharge)

// Store this next to your own record of the job before sending it: its whole
// purpose is to still be there after the crash that lost the response.
key, err := spicy.NewIdempotencyKey()
if err != nil {
    return err
}

request.Model = quote.Model
request.QuoteID = quote.QuoteID
request.ExpectedCost = quote.EstimatedCost

task, err := client.CreateTask(ctx, request, key, spicy.CreateTaskOptions{})
if err != nil {
    return err
}

final, err := client.WaitForTerminal(ctx, task.TaskID, spicy.WaitOptions{})
if err != nil {
    return err
}
for _, asset := range final.ReadyAssets() {
    log.Println(asset.URL)
}

MODEL_ID_FROM_CATALOG is a placeholder. Take a real ID from the authenticated catalogue — client.ListModels, which is GET /api/v1/models — and never from memory or an old page: models are added, paused and retired. Build Input from that model's own inputSchema, which ListModels returns; every model accepts different fields.

Amounts are decimal USD strings, never floats, because binary floats cannot hold most decimal amounts exactly. There are no credits or points anywhere in this API.

A terminal state is not a successful one: failed, canceled and expired all end the wait. Check final.State.

Skip the first poll

WaitSeconds asks the service to hold the connection open until the task finishes, which on a quick model means the result arrives with the submission.

seconds := 30
task, err := client.CreateTask(ctx, request, key, spicy.CreateTaskOptions{WaitSeconds: &seconds})
if err != nil {
    return err
}

// Task is nil whenever the wait ran out. That is the ordinary outcome, not an
// error — the generation is still running, so poll from here.
final := task.Task
if final == nil {
    final, err = client.WaitForTerminal(ctx, task.TaskID, spicy.WaitOptions{})
    if err != nil {
        return err
    }
}
log.Println(final.State, final.Cost)

It is an optimisation, never a guarantee. Code that reads task.Task without the nil check works right up until the first generation slower than the budget, and then panics in production.

Start from a local file

Image-to-video, subject swap and image editing all need your material on our side first. UploadFile does the three-step upload — ticket, PUT to storage, commit — in one call and returns a spicy:// URI. That URI is what goes into Input.

uploaded, err := client.UploadFile(ctx, "/path/to/reference.png", "")
// uploaded.URI -> "spicy://f/fil_..."

A publicly reachable HTTPS URL can go into the input directly and needs no upload at all. Images are accepted to 10 MiB, audio, video and documents (PDF, Word, Excel, PowerPoint, plain text, Markdown and more) to 90 MiB, and .safetensors LoRA weights (sent as application/octet-stream, for loras[].path) to 2 GiB; see Media. An upload lasts one day — to keep a file, save it to the asset library.

Keep files in the asset library

An upload's spicy://f/ URI lasts one day. Files you use again and again — a character portrait, a style reference, a voice sample — belong in the asset library: each saved file gets a stable URI of the form spicy://a/<id> that works in any file field of a model input until you delete it. How the library, its storage plans and its limits work is explained in Media: Asset library.

The key decides the library. A personal key reaches your personal library; a key created in a team workspace reaches that team's shared library, never anyone's personal one. With a team key, the current role of the member who created it decides what may change: owner and admin anything, developer only what they saved, billing and readonly only read and use. GetAssetUsage returns this as Scope.

// Save the first output of one of your successful tasks. AssetSourceURL with URL, and
// AssetSourceUpload with FileID, work the same way. The required Idempotency-Key is
// created for you; pass your own as the last argument to replay a save.
index := 0
hero, err := client.SaveAsset(ctx, spicy.SaveAssetInput{
    Source: spicy.AssetSourceTaskOutput,
    TaskID: final.TaskID,
    Index:  &index,
    Name:   "Hero portrait",
}, "")
if err != nil {
    return err
}

// Or upload a local file and save it in one call; the name defaults to the file name.
voice, err := client.UploadAssetFile(ctx, "./voice-sample.wav", spicy.UploadAssetOptions{})
if err != nil {
    return err
}
log.Println(voice.URI)

// Later, in any request: the URI goes where the model's schema expects a file.
input := map[string]any{"prompt": "slow push-in, light rain", "image_url": hero.URI}

// Every saved image whose name contains "portrait", across all pages.
err = client.EachAsset(ctx, spicy.ListAssetsOptions{Kind: "image", Q: "portrait"},
    func(asset spicy.LibraryAsset) bool {
        log.Println(asset.URI, asset.Name)
        return true // return false to stop early
    })
MethodWhat it does
SaveAsset(ctx, SaveAssetInput{...}, idempotencyKey)Saves a file and returns the *LibraryAsset. Source is AssetSourceTaskOutput (with TaskID and Index or Key), AssetSourceUpload (with FileID, fil_… or spicy://f/…) or AssetSourceURL (with a public http/https URL). Saving the same source again returns the asset you already have
UploadAssetFile(ctx, path, UploadAssetOptions{Name, ContentType})Uploads a local file and saves it in one call
ListAssets(ctx, ListAssetsOptions{...})One page: Items and NextCursor (empty on the last page)
EachAsset(ctx, ListAssetsOptions{...}, fn)Calls fn for every matching asset, page by page
GetAsset(ctx, assetID)One asset with a fresh PreviewURL
UpdateAsset(ctx, assetID, UpdateAssetInput{Name, Favorite})Renames, marks or unmarks a favorite; only what you set changes and the URI stays the same
DeleteAsset(ctx, assetID)Deletes for good; the URI stops working at once
GetAssetUsage(ctx)Scope (which library, Role, CanWrite, CanTopUp), the plan, what is stored, the limits and today's count
ListCharacters(ctx, ListCharactersOptions{AssetID, Cursor, Limit}), EachCharacter(...), GetCharacter(ctx, characterID)Your characters, read-only, each with its images in order
  • A saved file is a LibraryAsset; Asset remains one output of a task. An asset ID can be the bare ast_… ID or the spicy://a/… reference. An empty ID, a blank filter, an unknown Sort and a save that mixes two sources fail before anything is sent.
  • ListAssetsOptions takes Kind, Source (one or several), Q, Favorite, CollectionID (one folder), EntityID (one character's images), Sort, Cursor and Limit. Favorite is a *bool: true lists only favorites, false only the rest, nil both. Sort is AssetSortRecent (default), AssetSortOldest, AssetSortName or AssetSortSize, and a NextCursor only works with the sort it came from. EachAsset keeps your filters and sort on every page.
  • PreviewURL is a private preview signed for at most 20 minutes. Show it; store URI.
  • When Scope.CanTopUp is false (a team key not created by the owner), LifetimeTopupUSD and TopupToNextTierUSD are empty.
  • Characters are named, ordered sets of images, made on the Assets page of the web app. To use one, put character.URIs() — its images' spicy://a/ references, in order — into the model's reference-image field. Old spicy://p/ references keep working in the personal library. See Media: Characters.

Balance, usage and history

All three are scoped to the calling API key: sibling keys on the same account, and generations started in the web console, are not included, and their absence is not a fault.

balance, err := client.GetBalance(ctx)
if err != nil {
    return err
}
log.Printf("%s available, %s held by accepted tasks", balance.Available, balance.Held)

usage, err := client.GetUsage(ctx, spicy.UsageOptions{From: "2026-09-01", To: "2026-09-08"})
if err != nil {
    return err
}
log.Printf("%d calls, %s settled over [%s,%s)", usage.TotalCalls, usage.TotalSpend, usage.From, usage.To)

// EachTask repeats every filter on every page and moves only the cursor.
if err := client.EachTask(ctx, spicy.ListTasksOptions{From: "2026-09-01", To: "2026-09-08"},
    func(task spicy.TaskListItem) bool {
        log.Println(task.TaskID, task.State, task.Cost)
        return true // return false to stop early
    }); err != nil {
    return err
}

Dates are UTC calendar dates in a half-open interval [from, to) of at most 92 days. Pin From and To on any walk that can cross midnight UTC. Left empty, the server recomputes its own window — to is tomorrow in UTC — on every page, so a walk that starts at 23:59 and continues at 00:01 asks two different questions and splices the answers together. Nothing reports it.

GetUsage is for reconciliation, not for progress. It sits behind an account-wide budget shared by every key, and that limiter fails closed — polling it can lock every other key out of its own reporting. Follow a task with WaitForTerminal instead. Settlement can also land late, so a figure read today can still change tomorrow.

Errors

Failures come back as *spicy.APIError, reachable with errors.As:

var apiErr *spicy.APIError
if errors.As(err, &apiErr) {
    log.Println(apiErr.Status, apiErr.Code, apiErr.RequestID, apiErr.RetryAfter, apiErr.Reason)
}

Branch on Code, never on the message — messages are translated, codes are not. HTTP 503 is shared by three different business codes, so the status alone is not enough to decide what to do:

CodeMeaningWhat to do
40003uploaded bytes do not match their ticketstart over from a fresh ticket
40004no deployment serves that parameter combinationchange the parameter named in the message
40201not enough balanceadd funds
40901the price moved before the task was createdquote again, keep the same idempotency key
503a dependency is briefly unavailableback off by RetryAfter
50301no usable deployment or price right nowrefresh the catalogue, do not hammer
50302a synchronous generation failed upstream and was refundedretry with a new idempotency key

Every code is listed in Errors. Quote RequestID when you contact support.

Asset library failures also carry a Reason, a fixed word that says exactly why: ReasonAssetLibraryLocked, ReasonAssetLibraryFull and ReasonAssetFileTooLarge (400, plan limits — read GetAssetUsage rather than retrying), ReasonAssetDailyLimit (429, resets at 00:00 UTC, with RetryAfter), ReasonAssetStorageFull (503, temporary), ReasonAssetPermissionDenied (403, your team role does not allow the change), ReasonAssetWorkspaceForbidden (403, this key cannot reach that library) and ReasonAssetEntityNameTaken (409). IsAssetErrorReason tells a known value apart; Reason carries any other value the server sends unchanged, so keep a default branch. A refusal whose Retry-After is longer than the client waits between attempts or than the context has left, such as the daily limit, is returned at once. What to do about each reason is in Errors.

_, err := client.SaveAsset(ctx, spicy.SaveAssetInput{
    Source: spicy.AssetSourceURL,
    URL:    "https://example.com/still.png",
}, "")
var apiErr *spicy.APIError
if errors.As(err, &apiErr) && apiErr.Reason == spicy.ReasonAssetLibraryFull {
    usage, usageErr := client.GetAssetUsage(ctx)
    if usageErr != nil {
        return usageErr
    }
    log.Printf("full on %s (%d of %d items)", usage.Tier.Name, usage.Usage.Count, usage.Limits.MaxCount)
} else if err != nil {
    return err
}

Two things that will save you money

Keep one idempotency key per submission. Reuse it for every resend, including after a timeout. A lost response does not prove the task was not created — a fresh key turns an unknown outcome into a second paid task. CreateTask requires the key for exactly this reason. See Idempotency.

A task that succeeds is charged, even if the result disappoints. Quote reserves nothing, so quote first when the price matters.

What this package does not do

  • Text models. They speak the OpenAI, Anthropic and Gemini wire formats — the established Go clients for those already work against https://api.spicyapi.ai/v1 with the same key. See Text and streaming.
  • Client-side applications. Never ship this key inside a binary you distribute. Call from your server.
  • Choosing a model or filling in its fields. It hands you the catalogue and each model's schema; you decide what to send.
  • Cancelling a task. Once a task is accepted it runs to the end. Cancelling the context only stops your waiting.

Source

The module is MIT-licensed and developed in the open at github.com/spicyapi-ai/spicy-go. Its README is the shortest complete tour of the client; this page adds the surrounding concepts.

Next steps

On this page