Skip to content

About

A minimal, dependency-light Java 17 client for the PixAI image-generation REST API v2. Fluent immutable builders, typed model-aware parameters, blocking or async generation, LoRA and webhook support - only OkHttp + org.json at runtime.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

12 Commits

Folders and files

Repository files navigation

pixai-api-java

⚠️ Unofficial, community-built client. Not affiliated with or endorsed by PixAI.

A minimal, dependency-light Java client for the PixAI image-generation REST API v2. Give it a prompt; it starts a generation task, waits for completion, and gives you the resulting image(s) as bytes or saves them to disk.

Features

  • Fluent, immutable API — configure the client and each request with builders.
  • High-level generate(...) (submit → wait → fetch) plus low-level task methods.
  • Async twin for every call — generateAsync(...) returns a CompletableFuture and holds no thread while the task runs. Built for bots serving many concurrent generations.
  • Automatic retries of 429 / 5xx / network errors with exponential backoff, honouring Retry-After.
  • Typed exceptions — branch on PixAIRateLimitException, PixAIAuthException, PixAITimeoutException, PixAITaskFailedException instead of parsing messages.
  • First-class LoRA support — up to 5 per request, with weights, URL parsing and duplicate detection.
  • Every documented request parameter has a typed builder method, with enums for model, aspectRatio, size, mode and samplingMethod.
  • Type-aware validation of model-dependent parameters.
  • Returns a Task with status, timestamps, failure reason and multiple images.
  • Java 17, only OkHttp and org.json at runtime.

Tech stack

Java 17 · OkHttp · org.json · Maven

Installation

Not on a public registry yet — the easiest way is to download the self-contained jar from the release and put it on your classpath.

Option 1 — Download the jar (recommended)

  1. Download pixai-api-java-1.1.1-all.jar from the latest release.
  2. Add it to your project:
    • Eclipse: Project → Properties → Java Build Path → Libraries → select Classpath → Add External JARs… → pick the jar.
    • IntelliJ IDEA: File → Project Structure → Libraries → + → Java → pick the jar.
    • Command line:
      javac -cp pixai-api-java-1.1.1-all.jar Main.java
      java  -cp ".:pixai-api-java-1.1.1-all.jar" Main      # Windows: use ';' instead of ':'

The -all jar bundles every runtime dependency (OkHttp, Okio, kotlin-stdlib, org.json), so there is nothing else to add.

If your project uses the Java module system (has a module-info.java), add requires kz.arianwaitstudio.pixai; and put the jar on the module path.

Option 2 — Maven / Gradle (local install)

If you build with Maven, install it into your local repository and depend on it:

./mvnw install
<dependency>
  <groupId>kz.arianwaitstudio.pixai</groupId>
  <artifactId>pixai-api-java</artifactId>
  <version>1.1.1</version>
</dependency>

Quickstart (4 steps)

The default model is Tsubaki.2, so the only required field is the prompt: create the client, pass your key, set the prompt, run.

import kz.arianwaitstudio.pixai.*;
import java.nio.file.Paths;

PixAIClient client = new PixAIClient(System.getenv("PIXAI_API_KEY")); // 1) client + 2) key

GenerationParameters params = GenerationParameters.builder()
        .prompt("a fox in a forest, digital art")                    // 3) prompt (required)
        .build();

Task task = client.generate(params);                                  // 4) run (blocks until done)

task.images().get(0).saveTo(Paths.get("out"));                       // -> out/picture_PixAI_<timestamp>.png

Gallery

Generated with this client.

silver-haired elf knight in ornate plate armor with phoenixes
elf knight in ornate armor, phoenixes
floating island with waterfalls above the clouds at sunset
floating island, waterfalls, sunset
cyberpunk girl with a neon-lit city at night
cyberpunk portrait, neon city

Examples

Full configuration

PixAIClient client = PixAIClient.builder()
        .apiKey(System.getenv("PIXAI_API_KEY"))
        .pollInterval(java.time.Duration.ofSeconds(3)) // status poll interval (default 5s)
        .timeout(java.time.Duration.ofMinutes(5))      // max wait (default 10 min)
        .build();

GenerationParameters params = GenerationParameters.builder()
        .model(Model.HARUKA_V2)             // or .modelVersionId("...") for a custom model
        .prompt("1girl, kimono, cherry blossoms")
        .negativePrompt("low quality, blurry")
        .aspectRatio(AspectRatio.RATIO_9_16)
        .size(Size.ONE_K)
        .seed(42L)
        .promptHelper(false)                // don't auto-enhance the prompt
        .build();

