### Install higgsfield-client Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/README.md Installs the official Python SDK for Higgsfield AI. ```bash pip install higgsfield-client ``` -------------------------------- ### Create session example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Example of creating a session and printing its ID. ```python session = client.agents.sessions.create() print(session.session_id) ``` -------------------------------- ### upload_file usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-client.md Example of uploading a local file by path. ```python url = await client.upload_file('path/to/example.jpeg') ``` -------------------------------- ### Synchronous subscribe example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/README.md Synchronous example that submits a text-to-image request and waits for the result, then prints the URL of the first generated image. ```python import higgsfield_client # Submit and wait for result result = higgsfield_client.subscribe( 'bytedance/seedream/v4/text-to-image', arguments={ 'prompt': 'A serene lake at sunset with mountains', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False } ) print(result['images'][0]['url']) ``` -------------------------------- ### submit usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-client.md Example of calling client.submit with an application, arguments, and an optional webhook URL. ```python controller = await client.submit( 'bytedance/seedream/v4/text-to-image', arguments={'prompt': 'Football ball', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False}, webhook_url='https://example.com/webhook', ) ``` -------------------------------- ### upload_image usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-client.md Example of uploading a Pillow image with a specified format. ```python from PIL import Image url = await client.upload_image(Image.open('example.jpeg'), format='jpeg') ``` -------------------------------- ### Asynchronous subscribe_async example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/README.md Asynchronous example that uses subscribe_async to submit a text-to-image request and await the result, then prints the URL of the first generated image. ```python import asyncio import higgsfield_client async def main(): # Submit and wait for result result = await higgsfield_client.subscribe_async( 'bytedance/seedream/v4/text-to-image', arguments={ 'prompt': 'A serene lake at sunset with mountains', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False } ) print(result['images'][0]['url']) asyncio.run(main()) ``` -------------------------------- ### subscribe usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-client.md Example of using client.subscribe with an on_queue_update callback that prints the status type name, then prints the first image URL from the result. ```python async def main(): async def on_update(status): print(type(status).__name__) result = await client.subscribe( 'bytedance/seedream/v4/text-to-image', arguments={'prompt': 'A serene lake', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False}, on_queue_update=on_update, ) print(result['images'][0]['url']) ``` -------------------------------- ### AsyncHttpTransport usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/transport.md Shows how to instantiate AsyncHttpTransport with an httpx.AsyncClient and NoRetry, then make an async request. The example uses asyncio.run to execute the main coroutine. ```python import asyncio import httpx from higgsfield_client.http.transport import AsyncHttpTransport async def main(): client = httpx.AsyncClient(base_url='https://api.higgsfield.ai') transport = AsyncHttpTransport(client, NoRetry()) response = await transport.request('GET', '/requests/abc/status') print(response.json()) asyncio.run(main()) ``` -------------------------------- ### Direct call example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/auth.md Demonstrates calling get_credential_key directly with environment variables set. Shows HF_API_KEY/HF_API_SECRET combination, HF_KEY precedence, and the CredentialsMissedError when nothing is configured. ```python import os from higgsfield_client.auth import get_credential_key from higgsfield_client import CredentialsMissedError os.environ['HF_API_KEY'] = 'key-id' os.environ['HF_API_SECRET'] = 'key-secret' print(get_credential_key()) # 'key-id:key-secret' os.environ['HF_KEY'] = 'key-id:key-secret' print(get_credential_key()) # 'key-id:key-secret' (HF_KEY wins) # When nothing is configured: os.environ.pop('HF_KEY', None) os.environ.pop('HF_API_KEY', None) os.environ.pop('HF_API_SECRET', None) try: get_credential_key() except CredentialsMissedError as exc: print(exc) # 'Higgsfield API credentials missing. ...' ``` -------------------------------- ### upload usage with error handling Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-client.md Example of uploading a file as bytes and handling HiggsfieldClientError exceptions. ```python data = open('example.jpeg', 'rb').read() url = await client.upload(data, 'image/jpeg') # error handling from higgsfield_client import HiggsfieldClientError try: await client.upload(b'bad', 'image/jpeg') except HiggsfieldClientError as exc: print(f'upload failed: {exc}') ``` -------------------------------- ### Full async agent workflow Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-agents.md Complete example of an async agent workflow: create a session, run a request with a question handler, print results, and run a follow-up request. Demonstrates the full lifecycle of an async agent session. ```python import asyncio from higgsfield_client import AsyncClient async def main(): client = AsyncClient() session = await client.agents.sessions.create() result = await client.agents.sessions.run( session.session_id, "Generate one image of a quiet alpine lake at sunrise. Reply with the image URL.", on_question=lambda q: "Photorealistic style.", ) print(result.status) print(result.text) print(result.asset_urls) follow_up = await client.agents.sessions.run( session.session_id, "Now make a 16:9 version of the same scene at dusk." ) print(follow_up.text) asyncio.run(main()) ``` -------------------------------- ### Retry log output example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/transport.md Example DEBUG-level log message showing retry attempts with backoff. ```text [2/3] Retrying POST https://... due to 429; sleeping 0.4s ``` -------------------------------- ### Example usage of get_status Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/utils.md Demonstrates calling get_status with valid statuses and handling an unknown status. Prints 'InProgress()', 'Completed()', and 'Unknown status: mystery'. ```python from higgsfield_client.utils import get_status from higgsfield_client import InProgress, Completed print(get_status({'status': 'in_progress'})) # InProgress() print(get_status({'status': 'completed'})) # Completed() try: get_status({'status': 'mystery'}) except ValueError as exc: print(exc) # Unknown status: mystery ``` -------------------------------- ### HttpTransport usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/transport.md Shows how to create an HttpTransport with NoRetry and make a request, catching HiggsfieldClientError. ```python import httpx from higgsfield_client.http.transport import HttpTransport from higgsfield_client.http.retry import NoRetry from higgsfield_client import HiggsfieldClientError client = httpx.Client(base_url='https://api.higgsfield.ai') transport = HttpTransport(client, NoRetry()) try: response = transport.request('GET', '/requests/abc/status') except HiggsfieldClientError as exc: print(f'request failed: {exc}') ``` -------------------------------- ### AsyncMedia.upload usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-agents.md Shows how to upload a file using the async media upload method. The upload returns a CDN URL that can be used in message content. Requires an open file and an existing session. ```python async def main(): client = AsyncClient() with open("photo.jpeg", "rb") as f: url = await client.agents.media.upload(f.read(), extension="jpeg", type="image") await client.agents.sessions.run(session.session_id, f"Animate this image: {url}") ``` -------------------------------- ### get() method implementation Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/request-controllers.md Polls until a terminal status is reached (discarding each status), then performs a GET request to the response URL and returns the JSON payload. For image applications, the payload typically contains an 'images' key with a list of image URLs. ```python def get(self) -> AnyJSON: for _ in self.poll_request_status(): continue response = self._transport.request('GET', self.response_url) return response.json() ``` -------------------------------- ### Run a full agent turn with error handling Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-agents.md Complete example of running a turn: creates a session, sends a message with an on_question handler, prints the result, and catches AgentTimeoutError for local timeouts. The server turn continues running even after a local timeout. ```python async def main(): client = AsyncClient() session = await client.agents.sessions.create() result = await client.agents.sessions.run( session.session_id, "Generate an image of an alpine lake at sunrise. Reply with the image URL.", on_question=lambda question: "Photorealistic style.", ) print(result.status, result.text, result.asset_urls) # error handling from higgsfield_client import AgentTimeoutError try: await client.agents.sessions.run(session.session_id, "a long task", timeout=120) except AgentTimeoutError as exc: print(f'timed out locally: {exc}') ``` -------------------------------- ### Example usage of get_url Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/utils.md Shows get_url with and without a webhook URL. The second call URL-encodes the webhook URL in the query parameter. ```python from higgsfield_client.utils import get_url get_url('bytedance/seedream/v4/text-to-image', None) # 'bytedance/seedream/v4/text-to-image' get_url('bytedance/seedream/v4/text-to-image', 'https://example.com/hook') # 'bytedance/seedream/v4/text-to-image?hf_webhook=https%3A%2F%2Fexample.com%2Fhook' ``` -------------------------------- ### Sessions.send method example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Sends a user message to a session and returns the `message_id`. The turn runs asynchronously server-side; poll with `messages()`. ```python message_id = client.agents.sessions.send(session.session_id, "Generate a sunset image") ``` -------------------------------- ### Use module-level subscribe function Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/package.md The package re-exports the public API and provides module-level client instances (sync_client and async_client) with methods bound to module-level functions. This example calls higgsfield_client.subscribe without instantiating any object. Module-level instances use default options (base_url=BASE_URL, timeout=DEFAULT_TIMEOUT, api_key=None); the API key is resolved lazily from the environment on first request. ```python import higgsfield_client result = higgsfield_client.subscribe('bytedance/seedream/v4/text-to-image', arguments={...}) ``` -------------------------------- ### UploadMixin usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/upload-mixin.md Demonstrates calling the static helpers directly. guess_mime_type returns 'image/jpeg' for a .jpeg file and 'application/octet-stream' when the MIME type cannot be determined. ensure_bytes encodes strings to UTF-8 and passes bytes through unchanged. image_to_bytes serializes a Pillow image to bytes in the given format (default 'jpeg'). ```python from higgsfield_client.mixins import UploadMixin UploadMixin.guess_mime_type('photo.jpeg') # 'image/jpeg' UploadMixin.guess_mime_type('archive') # 'application/octet-stream' UploadMixin.ensure_bytes('hello') # b'hello' UploadMixin.ensure_bytes(b'raw') # b'raw' from PIL import Image img = Image.open('example.jpeg') UploadMixin.image_to_bytes(img, 'png') # PNG bytes ``` -------------------------------- ### status() method implementation Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/request-controllers.md Performs a GET request to the status URL and maps the response body's 'status' field to a Status subclass using get_status. Raises ValueError for unknown status strings and HiggsfieldClientError for HTTP errors. ```python def status(self) -> Status: response = self._transport.request('GET', self.status_url) return get_status(response.json()) ``` -------------------------------- ### NoRetry for one-shot fail-fast calls Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/retry.md For one-shot calls that must fail fast, NoRetry() skips the delay loop entirely. This example creates an HttpTransport with NoRetry and makes a GET request. ```python from higgsfield_client.http.retry import NoRetry transport = HttpTransport(client, NoRetry()) response = transport.request('GET', 'https://api.higgsfield.ai/requests/abc/status') ``` -------------------------------- ### Run Agent API session with SyncClient Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/README.md Run a multi-step creative task in a persistent session using `SyncClient`. Creates a session, runs a prompt with an `on_question` callback, prints status/text/asset URLs, and uploads media for a follow-up run. Requires Agent API access and sufficient credits. `run()` polls with backoff from 2 to 10 seconds; without a callback, an agent question returns `awaiting_input`. Defaults to a 30-minute wait limit, configurable with `timeout`. Errors include `SessionBusyError` (409), `AgentAccessDeniedError` (403), `InsufficientCreditsError` (402), and `AgentBackendError` (5xx). ```python from higgsfield_client import SyncClient # Uses HF_KEY or HF_API_KEY + HF_API_SECRET. client = SyncClient() session = client.agents.sessions.create() result = client.agents.sessions.run( session.session_id, "Generate an image of an alpine lake at sunrise. Reply with the image URL.", on_question=lambda question: "Photorealistic style.", ) print(result.status) # completed | failed | awaiting_input print(result.text) print(result.asset_urls) with open("photo.jpeg", "rb") as file: url = client.agents.media.upload(file.read(), extension="jpeg", type="image") client.agents.sessions.run(session.session_id, f"Animate this image: {url}") ``` -------------------------------- ### Run a turn with question handler Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Runs a turn with a question handler that answers agent questions. Prints the result status, text, and asset URLs. ```python result = client.agents.sessions.run( session.session_id, "Generate an image of an alpine lake at sunrise. Reply with the image URL.", on_question=lambda question: "Photorealistic style.", ) print(result.status) # completed | failed | awaiting_input print(result.text) # agent's answer text print(result.asset_urls) # URLs of generated assets ``` -------------------------------- ### poll_request_status() usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/request-controllers.md Example of iterating over the poll_request_status generator with a custom delay of 2.0 seconds, printing the class name of each yielded status. ```python for status in controller.poll_request_status(delay=2.0): print(type(status).__name__) ``` -------------------------------- ### Media class constructor Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Initializes the Media class with an authenticated HTTP client, an unauthenticated upload client, and the base URL. The upload client is used for presigned uploads and is not authenticated. ```python class Media: def __init__( self, client: httpx.Client, upload_client: httpx.Client, base_url: str ) -> None: ``` -------------------------------- ### Sessions.create method Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Creates a new agent session by POSTing `{config: {}}` to `/v1/agent/sessions`. Returns an `AgentSession` with the server-assigned `session_id` and initial `SessionStatus`. ```python def create(self, config: Optional[Dict[str, Any]] = None) -> AgentSession: resp = self._client.post(self._url("/sessions"), json={"config": config or {}}) raise_for_agent_status(resp) data = resp.json() return AgentSession( session_id=data["session_id"], status=SessionStatus(data["status"]) ) ``` -------------------------------- ### Simple Submit and Wait with subscribe and subscribe_async Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/README.md Synchronous and asynchronous versions of the simple submit-and-wait pattern using higgsfield_client.subscribe and subscribe_async. Both call the 'bytedance/seedream/v4/text-to-image' model with the same arguments and print the first image URL from the result. ```python import higgsfield_client result = higgsfield_client.subscribe( 'bytedance/seedream/v4/text-to-image', arguments={ 'prompt': 'A serene lake at sunset with mountains', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False } ) print(result['images'][0]['url']) ``` ```python import asyncio import higgsfield_client async def main(): result = await higgsfield_client.subscribe_async( 'bytedance/seedream/v4/text-to-image', arguments={ 'prompt': 'A serene lake at sunset with mountains', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False } ) print(result['images'][0]['url']) asyncio.run(main()) ``` -------------------------------- ### Run a complete agent session with SyncClient Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Creates a session, runs a prompt with an on_question callback, prints the result, sends a follow-up message, reads messages after a given ID, and interrupts the session. Requires the higgsfield_client package and handles AgentTimeoutError. ```python from higgsfield_client import SyncClient, AgentTimeoutError client = SyncClient() session = client.agents.sessions.create() result = client.agents.sessions.run( session.session_id, "Generate an image of a quiet alpine lake at sunrise, editorial photography, 4:3. Reply with the image URL.", on_question=lambda question: "Photorealistic style.", ) print(result.status, result.text, result.asset_urls) # manual control message_id = client.agents.sessions.send(session.session_id, "Now animate that scene.") state = client.agents.sessions.messages(session.session_id, after=message_id) print(state.status, [m.role for m in state.messages]) client.agents.sessions.interrupt(session.session_id) ``` -------------------------------- ### Logger setup for transports Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/transport.md Logger used by both transports to log retry decisions at DEBUG level. ```python logger = logging.getLogger(__name__) ``` -------------------------------- ### status(request_id) Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/package.md Gets the current status of a request by ID. This is a synchronous function that delegates to the module instance sync_client. ```APIDOC ## status(request_id) ### Description Gets the current status of a request by ID. ### Method Function call ### Signature `status(request_id: str) -> Status` ### Parameters - **request_id** (str) - Required - The ID of the request to query. ### Returns `Status` - a Status subclass instance (see types.md). ``` -------------------------------- ### subscribe usage with callbacks Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/sync-client.md Shows how to use client.subscribe with on_enqueue and on_queue_update callbacks to track request progress and print the final image URL. ```python def on_enqueue(request_id: str): print(f'enqueued: {request_id}') def on_update(status): print(f'{type(status).__name__}: {status}') result = client.subscribe( 'bytedance/seedream/v4/text-to-image', arguments={'prompt': 'A serene lake at sunset', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False}, on_enqueue=on_enqueue, on_queue_update=on_update, ) print(result['images'][0]['url']) ``` -------------------------------- ### status(request_id: str) -> Status Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/sync-client.md Gets the current status of a request by ID. Returns a Status subclass representing the current state. ```APIDOC ## status(request_id: str) -> Status ### Description Get the current status of a request by ID. ### Method `status` ### Parameters - **request_id** (`str`) - Required - The ID of the request. ### Returns `Status` - A `Status` subclass (`Queued` / `InProgress` / `Completed` / `Failed` / `NSFW` / `Cancelled`). ### Throws `ValueError` if the server returns an unrecognized status string. ``` -------------------------------- ### SyncClient.__init__ Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/sync-client.md Constructor for the synchronous HTTP client. Initializes the client with base URL, timeout, and optional API key. The API key can be provided directly or resolved lazily from environment variables. ```APIDOC ## SyncClient.__init__ ### Description Constructor for the synchronous HTTP client. Initializes the client with base URL, timeout, and optional API key. The API key can be provided directly or resolved lazily from environment variables. ### Method Constructor ### Signature ```python def __init__( self, base_url: str = BASE_URL, timeout: float = DEFAULT_TIMEOUT, api_key: str | None = None, ): ``` ### Parameters - **base_url** (str) - Optional - API host used for all authenticated requests. Default: `'https://api.higgsfield.ai'`. - **timeout** (float) - Optional - Request timeout in seconds (httpx `timeout`). Default: `90.0`. - **api_key** (str | None) - Optional - Credential string `"key-id:key-secret"`. When `None`, resolved lazily from `HF_KEY` or `HF_API_KEY`+`HF_API_SECRET` via `get_credential_key()`. ### Notes The constructor only stores the three values. Clients, transports, and the agents namespace are built lazily by `cached_property`s on first access: - `_client: httpx.Client` — authenticated client. Headers: `Authorization: Key {api_key}`, `Content-Type: application/json`, `User-Agent: higgsfield-client-py/1.0`; `base_url` and `timeout` from the constructor. - `_upload_client: httpx.Client` — unauthenticated client (for presigned upload URLs); `timeout` only. - `_transport: HttpTransport` — wraps `_client` with `create_default_retry_strategy()` (exponential backoff). - `agents: AgentsResource` — Agent API namespace. If no credentials are found when `_client` is first built, `CredentialsMissedError` is raised. ``` -------------------------------- ### GET {base_url}/v1/agent/sessions/{session_id}/messages Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/endpoints.md Fetches messages from an agent session. This endpoint is called via the `Sessions.messages` method. ```APIDOC ## [GET] {base_url}/v1/agent/sessions/{session_id}/messages ### Description Fetches messages from an agent session. This endpoint is called via the `Sessions.messages` method. ### Method GET ### Endpoint {base_url}/v1/agent/sessions/{session_id}/messages ### Parameters #### Path Parameters - **session_id** (string) - Required - The ID of the session. #### Query Parameters - **after** (string) - Optional - Return only messages with id greater than this. ### Response #### Success Response (2xx) - **status** (string) - Session status; missing defaults to `'idle'` - **messages** (array) - Transcript slice; each row has `message_id` (str), `role` (str), `status` (str), `message` (object), `created_at` (str), optional `llm_cost_usd` (str) ``` -------------------------------- ### Async uploads with higgsfield_client Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/README.md Async versions of all upload methods: `upload_async`, `upload_file_async`, and `upload_image_async`. Each returns a URL and must be awaited. ```python import higgsfield_client # Async raw data upload url = await higgsfield_client.upload_async(data, content_type='image/jpeg') # Async file upload url = await higgsfield_client.upload_file_async('path/to/example.jpeg') # Async image upload url = await higgsfield_client.upload_image_async(image, format='jpeg') ``` -------------------------------- ### Example usage of HTTP error helpers Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/http-error.md Shows how to use extract_error_message and raise_for_status with an httpx response. The original httpx.HTTPStatusError is available as __cause__ on the raised HiggsfieldClientError. ```python import httpx from higgsfield_client.http.error import raise_for_status, extract_error_message from higgsfield_client import HiggsfieldClientError response = httpx.get('https://api.higgsfield.ai/requests/unknown/status') print(extract_error_message(response)) # 'detail' | 'details' | 'message' | 'error' | raw text try: raise_for_status(response) except HiggsfieldClientError as exc: # str(exc) is the server-provided message; the original httpx.HTTPStatusError is __cause__ print(f'HTTP error: {exc}') print(f'status code: {exc.__cause__.response.status_code}') ``` -------------------------------- ### Import SyncClient Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/sync-client.md Shows two equivalent import paths for the SyncClient class. Use the first for the public API, the second for direct module access. ```python from higgsfield_client import SyncClient # or from higgsfield_client.http.client import SyncClient ``` -------------------------------- ### Typical end-user client usage Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/auth.md Shows how credentials are resolved implicitly from the environment when creating a SyncClient, or passed explicitly to skip auth resolution. ```python from higgsfield_client import SyncClient client = SyncClient() # uses HF_KEY or HF_API_KEY + HF_API_SECRET client2 = SyncClient(api_key='key-id:key-secret') # explicit; env never consulted ``` -------------------------------- ### Async polling and result retrieval Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/request-controllers.md Shows how to iterate over poll_request_status() as an async generator and await get() to retrieve the result. The status type name is printed for each poll. ```python async for status in controller.poll_request_status(): print(type(status).__name__) result = await controller.get() print(result['images'][0]['url']) ``` -------------------------------- ### AsyncRequestController class definition Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/request-controllers.md Defines the async request controller with the same constructor shape as the sync controller. Methods must be awaited: cancel(), status(), poll_request_status(), and get(). ```python class AsyncRequestController(RequestController): def __init__( self, request_id: str, transport: AsyncHttpTransport, response_url: Optional[str] = None, status_url: Optional[str] = None, cancel_url: Optional[str] = None, ) -> None: ``` -------------------------------- ### Import AgentsResource, Sessions, Media Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Import the sync Agent API resource classes from the higgsfield_client package. ```python from higgsfield_client.agents.resources import AgentsResource, Sessions, Media ``` -------------------------------- ### GET /requests/{request_id}/status Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/endpoints.md Polls the status of a request. Returns a JSON object with a status field that maps to enum values. Terminal statuses end polling. ```APIDOC ## GET /requests/{request_id}/status ### Description Polls the status of a request. Returns a JSON object with a status field that maps to enum values. Terminal statuses end polling. ### Method GET ### Endpoint `{base_url}/requests/{request_id}/status` ### Parameters #### Path Parameters - **request_id** (string) - Required - The ID of the request to poll. ### Response #### Success Response (2xx) - **status** (string) - The current status of the request. Possible values: `queued`, `in_progress`, `completed`, `failed`, `nsfw`, `canceled`. #### Response Example ```json { "status": "completed" } ``` ``` -------------------------------- ### SyncRequestController.status() Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/request-controllers.md Retrieves the current status of the request by GETting the status_url and mapping the body's status field to a Status subclass. Raises ValueError for unknown status strings and HiggsfieldClientError for HTTP errors. ```APIDOC ## SyncRequestController.status() ### Description Retrieves the current status of the request by GETting the status_url and mapping the body's status field to a Status subclass. Raises ValueError for unknown status strings and HiggsfieldClientError for HTTP errors. ### Method GET ### Endpoint status_url ### Response #### Success Response - **Status** - A Status subclass instance #### Error Response - **ValueError** - If status string is unknown - **HiggsfieldClientError** - For HTTP errors ``` -------------------------------- ### SyncRequestController.__init__ Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/request-controllers.md Initializes a SyncRequestController instance with the given request ID, transport, and optional URLs for response, status, and cancellation. ```APIDOC ## SyncRequestController.__init__ ### Description Initializes a SyncRequestController instance with the given request ID, transport, and optional URLs for response, status, and cancellation. ### Method Constructor ### Parameters - **request_id** (str) - Required - Request ID - **transport** (HttpTransport) - Required - Transport used for all HTTP calls - **response_url** (str | None) - Optional - Result payload URL (default: built) - **status_url** (str | None) - Optional - Status polling URL (default: built) - **cancel_url** (str | None) - Optional - Cancel URL (default: built) ### Request Example ```python controller = SyncRequestController( request_id="...", transport=transport, response_url="...", status_url="...", cancel_url="..." ) ``` ``` -------------------------------- ### Submit with Callbacks using on_enqueue and on_queue_update Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/README.md Synchronous and asynchronous versions of the submit-with-callbacks pattern using higgsfield_client.subscribe and subscribe_async. Both define on_enqueue and on_status_update callbacks and pass them via the on_enqueue and on_queue_update parameters to handle status updates. ```python import higgsfield_client def on_enqueue(request_id): print(f'Request {request_id} was enqueued') def on_status_update(status): print(f'Status: {status}') result = higgsfield_client.subscribe( 'bytedance/seedream/v4/text-to-image', arguments={ 'prompt': 'A serene lake at sunset with mountains', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False }, on_enqueue=on_enqueue, on_queue_update=on_status_update ) ``` ```python import asyncio import higgsfield_client def on_enqueue(request_id): print(f'Request {request_id} was enqueued') def on_status_update(status): print(f'Status: {status}') async def main(): await higgsfield_client.subscribe_async( 'bytedance/seedream/v4/text-to-image', arguments={ 'prompt': 'A serene lake at sunset with mountains', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False }, on_enqueue=on_enqueue, on_queue_update=on_status_update ) asyncio.run(main()) ``` -------------------------------- ### GET /v1/agent/sessions/{session_id}/messages Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-agents.md Retrieves the transcript of messages for a session, optionally filtered by a lower bound message ID. Returns the session state including status and messages. ```APIDOC ## GET /v1/agent/sessions/{session_id}/messages ### Description Retrieves the transcript of messages for a session, optionally filtered by a lower bound message ID. Returns the session state including status and messages. ### Method GET ### Endpoint /v1/agent/sessions/{session_id}/messages ### Parameters #### Path Parameters - **session_id** (str) - Required - The ID of the session. #### Query Parameters - **after** (str | None) - Optional - Message ID lower bound for the transcript slice. ### Response #### Success Response (200) - **status** (SessionStatus) - The current status of the session. - **messages** (list) - The list of messages in the transcript. #### Response Example ```json { "status": "string", "messages": [] } ``` ``` -------------------------------- ### Sessions class constructor Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Defines the Sessions class with an HTTP client and base URL. All URLs are built as `{base_url}/v1/agent{path}`. ```python class Sessions: def __init__(self, client: httpx.Client, base_url: str) -> None: ``` -------------------------------- ### LinearRetry usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/retry.md Shows how to instantiate LinearRetry with custom parameters and verify should_retry behavior. With max_retries=2, delay=5.0, should_retry(1, 503) returns True, but should_retry(2, 503) returns False because attempt >= max_retries. ```python strategy = LinearRetry(max_retries=2, delay=5.0) assert strategy.should_retry(1, 503) is True assert strategy.should_retry(2, 503) is False # attempt >= max_retries ``` -------------------------------- ### AsyncClient.__init__ Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-client.md Constructor for the AsyncClient class. Initializes an asynchronous HTTP client with configurable base URL, timeout, and API key. ```APIDOC ## [CONSTRUCTOR] AsyncClient.__init__ ### Description Initializes an AsyncClient instance with the given base URL, timeout, and API key. This is the asynchronous counterpart of SyncClient, built on httpx.AsyncClient. ### Method Constructor ### Endpoint AsyncClient.__init__ ### Parameters - **base_url** (str) - Optional - API host, default is 'https://api.higgsfield.ai' - **timeout** (float) - Optional - Request timeout in seconds, default is 90.0 - **api_key** (str | None) - Optional - Credential in format "key-id:key-secret"; if not provided, resolved from environment lazily ### Request Example ```python client = AsyncClient( base_url='https://api.higgsfield.ai', timeout=90.0, api_key='key-id:key-secret' ) ``` ### Response #### Success Response - Returns an AsyncClient instance #### Response Example ```python client = AsyncClient() ``` ``` -------------------------------- ### async upload_file(path: os.PathLike) -> str Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-client.md Uploads a local file; MIME guessed via `mimetypes` (fallback `application/octet-stream`). ```APIDOC ## async upload_file(path: os.PathLike) -> str ### Description Uploads a local file; MIME guessed via `mimetypes` (fallback `application/octet-stream`). ### Method Async method ### Parameters - **path** (os.PathLike) - Required - Path to the local file. ### Returns `str` — the public URL. ### Request Example ```python url = await client.upload_file('path/to/example.jpeg') ``` ``` -------------------------------- ### ExponentialBackoffRetry usage example Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/retry.md Shows how to instantiate ExponentialBackoffRetry with custom parameters and verify should_retry and get_delay behavior. With max_retries=5, initial_delay=1.0, max_delay=30.0, should_retry(1, 429) returns True and get_delay(3) returns 4.0 (1.0 * 2^(3-1)). ```python strategy = ExponentialBackoffRetry(max_retries=5, initial_delay=1.0, max_delay=30.0) assert strategy.should_retry(1, 429) is True assert strategy.get_delay(3) == 4.0 # 1.0 * 2^(3-1) ``` -------------------------------- ### run(session_id: str, content: str, on_question: Optional[QuestionHandler] = None, timeout: float = 1800.0) -> TurnResult Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Sends a message and polls for the turn to complete, handling agent questions if a handler is provided. Returns a TurnResult with the final status, text, and asset URLs. ```APIDOC ## POST /v1/agent/sessions/{session_id}/messages (with polling) ### Description Sends a user message and then polls the session until the turn reaches a terminal state. If the agent asks a question and an `on_question` handler is provided, the answer is sent and polling continues. Returns a TurnResult with the final status, text, and asset URLs. ### Method POST (send) + GET (poll) ### Endpoint /v1/agent/sessions/{session_id}/messages ### Parameters #### Path Parameters - **session_id** (string) - Required - Session ID #### Request Body - **content** (string) - Required - User message for the turn #### Additional Parameters (SDK method) - **on_question** (Callable[[str], str] | None) - Optional - Handles agent questions; receives question text, returns the answer - **timeout** (float) - Optional - Wall-clock limit in seconds for the local wait (default 1800.0) ### Request Example { "content": "Generate an image of an alpine lake at sunrise. Reply with the image URL." } ### Response #### Success Response (200) - **status** (string) - One of: completed, failed, awaiting_input - **text** (string) - Agent's answer text - **asset_urls** (array) - URLs of generated assets #### Response Example { "status": "completed", "text": "Here is your image: https://...", "asset_urls": ["https://..."] } ### Error Handling - **AgentTimeoutError** - Turn did not reach a terminal state within timeout; server-side turn keeps running - **SessionBusyError** (409) - Another turn is running on this session ``` -------------------------------- ### create(config: Optional[Dict[str, Any]] = None) -> AgentSession Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/agents.md Creates a new agent session by POSTing a configuration to the /v1/agent/sessions endpoint. Returns an AgentSession object containing the server-assigned session ID and initial status. ```APIDOC ## POST /v1/agent/sessions ### Description Creates a new agent session with an optional configuration dictionary. The server assigns a session ID and returns the initial session status. ### Method POST ### Endpoint /v1/agent/sessions ### Parameters #### Request Body - **config** (Dict[str, Any] | None) - Optional - Session configuration dictionary (also used to resume an existing session). Defaults to {}. ### Request Example { "config": {} } ### Response #### Success Response (200) - **session_id** (string) - Server-assigned session ID - **status** (string) - Initial session status #### Response Example { "session_id": "abc123", "status": "created" } ``` -------------------------------- ### Submit and Track Progress with submit and submit_async Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/README.md Synchronous and asynchronous versions of the submit-and-track-progress pattern using higgsfield_client.submit and submit_async. Both use a request controller to poll status (Queued, InProgress, Completed, Failed, NSFW, Cancelled) and then fetch the result. The webhook_url parameter is optional and calls the provided URL on completion. ```python import higgsfield_client request_controller = higgsfield_client.submit( 'bytedance/seedream/v4/text-to-image', arguments={ 'prompt': 'Football ball', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False }, webhook_url='https://example.com/webhook' # Optional parameter which calls your webhook on completion ) for status in request_controller.poll_request_status(): if isinstance(status, higgsfield_client.Queued): print('Queued') elif isinstance(status, higgsfield_client.InProgress): print('In progress') elif isinstance(status, higgsfield_client.Completed): print('Completed') elif isinstance(status, (higgsfield_client.Failed, higgsfield_client.NSFW, higgsfield_client.Cancelled)): print('Oops!') result = request_controller.get() print(result['images'][0]['url']) ``` ```python import asyncio import higgsfield_client async def main(): request_controller = await higgsfield_client.submit_async( 'bytedance/seedream/v4/text-to-image', arguments={ 'prompt': 'Football ball', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False }, webhook_url='https://example.com/webhook' # Optional parameter which calls your webhook on completion ) async for status in request_controller.poll_request_status(): if isinstance(status, higgsfield_client.Queued): print('Queued') elif isinstance(status, higgsfield_client.InProgress): print('In progress') elif isinstance(status, higgsfield_client.Completed): print('Completed') elif isinstance(status, (higgsfield_client.Failed, higgsfield_client.NSFW, higgsfield_client.Cancelled)): print('Oops!') result = await request_controller.get() print(result['images'][0]['url']) asyncio.run(main()) ``` -------------------------------- ### RequestController.__init__ Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/request-controllers.md Initializes a RequestController instance with the request ID and optional URLs for response, status, and cancel endpoints. The request_id is required, while the URLs default to values built from BASE_URL. ```APIDOC ## RequestController.__init__ ### Description Initializes a RequestController instance with the request ID and optional URLs for response, status, and cancel endpoints. ### Method Constructor ### Signature ```python def __init__( self, request_id: str, response_url: Optional[str] = None, status_url: Optional[str] = None, cancel_url: Optional[str] = None, ) -> None: ``` ### Parameters - **request_id** (str) - Required - Unique request identifier (server-assigned) - **response_url** (str | None) - Optional - Endpoint returning the final result payload. Default: URL built from BASE_URL. - **status_url** (str | None) - Optional - Endpoint returning the current status. Default: URL built from BASE_URL. - **cancel_url** (str | None) - Optional - Endpoint to cancel the request. Default: URL built from BASE_URL. ### Returns None ``` -------------------------------- ### Full async session workflow with AsyncClient Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/async-client.md Shows a complete async workflow: submit a text-to-image request, poll status, fetch the result, and handle errors. Uses AsyncClient, AsyncRequestController, and HiggsfieldClientError. Requires Python 3.7+ with asyncio support. The controller.poll_request_status() yields status objects whose class names are printed; get() returns a dict with 'images' containing a URL. Errors are caught and printed as 'failed: ...'. ```python import asyncio from higgsfield_client import AsyncClient, HiggsfieldClientError async def main(): client = AsyncClient() controller = await client.submit( 'bytedance/seedream/v4/text-to-image', arguments={'prompt': 'Football ball', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False}, ) try: async for status in controller.poll_request_status(): print(type(status).__name__) result = await controller.get() print(result['images'][0]['url']) except HiggsfieldClientError as exc: print(f'failed: {exc}') asyncio.run(main()) ``` -------------------------------- ### Set HF_API_KEY and HF_API_SECRET environment variables Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/README.md Sets separate environment variables for the API key and secret as an alternative authentication method. ```bash export HF_API_KEY="your-api-key" export HF_API_SECRET="your-api-secret" ``` -------------------------------- ### submit usage and error handling Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/sync-client.md Shows how to call client.submit with a text-to-image application, print the request ID, and handle HiggsfieldClientError for non-retryable HTTP errors. ```python controller = client.submit( 'bytedance/seedream/v4/text-to-image', arguments={'prompt': 'A football ball on grass', 'resolution': '2K', 'aspect_ratio': '16:9', 'camera_fixed': False}, webhook_url='https://example.com/hooks/generation', ) print(controller.request_id) # error handling from higgsfield_client import HiggsfieldClientError try: client.submit('unknown/app', arguments={}) except HiggsfieldClientError as exc: print(f'submit failed: {exc}') ``` -------------------------------- ### Import get_status and get_url from higgsfield_client.utils Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/utils.md Import the internal helper functions get_status and get_url from the higgsfield_client.utils module. ```python from higgsfield_client.utils import get_status, get_url ``` -------------------------------- ### upload_file(path: os.PathLike) -> str Source: https://github.com/higgsfield-ai/higgsfield-client/blob/main/_autodocs/api-reference/sync-client.md Reads a local file as bytes and uploads it via the `upload` method, returning the public URL. The MIME type is guessed from the file extension using `mimetypes.guess_type`, defaulting to `application/octet-stream` if unknown. ```APIDOC ## upload_file(path: os.PathLike) -> str ### Description Reads a local file as bytes and uploads it via the `upload` method, returning the public URL. The MIME type is guessed from the file extension using `mimetypes.guess_type`, defaulting to `application/octet-stream` if unknown. ### Method PUT ### Endpoint Presigned URL returned by `_get_upload_url` ### Parameters #### Path Parameters - **path** (os.PathLike) - Required - Local path (e.g. `str` or `pathlib.Path`) ### Request Example ```python url = client.upload_file('path/to/example.jpeg') ``` ### Response #### Success Response (200) - **public_url** (str) - The public URL where the file is accessible. #### Response Example ```python url = client.upload_file('path/to/example.jpeg') ``` ```