Repository navigation
Expand file tree
/
Copy pathPixAIExample.java
More file actions
139 lines (124 loc) · 5.94 KB
/
Copy pathPixAIExample.java
File metadata and controls
139 lines (124 loc) · 5.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import kz.arianwaitstudio.pixai.AspectRatio;
import kz.arianwaitstudio.pixai.GeneratedImage;
import kz.arianwaitstudio.pixai.GenerationParameters;
import kz.arianwaitstudio.pixai.Lora;
import kz.arianwaitstudio.pixai.Model;
import kz.arianwaitstudio.pixai.PixAIAuthException;
import kz.arianwaitstudio.pixai.PixAIClient;
import kz.arianwaitstudio.pixai.PixAIException;
import kz.arianwaitstudio.pixai.PixAIRateLimitException;
import kz.arianwaitstudio.pixai.PixAITaskFailedException;
import kz.arianwaitstudio.pixai.PixAITimeoutException;
import kz.arianwaitstudio.pixai.RetryPolicy;
import kz.arianwaitstudio.pixai.Size;
import kz.arianwaitstudio.pixai.Task;
/**
* Runnable sample for the pixai-api-java library (PixAI API v2).
*
* <p>This file is documentation only and is intentionally NOT part of the Maven build. To run it,
* build/install the library first ({@code ./mvnw install}) and compile this file against the
* produced jar, or paste the body into your own project.
*
* <p>The API key is read from the {@code PIXAI_API_KEY} environment variable so it is never
* hardcoded or committed.
*/
public class PixAIExample {
public static void main(String[] args) throws Exception {
String apiKey = System.getenv("PIXAI_API_KEY");
if (apiKey == null || apiKey.isBlank()) {
System.err.println("Set the PIXAI_API_KEY environment variable first.");
return;
}
// The client owns an HTTP pool and a poll thread; close it when the app shuts down.
try (PixAIClient client = PixAIClient.builder()
.apiKey(apiKey)
.retryPolicy(RetryPolicy.builder() // retries 429/5xx with backoff
.maxAttempts(4)
.initialBackoff(Duration.ofSeconds(1))
.build())
.build()) {
simplest(client);
withLoras(client);
asynchronous(client);
typedErrorHandling(client);
}
}
/** The 4-step path: client, key, prompt, run. */
private static void simplest(PixAIClient client) {
GenerationParameters minimal = GenerationParameters.builder()
.prompt("a fox in a forest, digital art")
.build();
Task task = client.generate(minimal); // blocks until completion
for (GeneratedImage image : task.images()) {
Path saved = image.saveTo(Paths.get("out")); // extension taken from the URL
System.out.println("Image saved to: " + saved);
}
}
/** Up to 5 LoRAs per request, each with an optional weight. */
private static void withLoras(PixAIClient client) {
GenerationParameters params = GenerationParameters.builder()
.model(Model.HARUKA_V2)
.prompt("1girl, kimono, cherry blossoms")
.negativePrompt("low quality, blurry")
.aspectRatio(AspectRatio.RATIO_9_16)
.size(Size.ONE_K)
.addLora("1861558740588989558") // by version id
.addLora("1954632828118619567", 0.8) // with a weight
.addLoraUrl("https://pixai.art/model/184/1983308862240288769") // pasted URL
.seed(42L)
.build();
Task task = client.generate(params);
task.images().forEach(img -> System.out.println(img.getUrl()));
// LoRAs are immutable values: derive variants instead of mutating.
Lora base = Lora.of("1861558740588989558", 0.5);
GenerationParameters stronger = params.toBuilder()
.clearLoras()
.addLora(base.withWeight(0.9))
.build();
System.out.println("variant loras: " + stronger.getLoras());
}
/** Non-blocking flow: nothing holds a thread while the generation runs. */
private static void asynchronous(PixAIClient client) throws Exception {
GenerationParameters params = GenerationParameters.builder()
.prompt("a cyberpunk city at night")
.build();
CompletableFuture<Path> saved = client.generateAsync(params)
.thenCompose(task -> task.images().get(0).saveToAsync(Paths.get("out")))
.whenComplete((path, error) -> {
if (error != null) {
System.err.println("generation failed: " + error.getCause());
} else {
System.out.println("saved asynchronously to " + path);
}
});
// Fire several at once — a bot would keep these futures instead of blocking.
List<CompletableFuture<Task>> batch = List.of(
client.generateAsync(params),
client.generateAsync(params));
CompletableFuture.allOf(batch.toArray(new CompletableFuture[0])).join();
saved.join();
}
/** Every failure mode has its own exception type. */
private static void typedErrorHandling(PixAIClient client) {
try {
client.generate(GenerationParameters.builder().prompt("a fox").build());
} catch (PixAIRateLimitException e) {
Duration wait = e.getRetryAfter().orElse(Duration.ofSeconds(30));
System.err.println("rate limited, retry in " + wait);
} catch (PixAIAuthException e) {
System.err.println("bad API key (HTTP " + e.getStatusCode() + ")");
} catch (PixAITaskFailedException e) {
System.err.println("task " + e.getTask().getId() + " failed: "
+ e.getTask().getErrorMessage());
} catch (PixAITimeoutException e) {
System.err.println("still running, poll " + e.getTaskId() + " later");
} catch (PixAIException e) {
System.err.println("PixAI error " + e.getStatusCode() + ": " + e.getResponseBody());
}
}
}