Task task = client.generate(params);
for (GeneratedImage img : task.images()) {
    byte[] bytes = img.getBytes();                              // raw bytes
    java.nio.file.Path saved = img.saveTo(Paths.get("out"), "fox.png"); // or a custom file name
    System.out.println(img.getUrl() + " -> " + saved);
}

Model-dependent parameters

// Tsubaki.2 (DiT) — mode and style are available:
GenerationParameters.builder()
        .model(Model.TSUBAKI_2)          // optional — this is the default
        .prompt("knight in armor")
        .mode(Mode.ULTRA)                // lite/standard/pro/ultra — Tsubaki.2 only
        .style(Style.builder().set("name", "anime").build())
        .build();

// SDXL (Haruka / Hoshino) — sampling is available:
GenerationParameters.builder()
        .model(Model.HARUKA_V2)
        .prompt("knight in armor")
        .sampling(Sampling.builder()
                .method(SamplingMethod.DPMPP_2M_KARRAS)
                .set("steps", 25)        // sampling fields are flexible (see notes)
                .build())
        .build();

Mixing incompatible parameters throws at build time:

GenerationParameters.builder()
        .model(Model.HARUKA_V2)  // SDXL
        .prompt("x")
        .mode(Mode.PRO)          // mode is Tsubaki.2-only
        .build();                // -> IllegalStateException

LoRA (up to 5)

A request may carry up to 5 LoRAs. Each references a LoRA version id — the last segment of its URL on pixai.art — and optionally a weight in [-2.0, 2.0] controlling how strongly it is applied. Leave the weight out to use the PixAI default.

GenerationParameters.builder()
        .prompt("cyberpunk city")
        .addLora("1861558740588989558")                // by version id
        .addLora("1954632828118619567", 0.8)           // with a weight
        .addLoraUrl("https://pixai.art/model/184/1983308862240288769") // pasted from the browser
        .build();

Lora is an immutable value type, so you can derive variants instead of rebuilding them:

Lora base     = Lora.of("1861558740588989558", 0.5);
Lora stronger = base.withWeight(0.9);          // base is untouched
Lora fromUrl  = Lora.fromUrl("https://pixai.art/model/184/1861558740588989558");

base.getModelVersionId();   // "1861558740588989558"
base.getWeight();           // 0.5 (null when unset)

Invalid input is rejected where you make the mistake, not by the server:

Lora.of("v", 9.0);                       // IllegalArgumentException — weight out of range
Lora.fromUrl("https://pixai.art/model/"); // IllegalArgumentException — no version id in the URL

GenerationParameters.builder()
        .prompt("x")
        .addLora("same-id", 0.5)
        .addLora("same-id", 0.9)          // IllegalStateException — duplicate LoRA
        .build();

For fields the published schema does not cover, set them explicitly:

Lora.builder().modelVersionId("1861...").weight(0.8).set("customField", true).build();
Lora.raw(Map.of("modelVersionId", "1861...", "anything", "else")); // full control

Low-level control (no blocking generate)

Task created = client.createTask(params);            // returns immediately, status PENDING
Task done    = client.awaitCompletion(created.getId());
if (done.getStatus() == TaskStatus.COMPLETED) {
    done.images().forEach(i -> i.saveTo(Paths.get("out")));
}

Task snapshot = client.getTask(created.getId());     // or poll manually
System.out.println(snapshot.getStatus() + " / raw: " + snapshot.getRawStatus());

Asynchronous generation

Every call has a non-blocking ...Async twin returning a CompletableFuture. Nothing holds a thread while the task runs: the HTTP call is enqueued on the OkHttp dispatcher and each poll is scheduled on an internal timer — so a bot can have hundreds of generations in flight.

client.generateAsync(params)
      .thenCompose(task -> task.images().get(0).saveToAsync(Paths.get("out")))
      .whenComplete((path, err) -> {
          if (err != null) log.warn("generation failed", err.getCause());
          else             log.info("saved to {}", path);
      });

Available async methods: generateAsync, createTaskAsync, getTaskAsync, awaitCompletionAsync, plus GeneratedImage.getBytesAsync / saveToAsync. Futures fail with a CompletionException wrapping the same exception type the blocking calls throw.

