Principle:Togethercomputer Together python Image Response Processing
| Knowledge Sources | |
|---|---|
| Domains | Computer_Vision, Image_Generation, API_Client |
| Last Updated | 2026-02-15 16:00 GMT |
Overview
A pattern for extracting and saving generated image data from the ImageResponse object returned by the Together AI image generation API.
Description
Image Response Processing handles the ImageResponse object returned by the client.images.generate() method. Each response contains metadata about the generation (request ID, model used) and a list of generated images in the data field.
Each image in the data list is an ImageChoicesData object with:
index: The position of the image in the batch (integer starting from 0).b64_json: The generated image encoded as a base64 string, suitable for decoding into raw image bytes.url: An optional hosted URL where the generated image can be downloaded.
Typical processing involves:
- Accessing the
datalist on the response object. - Iterating over each
ImageChoicesDataentry. - Decoding the
b64_jsonfield from base64 to raw bytes using Python'sbase64.b64decode(). - Writing the decoded bytes to a local file (PNG, JPEG, etc.) or passing them to further processing.
Usage
Use this principle after receiving an ImageResponse from the generation API. It applies whenever you need to extract, decode, save, or display the generated images.
Theoretical Basis
Image data is returned base64-encoded to enable direct binary transfer within JSON responses. This design avoids the need for separate file download endpoints and ensures that image data is self-contained in the response payload.
The processing follows this pattern:
- Response parsing: The API returns a JSON response with an
id,model,objecttype (always"list"), and adataarray. The SDK deserializes this into anImageResponsePydantic model. - Data access: Each element in
datais anImageChoicesDatainstance. For single-image requests (n=1), accessresponse.data[0]. For batch requests, iterate overresponse.data. - Base64 decoding: The
b64_jsonfield contains standard base64-encoded image bytes. Callingbase64.b64decode(b64_json)produces the raw binary image data. - File persistence: Writing the decoded bytes to a file with the appropriate extension (e.g.,
.png) creates a valid image file that can be opened by any image viewer.
Pseudo-code:
function processImageResponse(response):
for each image_choice in response.data:
if image_choice.b64_json is not None:
raw_bytes = base64_decode(image_choice.b64_json)
write_file(f"output_{image_choice.index}.png", raw_bytes)
elif image_choice.url is not None:
download_file(image_choice.url, f"output_{image_choice.index}.png")