First we need to add a new endpoint to our application. We will use the same approach as in the previous blog post.
@Bean
fun aiRouter(chatClient: OpenAiChatClient, imageClient: OpenAiImageClient) = router {
...
GET("/api/ai/generateImage") { request ->
ServerResponse
.ok()
.contentType(MediaType.parseMediaType("application/zip"))
.body(
imageResponse(imageClient, request
.param("message")
.orElse("A photo of a cat"))
)
}
...
}
The … means that I removed some code to focus on the important part.
As we can see, we now use an OpenAiImageClient to generate the image.
The imageResponse method is used to call this client and download the generated the image.
@Configuration(proxyBeanMethods = false)
class RouterConfiguration {
...
private fun imageResponse(imageClient: OpenAiImageClient): ByteArray {
val imageResponse = imageClient.call(
ImagePrompt(
instruction
)
)
val imageInBase64 = imageResponse.result.output.b64Json
val files = imageResponse.results.asSequence().withIndex().map {
val test = imageInBase64.decodeFromBase64(it.value.output.b64Json)
Pair("${it.index}.png", test)
}.toMap()
return ZipUtilities.createZipFile(files)
}
}
The … means that I removed some code to focus on the important part.
Spring AI would be able to download more than one image but the Open AI API only returns one image. The code could handle more than one image if the API returns more than one image.
Because Spring AI support other API to generate images such as Stability API.
The ZipUtilities and its createZipFile method are used to create a zip file from with as many image as the map contains.
object ZipUtilities {
fun createZipFile(pngFiles: Map<String, ByteArray>): ByteArray {
ByteArrayOutputStream().use { baos ->
ZipOutputStream(baos).use { zos ->
pngFiles.forEach { (fileName, fileContent) ->
val entry = ZipEntry(fileName)
zos.putNextEntry(entry)
zos.write(fileContent)
zos.closeEntry()
}
}
return baos.toByteArray()
}
}
}
To try our endpoint we can use the following curl command:
curl "localhost:8080/api/ai/generateImage" -o image.zip
The image.zip file should contain a photo of a cat.
0 is the index of the image in the return result.
If you want to adapt the message to personalize the image, you can use the following command:
curl "localhost:8080/api/ai/generateImage?message=a%20photo%20of%20a%20dog" -o image.zip