The client owns an HTTP pool and a poll thread, so close it when your app shuts down (a caller-supplied OkHttpClient is left alone):

try (PixAIClient client = PixAIClient.builder().apiKey(key).build()) {
    // ...
}

Retries and rate limits

Transient failures — HTTP 429, 5xx and network errors — are retried automatically with exponential backoff. A Retry-After header from the server wins over the computed delay. Other 4xx responses are never retried.

PixAIClient client = PixAIClient.builder()
        .apiKey(key)
        .retryPolicy(RetryPolicy.builder()
                .maxAttempts(5)                            // total, including the first (default 3)
                .initialBackoff(Duration.ofMillis(500))    // default 500 ms
                .multiplier(2.0)                           // default x2
                .maxBackoff(Duration.ofSeconds(20))        // default 20 s
                .respectRetryAfter(true)                   // default true
                .build())
        .build();

PixAIClient failFast = PixAIClient.builder()
        .apiKey(key)
        .retryPolicy(RetryPolicy.NONE)   // no retries at all
        .build();

Error handling

Each failure mode has its own exception type, so you can branch on it without parsing messages. All of them extend PixAIException, which carries getStatusCode(), getErrorCode() and getResponseBody().

try {
    Task t = client.generate(params);
} catch (PixAIRateLimitException e) {
    // 429 — retries were exhausted; the server may have said how long to wait
    scheduleRetry(e.getRetryAfter().orElse(Duration.ofSeconds(30)));
} catch (PixAIAuthException e) {
    // 401/403 — bad or expired API key, never retried
    alertBadApiKey();
} catch (PixAITaskFailedException e) {
    // the task itself failed or was cancelled — with the server-side reason
    log.warn("task {} failed: {}", e.getTask().getId(), e.getTask().getErrorMessage());
} catch (PixAITimeoutException e) {
    // still running server-side — pick it up later by id
    resumeLater(e.getTaskId());
} catch (PixAIException e) {
    log.error("PixAI error {} ({}): {}", e.getStatusCode(), e.getErrorCode(), e.getResponseBody());
}

Resolution helper (no API call)

int w = AspectRatio.RATIO_16_9.width(Size.ONE_K);             // 1280
int h = AspectRatio.RATIO_16_9.height(Size.ONE_K);            // 720
int w2 = AspectRatio.RATIO_16_9.width(Size.ONE_AND_A_HALF_K); // 1536

Webhook instead of polling

GenerationParameters params = GenerationParameters.builder()
        .prompt("a fox")
        .callbackUrl("https://my-server.example/pixai-webhook") // PixAI POSTs on status changes
        .build();

Task created = client.createTask(params); // don't wait — handle the webhook on your server

There is a runnable sample at examples/PixAIExample.java (not part of the Maven build).


API reference

PixAIClient

The entry point. Immutable and thread-safe. All methods throw PixAIException on failure.

Construction

Member Description
new PixAIClient(String apiKey) Client with all defaults.
PixAIClient.builder() Returns a Builder for full configuration.

PixAIClient.Builder

Method Default Description
apiKey(String) — (required) PixAI API key.
baseUrl(String) https://api.pixai.art API base URL.
pollInterval(Duration) 5s How often status is polled while waiting.
timeout(Duration) 10 min Max wait before giving up on a task.
retryPolicy(RetryPolicy) RetryPolicy.DEFAULT Retrying of 429/5xx/network errors.
httpClient(OkHttpClient) 60s-timeout OkHttpClient Custom HTTP client (proxy, timeouts…).
build() Builds the client (validates every field).

Methods — each has a non-blocking ...Async twin returning CompletableFuture.

Method Returns Description
generate(GenerationParameters) Task Submit → wait → return completed task. Throws if not COMPLETED.
generateAsync(GenerationParameters) CompletableFuture<Task> Same flow, holding no thread.
createTask(GenerationParameters) / createTaskAsync Task Submit and return immediately (non-terminal status).
getTask(String taskId) / getTaskAsync Task Current state of a task.
awaitCompletion(String taskId) / awaitCompletionAsync Task Poll until terminal status (or timeout).
close() void Releases the poll thread and the HTTP pool it owns.

RetryPolicy

How transient failures are retried. Immutable; build with RetryPolicy.builder(), or use RetryPolicy.DEFAULT / RetryPolicy.NONE.

