AsyncTask
This section will demonstrate how to obtain different types of Response through various combinations of parameters. The Generate interface provides the following types of Response:
ImageResponse
: Image bytesJsonResponse
: Json stringStreamResponse
:Stream output
Among them, ImageResponse
and StreamResponse
are synchronous, while JsonResponse
can be either synchronous or asynchronous depending on the parameters.
The example will be demonstrated with Text to Image
.
Synchronous Request
JsonResponse
This is the return type with default parameters, which is also the type used in the previous examples.
Upon completion, you can obtain the list of URLs for the generated images in the result
field of the returned JSON.
ImageResponse
Continuing with the code above, if you include headers
in the request and set the accept
parameter to image/xxx
, you will receive an ImageResponse
. The supported formats include image/png
, image/jpg
, image/jpeg
, and image/webp
. Nevertheless, you can write any format after /
, but unsupported formats will be set to image/png
.
Upon completion, you can obtain the binary data of the generated image in response.content
, just as if you were downloading an image directly from the web. If you print it out directly, it will look something like this:
StreamResponse
If you have used LLMs like OpenAI, you should be familiar with streaming output, which returns a stream that you can access using response.iter_lines()
. Continuing with the code above, if you specify the stream_output
parameter as true
in the request, you will receive a StreamResponse
:
You will get this:
By slightly modifying the code to remove unnecessary characters, you can obtain a series of JSON strings:
The output:
Async request
Asynchronous requests only have one type, JsonResponse
. You simply need to specify the async_process
parameter as true
in the request. Its return format is consistent with JsonResponse
, but it will return immediately with some fields being empty.
Output below:
Priority
When the program processes these parameters, it checks accept
, stream_output
, and async_process
in sequence. Once a condition is met, it does not proceed with subsequent checks. This means that the priority order, from highest to lowest, is: accept
, stream_output
, async_process
. This also means that if accept
, stream_output
, and async_process
are all specified at the same time, stream_output
and async_process
will be ignored.