Skip to content

Use the asynchronous client

Topics: clients, generation, images, requests

Use the async client inside an existing asyncio application. The caller owns the aiohttp.ClientSession; closing it is the observable end of its connection pool and must happen after all Horde calls finish.

async def generate_image_async(api_key: str = ANON_API_KEY) -> bytes:
    """Run the image recipe without blocking the event loop."""
    async with aiohttp.ClientSession() as http_session:
        client = AIHordeAPIAsyncSimpleClient(aiohttp_session=http_session, apikey=api_key)
        status, _request_id = await client.image_generate_request(image_request(api_key))
        if not status.generations:
            raise RuntimeError("The request completed without an image")
        image, _generation_id = await client.download_image_from_generation(status.generations[0])
        return image.tobytes()

Verify that the coroutine returns non-empty bytes and that no unclosed-session warning appears. For multiple requests, create one session outside the individual coroutine calls and pass the same session to each client.

Cancellation propagates through the awaiting task. Keep the client/session context alive until cleanup completes; if you require explicit cancellation control, use AIHordeAPIAsyncManualClient and the same lifecycle described in clean up manual requests.