Method Default Description
maxAttempts(int) 3 Total attempts including the first (1 disables retrying).
initialBackoff(Duration) 500 ms Delay before the first retry.
multiplier(double) 2.0 Growth factor between attempts.
maxBackoff(Duration) 20 s Ceiling for any single delay.
respectRetryAfter(boolean) true Whether Retry-After overrides the computed delay.

Retried: 429, 5xx, network I/O errors. Never retried: other 4xx.

GenerationParameters

Immutable request body; build with GenerationParameters.builder(). Every field has a getter (getPrompt(), getModelVersionId(), getLoras(), getSeed(), …), and toBuilder() derives a variant request without mutating the original.

GenerationParameters.Builder

Method API field Notes
prompt(String) prompt Required.
model(Model) modelVersionId Defaults to Model.TSUBAKI_2. Enables type-aware validation.
modelVersionId(String) modelVersionId Custom model (last URL segment); skips type validation.
modelId(String) modelId @Deprecated — use model / modelVersionId.
negativePrompt(String) negativePrompt What to exclude.
aspectRatio(AspectRatio) / aspectRatio(String) aspectRatio Default 1:1.
size(Size) / size(String) size Default 1k.
mode(Mode) / mode(String) mode Tsubaki.2 only.
style(Style) style Tsubaki.2 only.
addLora(String) / addLora(String, double) / addLora(Lora) / addLoraUrl(String) / loras(List<Lora>) / clearLoras() loras Up to 5; duplicates rejected.
seed(long) seed Reproducibility (random when unset).
sampling(Sampling) sampling SDXL / SD v1 only.
promptHelper(boolean) promptHelper true→enable, false→disable (default enable).
callbackUrl(String) callbackUrl Status-change webhook.
build() Validates prompt, LoRA count and model compatibility.

Task

Method Returns Description
getId() String Task id.
getStatus() TaskStatus Parsed status.
getRawStatus() String Raw status string from the API.
getCreatedAt() / getUpdatedAt() / getStartedAt() / getEndAt() Instant Timestamps (nullable).
getErrorMessage() String Why the task failed, when the API said (nullable).
getErrorCode() String Machine-readable failure code (nullable).
isCompleted() boolean Whether the task finished successfully.
images() List<GeneratedImage> Generated images (empty until completed; unmodifiable).

GeneratedImage

Method Returns Description
getMediaId() String Media id (nullable).
getUrl() String Download URL.
getBytes() / getBytesAsync() byte[] Downloads once, then caches (thread-safe).
saveTo(Path dir) / saveToAsync Path Saves as picture_PixAI_<timestamp>.<ext>.
saveTo(Path dir, String fileName) / saveToAsync Path Saves under a custom name.
getFileExtension() String Extension implied by the URL (e.g. webp), png as fallback.

Lora

Immutable value type; up to Lora.MAX_PER_REQUEST (5) per request.

Member Returns Description
Lora.of(String versionId) Lora By version id, server-default weight.
Lora.of(String versionId, double weight) Lora With a weight in [-2.0, 2.0].
Lora.fromUrl(String url) Lora Parses the version id out of a pixai.art URL.
Lora.versionIdFromUrl(String url) String Just the id, without building a Lora.
Lora.raw(Map) Lora Full control over the serialised object.
Lora.builder() Builder .modelVersionId(..), .url(..), .weight(..), .set(k, v).
getModelVersionId() / getWeight() String / Double Typed accessors (weight null when unset).
getFields() Map<String,Object> Unmodifiable view of everything serialised.
withWeight(double) / toBuilder() Lora / Builder Derive a variant without mutating.

Validated at build time: blank version id, weight outside [-2.0, 2.0] or non-finite, a URL with no id (all IllegalArgumentException), more than 5 LoRAs or a duplicate version id in one request (IllegalStateException).

Flexible objects: Style, Sampling

Their full sub-schemas aren't published, so they're flexible key/value wrappers.

Type Factories / builder
Style Style.of(Map), Style.builder().set(k, v).build()
Sampling Sampling.of(Map), Sampling.builder().set(k, v).method(SamplingMethod).build()

Field-name assumptions to revisit once the Models / Supported Resolutions sub-schemas are available: Sampling.method(...) writes the samplingMethod key.

Exceptions

All unchecked and all extending PixAIException, so a single catch still covers everything.

Type Thrown when Extra methods
PixAIException Anything else: network failure, unparseable body, other 4xx. getStatusCode(), getErrorCode(), getResponseBody(), isRetryable()
PixAIAuthException HTTP 401/403 — bad or expired key. Never retried. —
PixAIRateLimitException HTTP 429 after retries were exhausted. getRetryAfter() → Optional<Duration>
PixAIServerException HTTP 5xx after retries were exhausted. —
PixAITimeoutException The task did not finish within timeout. The task keeps running server-side. getTaskId(), getWaited()
PixAITaskFailedException The task itself failed or was cancelled. getTask(), getStatus()

getStatusCode() returns PixAIException.NO_STATUS (-1) when the failure was not an HTTP response (network error, timeout, failed task).


Enums & values

Model

Constant versionId() type()
TSUBAKI_2 (= Model.DEFAULT) 1983308862240288769 DIT
HARUKA_V2 1861558740588989558 SDXL
HOSHINO_V2 1954632828118619567 SDXL

ModelType

SDXL · DIT · SD_V1

AspectRatio — value(), width(Size), height(Size), fromValue(String)

Constant value() 1k (W×H) 1.5k (W×H)
RATIO_1_1 1:1 1024×1024 1536×1536
RATIO_2_3 2:3 848×1280 1024×1536
RATIO_3_2 3:2 1280×848 1536×1024
RATIO_3_4 3:4 864×1152 1152×1536
RATIO_4_3 4:3 1152×864 1536×1152
RATIO_3_5 3:5 768×1280 912×1536
RATIO_5_3 5:3 1280×768 1536×912
RATIO_9_16 9:16 720×1280 864×1536
RATIO_16_9 16:9 1280×720 1536×864
RATIO_1_3 1:3 512×1536 512×1536
RATIO_3_1 3:1 1536×512 1536×512

Size — value(), fromValue(String)

Constant value() Resolution
ONE_K 1k ~1 MP (1024×1024 at 1:1)
ONE_AND_A_HALF_K 1.5k ~2.36 MP (long side ≤ 1536 px)

Mode (Tsubaki.2 only) — value(), fromValue(String)

Constant value() Meaning
LITE lite Fastest, base quality.
STANDARD standard Balanced (default).
PRO pro Higher quality, slower.
ULTRA ultra Max quality, slowest.

SamplingMethod (SDXL / SD v1) — value(), fromValue(String)

EULER_A (Euler a) · EULER (Euler) · LMS · HEUN (Heun) · DPM2_KARRAS (DPM2 Karras) · DPM2_A_KARRAS (DPM2 a Karras) · DDIM · DPMPP_2M_KARRAS (DPM++ 2M Karras) · DPMPP_2S_A_KARRAS (DPM++ 2S a Karras) · DPMPP_SDE_KARRAS (DPM++ SDE Karras) · DPMPP_2M_SDE_KARRAS (DPM++ 2M SDE Karras) · RESTART (Restart)

TaskStatus — isTerminal(), fromApi(String)

Constant Terminal? Maps from
PENDING no waiting, pending
PROCESSING no started, running, processing
COMPLETED yes completed, success
FAILED yes failed, error
CANCELLED yes cancelled, canceled
UNKNOWN no anything unrecognised

Not covered yet

The library implements what the PixAI v2 docs specify: POST /v2/image/create and task polling. Endpoints that exist in the product but are not documented in the public API reference are deliberately absent rather than guessed:

  • image-to-image / media upload
  • cancelling a running task
  • credit balance
  • listing models and LoRAs

If PixAI publishes these, they are straightforward to add on top of the existing transport.

Building from source

Requirements: JDK 17+ (a JDK 21/25 also works). Maven is not required — use the bundled wrapper:

./mvnw clean verify   # compile + run the offline tests
./mvnw package        # build the jar (+ sources & javadoc jars) into target/

⚠️ Security

Do not hardcode or commit your PixAI API key. Pass it from an environment variable or a local config file listed in .gitignore. If a key was ever committed, rotate it in your PixAI account — deleting the file does not remove it from git history.

License

MIT © Yelzhan Ibragimov (Arianwait)

About

A minimal, dependency-light Java 17 client for the PixAI image-generation REST API v2. Fluent immutable builders, typed model-aware parameters, blocking or async generation, LoRA and webhook support - only OkHttp + org.json at runtime.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages