Skip to main content

Automio.ai Python Client - API Documentation

A Python client for Automio.ai API that enables seamless integration with various APIs and services.

For development documentation (versioning, publishing, etc.), see README.dev.md

Installation

pip install automio

Quick Start

Structured errors (optional)

Available from Python SDK 0.5.9.

SDK-owned exceptions now also inherit from AutomioError and expose error_info, message (a stable technical summary), and metadata. Existing exception classes, str(error), args, HTTP statuses, return values, and automatic retry behavior are unchanged. Existing applications need no edits. get_error_info(error) also provides a generic diagnostic for exceptions that remain unwrapped, such as requests.ConnectionError and built-in timeouts.

from automio import AutomioError, get_error_info

try:
    integration = api.integrations.get_integration("example")
except AutomioError as error:
    info = error.error_info
    print(info.code, info.message, info.metadata)
    # Branch on codes, not translated detail or str(error).
    if info.code == "integration_account_required":
        print("Connect an account before continuing.")
    else:
        raise

ErrorInfo contains code, message, JSON metadata, detail, status_code, request_id, retryable, next_action, source, and a tuple of child errors. to_dict() returns JSON-serializable diagnostics. detail preserves variable/legacy/provider text; it is not a stable log title. Old servers remain supported: missing fields get conservative defaults, with retryable=False. That flag never triggers retries; writes with an uncertain outcome must not be replayed solely because a failure is transient.

Integration provider failures still return (data, response) by default:

data, response = api.integrations.call(integration, method="GET", endpoint="/items")
if response is not None and response.error_info is not None:
    info = response.error_info
    for item in info.errors:  # e.g. Allegro errors[].code / metadata
        print(item.code, item.metadata)

# Optional: explicitly switch this call site to exception handling.
if response is not None:
    response.raise_for_error()

raise_for_error() raises automio.wrapper.IntegrationResponseError (an AutomioError) and retains the original object in .response. It also detects business_ok=False. Parallel results expose the same methods, including item failures without api_response; successful results have error_info=None. GraphQL exceptions preserve their original args[1] and additionally expose all per-error diagnostics under error_info.errors, including extensions. AI SSE events are unchanged; inspect an error event with ErrorInfo.from_payload(event["data"]) instead of parsing its text.

For structured logs, use info.message as the title and explicitly select context fields. Do not log str(error) or the entire to_dict() if you want to exclude legacy messages, response bodies, and provider text. Metadata can contain application data; it is not automatically safe for public display. For Sentry, an explicit fingerprint based on a known domain code can group failures across application IDs. Keep IDs in context, not the fingerprint. Do not group all api_error, provider_error, or unexpected_error events together: retain default stack-based grouping for unclassified failures. The SDK does not initialize Sentry or send telemetry. Hosted runtime transport and its Sentry filtering are not changed by this SDK feature.

Environment Variables

Copy .env.example to .env in your project root and adjust it for local configuration:

# Cache Service (when available)
CACHE_SERVICE_URL=https://code-cache.automio.ai
CACHE_SERVICE_TOKEN=your_cache_token

# Redis Configuration (for local development)
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0
REDIS_PASSWORD=optional_password
ORGANIZATION_ID=optional_local_org_id

# Automio.ai API Configuration
API_BASE_URL=https://automio.ai
# Main Swagger endpoints use paths without /api/.
PUBLIC_API_BASE_URL=https://api.automio.ai
APP_TOKEN=your_api_token
APP_ID=your_app_id
ACTION_ID=optional_runtime_action_id

# Optional outbound proxy (standard Python proxy variables)
HTTPS_PROXY=http://proxy.internal:3128
NO_PROXY=localhost,127.0.0.1

# Task Management
TASK_ID=optional_custom_task_id

Usage Example

from automio.wrapper import API

api = API()

The generated Automio.ai API client honors HTTP_PROXY, HTTPS_PROXY, and NO_PROXY. An explicit Configuration.proxy value takes precedence; set it to an empty string to disable environment proxy discovery for that client.

Request retries

API() defaults to retry_requests=True. The integration wrapper makes up to four attempts: the initial request and retries after 15, 60 and 300 seconds for upstream 401/403, 5xx, connection disconnects and selected protocol errors. Platform authorization errors are excluded; not every timeout or HTTP error is retried. This policy also applies to writes, multipart uploads and raw_body binary PUT uploads. The provider may accept a write before the response is lost; SDK retries can repeat it before application code receives a result.

The generated Automio.ai API transport also makes at most two connection retries. This policy applies to every HTTP method, including GraphQL POST, but only to failures reported before the request is sent. It does not retry read timeouts, HTTP responses, or other ambiguous failures that could duplicate a mutation. The final connection retry is delayed by approximately 200-250 milliseconds.

Disable wrapper-level retries for writes without a verified safe replay contract, and when diagnostics need the first response:

from automio.wrapper import API

api = API(retry_requests=False)

This constructor option applies to that client instance; it is not a per-call integrations.call() argument. After an ambiguous failure, reconcile the provider's operation or accepted upload range before retrying. Disabling SDK retries does not undo accepted writes or disable backend OAuth refresh/retry behavior.

Although the SDK retains Idempotency-Key across retries, ordinary HTTP integration calls do not use it for backend deduplication or automatically forward it as a provider idempotency header. Durable backend replay protection is documented for SOAP operations. For HTTP writes, verify the provider's replay contract instead of relying on this key, the PUT method or retryable=True alone.

Actions

Stop a running action

Call api.actions.stop(run_id) only for an explicit stop request, using the run_id returned by run(), not task_id or the action slug. This is available in the JavaScript and Python SDK source builds containing this feature; older published packages do not have it. Deploy the matching backend, browser bundle, CLI and worker image before using it.

The response is {run_id, status, confirmed}. HTTP 202 / confirmed: false means the request is pending, not that execution has stopped. Keep observing the same run until stopped, completed, or failed. confirmed: true means terminal; inspect status because completion may have won the race. Repeated stop requests for the same run are safe and leave terminal outcomes unchanged. A timeout, 404 or disconnected log stream is not proof of cancellation. Preserve the IDs, check status, and optionally retry stop for that run; never restart it. Stopping does not undo database writes or external requests already performed. This stops individual action runs, not an entire cron schedule or trigger worker.

# result was returned by api.actions.run(...)
ack = api.actions.stop(result.run_id)
final_status = api.actions.wait_for_run(result.run_id, timeout=600)
print(final_status.status)  # stopped, completed, or failed

stop(run_id, *, timeout=30) returns a dictionary; read ack["confirmed"] and ack["status"]. The timeout bounds this HTTP request, not execution shutdown.

Run an action

from automio.wrapper import API

api = API()

result = api.actions.run(
    action_slug="my-action-slug",
    user_input={  # optional
        "date_from": "2026-01-01",
        "date_to": "2026-01-31",
    },
)

print(result.run_id, result.task_id, result.run_number)

Method signature:

api.actions.run(
    action_slug: str | int | None = None,
    selected_rows: list[str] | None = None,
    selected_all: bool | None = None,
    filter_params: dict | None = None,
    user_input: dict | None = None,
    connection_id: str | None = None,
    language: str | None = None,
)

user_input is optional, but important and frequently used for runtime parameters from the action form (USER_INPUT in action code).

Wait for the persisted run status independently from optional streamed logs:

final_status = api.actions.wait_for_run(
    result.run_id,
    timeout=600,
    poll_interval=1,
)

poll_interval defaults to one second and cannot be set below 1.

The helper resolves for completed, failed, or stopped. Transient network, 408/429 and temporary 5xx errors retry until timeout, with exponential backoff capped at 30 seconds and respect for Retry-After. An explicit max_consecutive_errors still limits consecutive failures. Permanent HTTP and malformed-status errors raise ActionRunObservationError with run_id, code, stage and the original cause. Deadline expiry remains a TimeoutError.

run() generates an Idempotency-Key per explicit call. Persist api.actions.new_request_key() before calling run(slug, request_key=key, ...) when start recovery is required. The same key and inputs return the same run without another charge; changed inputs return 409. recover_run(slug, key) retrieves existing IDs using GET only. A 404 can mean the start is still in flight. Start exceptions retain their original type and gain request_key, action_slug and stage. No automatic POST replay is added. Calls without an explicit key remain distinct starts. A retained key for deleted history returns 410 rather than starting again. Keys are scoped to app, organization, user and action; never reuse them for a new intended execution.

Files

Upload an application file

from pathlib import Path
from automio.wrapper import API

api = API()

result = api.files.upload(
    file=Path("report.txt"),
    path="exports/report.txt",
    overwrite=True,
)

print(result.public_url)
print(result.object_key)

Method signature:

api.files.upload(
    file: bytes | bytearray | str | os.PathLike | tuple[str, bytes],
    path: str | None = None,
    overwrite: bool = False,
    app_id: int | str | None = None,
    organization_id: int | str | None = None,
    is_public: bool | None = None,
    preserve_filename: bool | None = None,
)

Notes:

  • New files are private by default. public_url then contains a signed download URL, valid for 300 seconds by default. Resolve metadata again to obtain a fresh URL.
  • Use is_public=True for intentionally public files such as marketplace images. Overwrite preserves existing visibility when is_public is omitted; pass False to make the overwritten object private.
  • If app_id is omitted, the wrapper uses APP_ID from the environment.
  • Passing Path("local-file.txt") is supported and will upload that local file.
  • path is the deterministic logical path used to derive the final S3 object key.
  • Re-uploading the same app_id + organization context + path requires overwrite=True.
  • organization_id enables delegated upload in app_action context — see Delegated file upload in app_action.

Exact filenames for verification files

Both upload and upload_from_url accept preserve_filename (True in Python, true in JavaScript/JSON). Normally path is a logical identifier and the final filename in S3 is replaced by an HMAC hash. With this option enabled, the backend keeps the exact relative path, filename and extension case under apps/<app_id>/orgs/<organization_id>/. If path is omitted, the uploaded filename (or the filename derived from the source URL) is validated instead.

  • The filename without its final extension must have at least 38 characters. Directory names do not count. For name.tar.gz, only .gz is excluded.
  • The filename including extension must fit in 255 UTF-8 bytes, the relative path in 500 characters, and the full S3 key in 1024 UTF-8 bytes.
  • Use a relative POSIX path. Empty, . and .. segments, backslashes, control characters and surrounding whitespace are rejected. Names are never silently shortened, padded or normalized; invalid requests return HTTP 400.
  • Omitted/null: new files use hashed names; overwrites keep the existing naming mode and URL. Explicit false selects hashing. Switching an existing file's naming mode returns HTTP 400; use a new logical path instead.
  • Replacing the same logical file requires overwrite=true. A collision with another file or an untracked S3 object returns HTTP 409 even with overwrite.
  • This option does not make a file public. Add is_public=true for a public verification URL. A minimum length is not a guarantee of an unguessable name. Continue using the logical path for metadata, downloads and deletion.
result = api.files.upload(
    ("verification.txt", b"verification-content"),
    path="tiktok-photo-transfers/tiktok-verification-0123456789abcdef0123456789abcdef.txt",
    preserve_filename=True,
    is_public=True,
)
print(result.public_url)

Upload an application file from URL

from automio.wrapper import API

api = API()

result = api.files.upload_from_url(
    url="https://example.com/reports/report.txt",
    path="imports/report.txt",
    overwrite=True,
)

print(result.public_url)
print(result.object_key)

Method signature:

api.files.upload_from_url(
    url: str,
    path: str | None = None,
    overwrite: bool = False,
    app_id: int | str | None = None,
    organization_id: int | str | None = None,
    is_public: bool | None = None,
    preserve_filename: bool | None = None,
)

Notes:

  • New files are private by default. public_url then contains a signed download URL, valid for 300 seconds by default. Resolve metadata again to obtain a fresh URL.
  • Use is_public=True for intentionally public files such as marketplace images. Overwrite preserves existing visibility when is_public is omitted; pass False to make the overwritten object private.
  • If app_id is omitted, the wrapper uses APP_ID from the environment.
  • path works the same as in files.upload(...).
  • If path is omitted, the backend derives the file name from the URL path, ignoring query params.
  • The backend downloads the remote file first and only uploads to S3 after a successful full download.
  • organization_id enables delegated upload in app_action context — see Delegated file upload in app_action.

Resolve a file URL

from automio.wrapper import API

api = API()

result = api.files.get_metadata("exports/report.txt")
print(result.public_url)

Method signature:

api.files.get_metadata(
    path: str,
    app_id: int | str | None = None,
    organization_id: int | str | None = None,
)

Download stored file bytes

Application storage URLs returned by api.files.* use one automatically allowlisted shared S3 hostname. Application and organization isolation is enforced by the backend for every file operation. Private download URLs are short-lived bearer links; store a logical path or file reference and resolve fresh metadata when downloading. You can download one with a normal HTTP client:

import requests

from automio.wrapper import API

api = API()

metadata = api.files.get_metadata("exports/report.txt")
response = requests.get(metadata.public_url, timeout=(10, 30))
response.raise_for_status()
content = response.content

print(len(content))

Only exact storage hostnames generated for existing Automio.ai applications are allowed. The shared S3 provider domain and arbitrary buckets are not allowlisted.

Alternatively, use the authenticated Automio.ai API to validate the file against the current application and organization before returning its bytes:

content = api.files.download_binary(metadata.public_url)

Method signature:

api.files.download_binary(
    public_url: str,
    app_id: int | str | None = None,
    organization_id: int | str | None = None,
    timeout: float | tuple[float, float] | None = None,
) -> bytes

public_url must be an absolute HTTP(S) URL previously returned for a file in the same application and organization context. The backend verifies the file reference and returns its bytes through the Automio.ai API.

Delete a file

from automio.wrapper import API

api = API()

result = api.files.delete("exports/report.txt")
print(result.detail)
print(result.object_key)

Method signature:

api.files.delete(
    path: str,
    app_id: int | str | None = None,
    organization_id: int | str | None = None,
)

Notes:

  • If app_id is omitted, the wrapper uses APP_ID from the environment.
  • Deletion is scoped by the current backend organization context, the same as upload and download.

Delegated file operations in app_action

In app_action context, you can operate on files on behalf of another organization by passing organization_id. This applies to upload, upload_from_url, get_metadata, download_binary, and delete. The backend validates that:

  • The action exists, is of type app_action, and is public.
  • The calling organization owns both the action and the application.
  • The target organization has an active, authorized App-Token for the application.
  • The target organization has the application activated.
from pathlib import Path
from automio.wrapper import API

api = API()

# Upload on behalf of organization 42
result = api.files.upload(
    file=Path("report.pdf"),
    path="exports/report.pdf",
    overwrite=True,
    organization_id=42,
)
print(result.public_url)

# Upload from URL on behalf of organization 42
result = api.files.upload_from_url(
    url="https://example.com/data.csv",
    path="imports/data.csv",
    overwrite=True,
    organization_id=42,
)
print(result.public_url)

# Resolve file URL on behalf of organization 42
result = api.files.get_metadata("exports/report.pdf", organization_id=42)
print(result.public_url)

# Download file bytes on behalf of organization 42
content = api.files.download_binary(
    result.public_url,
    organization_id=42,
)
print(len(content))

# Delete file on behalf of organization 42
result = api.files.delete("exports/report.pdf", organization_id=42)
print(result.detail)

This pattern is available only in app_action. For user_action, table_action, trigger_action, and webhook_action, organization_id is ignored and file operations are scoped to request.user.organization.

AI Router

All methods are available directly on api.ai. Python uses snake_case; JavaScript uses camelCase.

Operation Python JavaScript
Text / JSON generation generate_text() generateText()
Normalized text stream generate_text_stream() generateTextStream()
Provider-native call call() call()
Provider-native stream call_provider_stream() callProviderStream()
Image analysis analyze_image() analyzeImage()
Image generation (JSON) generate_image() generateImage()
Image generation (binary) generate_image_content() generateImageContent()
Image editing edit_image() editImage()
Image edit stream edit_image_stream() editImageStream()
Video generation generate_video() generateVideo()
Video generation status get_video_generation() getVideoGeneration()
Wait for video generation wait_for_video_generation() waitForVideoGeneration()
Video download download_video() downloadVideo()

Use api.ai for application AI instead of calling provider URLs directly. The router selects the app-specific provider and credential source configured by the organization running the action, injects credentials server-side, records usage, and returns a billing breakdown.

Provider-neutral generation

data, response = api.ai.generate_text(
    model="automio-balanced",
    input="Return the order number and total as JSON.",
    response_schema={
        "type": "object",
        "properties": {
            "order_number": {"type": "string"},
            "total": {"type": "number"},
        },
        "required": ["order_number", "total"],
        "additionalProperties": False,
    },
)

print(data["text"], data.get("json"))
print(response.provider, response.model, response.credential_source)
print(response.billing.ai_usage_credits_charged)
print(response.billing.call_credits_charged)
print(response.billing.total_credits_charged)

generate_text() requires a global platform alias: automio-fast, automio-balanced, or automio-pro. The same action code follows the calling organization's OpenAI, Anthropic, or Gemini application route. Provider-neutral generate_text_stream() uses the same route and aliases. Provider-native call() and call_provider_stream() remain available for advanced provider-specific requests.

Provider-native calls

Use call() for allowlisted provider-native parameters that are not part of the normalized generation API:

data, response = api.ai.call(
    model="your-enabled-model",
    endpoint="/responses",
    request_id="invoice-summary-123",
    payload={
        "input": "Summarize this invoice.",
        "reasoning": {"effort": "medium"},
    },
)

This example applies to an OpenAI-configured route. endpoint and payload must match that route. Use an allowlisted endpoint path, the top-level model argument, and api.ai.call_provider_stream(...) for streaming instead of full URLs, custom authentication headers, payload["model"], or payload["stream"]. Managed routes additionally reject raw provider resource IDs, hosted tools, media, prompt-cache modifiers, and other fields not covered by token billing. Use a connected integration route for supported provider-native fields. request_id is an optional deduplication and correlation key. The first accepted request claims it within the current application; reusing it returns ai_idempotency_conflict (409) and does not replay the response body. After an ambiguous client timeout, check AI Router usage history for that ID before deciding whether to issue a new request ID.

Streaming

for event in api.ai.generate_text_stream(
    model="automio-balanced",
    input="Write a short status update.",
):
    if event["type"] == "text_delta":
        print(event["data"]["text"], end="", flush=True)
    elif event["type"] == "done":
        billing = event.get("metadata", {}).get("billing", {})
        print("\nCredits:", billing.get("total_credits_charged"))
    elif event["type"] == "error":
        print("\nAI error:", event["data"]["detail"])

The iterator yields the same normalized text_delta, usage, done, and error events for OpenAI, Anthropic, and Gemini. The terminal done.data contains complete text, optional parsed JSON, and the finish reason; done.metadata contains final usage and billing.

Use api.ai.call_provider_stream(...) only when you need raw provider events and can supply the configured provider's allowlisted endpoint and native payload.

Image analysis

api.ai.analyze_image() is included from Python SDK 0.5.8 and requires the backend with managed image analysis support.

Analyze an image using platform credentials and Automio credits:

data, response = api.ai.analyze_image(
    image="invoice.png",  # local path, image bytes, or a binary file object
    prompt="Read the invoice number, date and total.",
    model="automio-balanced",
    max_output_tokens=1000,
)
print(data["text"])

This method uses the configured Text route, which must select OpenAI and a supported vision model (including the GPT-5.6 family and GPT-6 Astra). It works with Automio's API credentials or platform Codex authorization; no personal provider account is required. A supplied response_schema returns parsed JSON in data["json"], just like ai.generate_text(). Usage and credit charges are available in response.usage and response.billing.

Accepted images are non-animated PNG, JPEG and WebP, up to 4 MiB and 4096 pixels per side. detail defaults to high; low, auto, and model-supported original are also accepted. The helper sends image bytes, not a remote URL.

For multiple images or streaming, pass OpenAI input_image content parts with base64 data URLs to ai.generate_text() / ai.generate_text_stream(), or the native payload to ai.call() / ai.call_provider_stream(). Managed calls accept at most four images and 8 MiB of decoded image data per request. Chat Completions accepts the native image_url content part with a base64 data URL. Remote image URLs, provider file IDs, documents, audio and video remain unavailable through these managed text methods. Image analysis for other managed providers is not enabled.

The platform validates images and reserves credits for text plus image tokens before the provider call, then settles against reported usage. Large images can require a larger temporary reservation than their final charge.

Image generation and editing

Generate images through the configured route without selecting a provider or provider endpoint:

generated, generation_response = api.ai.generate_image(
    model="automio-image-balanced",
    prompt="Create a clean product hero image.",
    request_id="product-hero-v3",
)

When only one binary image is needed, avoid keeping base64 JSON in memory:

image_bytes, generation_response = api.ai.generate_image_content(
    model="automio-image-balanced",
    prompt="Create a clean product hero image.",
    request_id="product-hero-v4",
)

generate_image_content() supports exactly one image. Use generate_image() when raw b64_json or batch output is explicitly required.

Image calls use the provider and credentials configured in AI Router's Images section, independently of text routing. Generation requires one of automio-image-fast, automio-image-balanced, or automio-image-pro; AI Router resolves that alias to the selected provider model. Direct provider model names are not accepted.

Image edits use a dedicated multipart helper and the normal application route:

data, response = api.ai.edit_image(
    image=["images/product.png", "images/style.webp"],
    mask="images/mask.png",
    prompt="Replace the background while preserving the product.",
    output_format="webp",
    output_compression=85,
    size="1536x1024",
    request_id="product-background-v3",
)

The example includes an image mask, so it requires a regular OpenAI API route, not Codex, even though the model is selected automatically. Gemini routes support image editing with the common image and prompt fields. Binary masks, partial_images, and OpenAI output options are rejected on Gemini. Anthropic does not provide image generation. Gemini image editing currently requires a connected Gemini account, and the total inline request must be smaller than 20 MB.

BytePlus routes require a connected ModelArk API key. Source images may be JPEG, PNG, or WebP (up to 30 MB and 36 megapixels) and edit regions are described in the prompt; masks and OpenAI-only controls are rejected. Fast uses Seedream 4.0, Balanced uses Seedream 5.0 Lite, and Pro uses Seedream 5.0 Pro. Pro returns exactly one image and does not stream. For the other tiers, n > 1 selects a maximum batch size, so the provider may return fewer images.

image accepts a path, bytes, an open binary file, or up to 16 such values in a list/tuple. Use api.ai.edit_image_stream(...) for provider-native image events followed by normalized usage and billing; partial_images=1..3 is OpenAI-only. /images/edits is intentionally unavailable through JSON call().

Video generation

Video generation is asynchronous and uses the application's separate Videos route:

generation, response = api.ai.generate_video(
    model="automio-video-balanced",
    prompt="A paper plane flying above Warsaw at sunrise.",
)
completed = api.ai.wait_for_video_generation(generation["id"], timeout=600)
if completed["status"] == "succeeded":
    video_bytes = api.ai.download_video(completed["id"])

Use api.ai.get_video_generation(id) for one status refresh. Gemini, Kling, and BytePlus are supported through connected provider accounts. The same BytePlus connection can be selected for both Seedream images and Seedance videos. Submission incurs one standard Automio.ai call fee; polling and download do not.

Provider capabilities differ:

Operation OpenAI Anthropic Gemini BytePlus
generate_text, generate_text_stream Yes Yes Yes No
generate_image Yes No Yes, connected account Yes, connected account
edit_image Yes No Yes, connected account Yes, connected account
edit_image_stream Yes No Yes, connected account Fast/Balanced only
Video operation Gemini Kling BytePlus
generate_video, get_video_generation, wait_for_video_generation, download_video Yes Yes Yes
Do not retry capability or endpoint errors by
silently selecting another provider. Fix an invalid operation or endpoint in
application code, or ask the organization owner to select a compatible route.
Codex reports narrower limitations with specific ai_codex_* capability codes.

Billing

  • An Automio.ai-managed key charges the measured provider usage as ai_usage_credits_charged.
  • A connected provider integration keeps the existing standard flat call charge as call_credits_charged for every provider attempt, including a provider error; Automio.ai does not additionally charge its token cost.
  • total_credits_charged is always the sum of those two fields.
  • All credit values are decimal strings. Do not convert them to binary floats for accounting. Non-streaming Router failures and requests rejected before an SSE stream starts raise automio.AIRouterError. After a stream starts, failures arrive as {"type": "error", "data": ...} events. AIRouterError exposes code, detail, hint, retryable, provider, credential_source, request_id, upstream_status, and status_code; route and request metadata can be None when the failure happens before route resolution or usage-record creation. Stable errors include ai_route_not_configured, ai_capability_unavailable, ai_insufficient_credits, and ai_app_budget_exceeded.

Use code and retryable for control flow and request_id for correlation. Do not parse detail. When credential_source == "integration", the organization is using its own connected provider account and detail contains the provider's error message, limited to 4,000 characters. For credential_source == "automio" or "codex_user", detail is a normalized Automio.ai message. Provider response bodies, request payloads, authorization headers, and credentials are never exposed. A provider message may mention request data, so map code to an application-owned message before displaying an error to an end user.

from automio import AIRouterError

try:
    data, response = api.ai.generate_text(
        model="automio-balanced",
        input="Summarize this order.",
    )
except AIRouterError as error:
    print(error.code, error.detail, error.request_id)
    if error.retryable:
        schedule_bounded_retry()
    else:
        handle_permanent_failure(error.code)

Core Methods

GraphQL (Tables API)

Use GraphQLRequest together with api.tables.apps_graphql_query(...) to run queries and mutations against dynamic app tables backed by Hasura or SQLite. Both engines use the same documented mutation shapes and variables; application code does not select a different query for each engine.

  • Queries are scoped by APP_ID and table name (e.g., app_{APP_ID}_orders).
  • Variables are passed via GraphQLRequest(query=..., variables=...).
  • Responses include .data and .errors; always check .errors before using data.
  • Each error preserves message, locations, path, and extensions (when present). The Tables API exposes errors as JSON-serializable dictionaries with attribute access. Read error.get("extensions", {}) for diagnostic codes, field names, and validation paths; message alone may omit the failing field. The graphql(...) helper logs these details and includes the complete errors in GraphqlException.args[1].
  • Mutations use insert_app_{APP_ID}_{TABLE_NAME} or update_app_{APP_ID}_{TABLE_NAME} with where clauses and _set updates.
  • Ordinary users read and write records belonging to their current runtime organization. The application owner can read across organizations; ordinary owner writes target the owner's organization. Protected tables have shared authenticated reads and owner-only writes. Public reads require the table's explicit public-read option.
  • Public app_action code must pass organization_id when reading or writing one target organization's rows. The SDK sends the delegated runtime headers; it does not rewrite the GraphQL where clause.
  • An app_action call without organization_id keeps creator-wide visibility and should be used only for app-owner discovery reads across activated organizations.

Delegated table access in app_action

Use explicit delegation for every tenant-specific read or mutation:

result = api.tables.apps_graphql_query(
    app=APP_ID,
    table="orders",
    organization_id=target_organization_id,
    graph_ql_request=GraphQLRequest(query=query, variables=variables),
)

The backend verifies the public app_action, its owner, the runtime App-Token, and the target organization's active application token/subscription. It then executes GraphQL using the target organization's scope on either storage engine. Never put the table's organization_id in insert objects, _set, or update_columns, including nested mutation inputs. This applies to every role, including the application owner. The backend assigns the tenant key from the authorized request context. The SDK's organization_id=... argument is request delegation, not a field to add to record variables. Keys named organization_id inside a JSON business field are ordinary data and remain unchanged.

A UUID id may be supplied when creating/importing/upserting a record, but cannot be changed by an update. Timestamps and auto-increment fields remain platform-managed. Creator-wide discovery reads do not authorize global writes; use validated delegation for each customer's records. Protected tables remain read-only under delegated customer scope.

Example: Query a single order by orderId

from typing import Any, Dict
from automio import GraphQLRequest
from automio.wrapper import API

api = API()
APP_ID = 130
ORDERS_TABLE_NAME = "orders"

order_query = f"""query GetOrder($order_id: String!, $organization_id: Int) {{
    app_{APP_ID}_{ORDERS_TABLE_NAME}(
        where: {{orderId: {{_eq: $order_id}}, organization_id: {{_eq: $organization_id}}}},
        limit: 1
    ) {{
        id
        orderId
        buyerLogin
    }}
}}"""

variables: Dict[str, Any] = {"order_id": "eba6bc90-faab-11f0-96f9-c518c5ba21fb", "organization_id": 2}
request = GraphQLRequest(query=order_query, variables=variables)
response = api.tables.apps_graphql_query(
    app=APP_ID, table=ORDERS_TABLE_NAME, graph_ql_request=request
)

if response.errors:
    print(f"Order fetch errors: {response.errors}")
else:
    records = response.data.get(f"app_{APP_ID}_{ORDERS_TABLE_NAME}") or []
    print(records[0] if records else "Order not found")

Example: Update delivered flag by orderId

from typing import Any, Dict
from automio import GraphQLRequest
from automio.wrapper import API

api = API()
APP_ID = 130
ORDERS_TABLE_NAME = "orders"

mutation = f"""mutation UpdateOrderDelivered($order_id: String!, $delivered: Boolean!, $organization_id: Int) {{
    update_app_{APP_ID}_{ORDERS_TABLE_NAME}(
        where: {{orderId: {{_eq: $order_id}}, organization_id: {{_eq: $organization_id}}}},
        _set: {{delivered: $delivered}}
    ) {{
        affected_rows
    }}
}}"""

variables: Dict[str, Any] = {"order_id": "eba6bc90-faab-11f0-96f9-c518c5ba21fb", "delivered": True, "organization_id": 2}
request = GraphQLRequest(query=mutation, variables=variables)
response = api.tables.apps_graphql_query(
    app=APP_ID, table=ORDERS_TABLE_NAME, graph_ql_request=request
)

if response.errors:
    print(f"Order update errors: {response.errors}")

Example: Query without variables (simple string query)

from automio import GraphQLRequest
from automio.wrapper import API

api = API()
APP_ID = 130
TABLE_NAME = "billing_entries"

# GraphQLRequest can be used without variables for simple queries
query = f"""{{
    app_{APP_ID}_{TABLE_NAME}(
        order_by: {{ occurredAt: desc }}
        limit: 1
    ) {{
        allegroId
    }}
}}"""

response = api.tables.apps_graphql_query(
    app=APP_ID, table=TABLE_NAME, graph_ql_request=GraphQLRequest(query=query)
)
rows = response.data.get(f"app_{APP_ID}_{TABLE_NAME}", [])
print(rows[0]["allegroId"] if rows else "No records")

Example: Batch upsert with on_conflict

from typing import Any, Dict, List
from automio import GraphQLRequest
from automio.wrapper import API

api = API()
APP_ID = 130
TABLE_NAME = "billing_entries"

def upsert_batch(rows: List[Dict[str, Any]]) -> None:
    mutation = f"""mutation InsertBatch($objects: [app_{APP_ID}_{TABLE_NAME}_insert_input!]!) {{
        insert_app_{APP_ID}_{TABLE_NAME}(
            objects: $objects,
            on_conflict: {{
                constraint: uq_app_{APP_ID}_{TABLE_NAME}_allegroId_org,
                update_columns: [occurredAt, type, value, balance]
            }}
        ) {{
            affected_rows
        }}
    }}"""

    request = GraphQLRequest(query=mutation, variables={"objects": rows})
    response = api.tables.apps_graphql_query(
        app=APP_ID, table=TABLE_NAME, graph_ql_request=request
    )
    if response.errors:
        print(f"Batch upsert errors: {response.errors}")
        return
    affected = (
        response.data
        .get(f"insert_app_{APP_ID}_{TABLE_NAME}", {})
        .get("affected_rows", 0)
    )
    print(f"Saved {affected} rows")

Example: Insert a message linked to an order

from typing import Any, Dict
from automio import GraphQLRequest
from automio.wrapper import API

api = API()
APP_ID = 130
MESSAGES_TABLE_NAME = "messages"

message_mutation = f"""mutation InsertMessage($data: app_{APP_ID}_{MESSAGES_TABLE_NAME}_insert_input!) {{
    insert_app_{APP_ID}_{MESSAGES_TABLE_NAME}_one(object: $data) {{
        order_id
    }}
}}"""

send_message_payload: Dict[str, Any] = {
    "order_id": "c9a1d25a-fcf3-4950-a660-2f5b04a25320",  # foreign key id
    "messageContent": "Hello, user",
    "organization_id": 2,
}

request = GraphQLRequest(query=message_mutation, variables={"data": send_message_payload})
response = api.tables.apps_graphql_query(
    app=APP_ID, table=MESSAGES_TABLE_NAME, graph_ql_request=request
)

if response.errors:
    print(f"Message insert errors: {response.errors}")
else:
    print(response.data)

Integration API Calls

For public APIs configured with authentication None, get_integration() returns metadata with requires_connection=False even with no accounts. Do not require connected_accounts or user_connections to be nonempty. Omit connection_id for single, parallel and streaming calls:

nbp = api.integrations.get_integration("nbp")
data, response = api.integrations.call(
    nbp, method="GET", endpoint="/api/exchangerates/tables/A/",
    params={"format": "json"},
)
if response and response.ok:
    rates = data[0]["rates"]

This example assumes NBP's configured base URL is https://api.nbp.pl; inspect the integration metadata/OpenAPI before selecting the relative endpoint. The app must allow this integration and be active. Authenticated integrations still require an enabled connection. requires_connection comes from backend metadata; missing metadata does not remove the connection requirement.

Browser and local integrations

Browser execution metadata and BrowserExecutionRequiredError require Automio Python SDK 0.5.3 or newer. Published 0.5.2 does not include this behavior.

Integration definitions preserve execution_target and network_scope. When execution_target="browser", run the operation through the JavaScript SDK in the application UI on the user's computer. The Python SDK raises automio.wrapper.BrowserExecutionRequiredError (code="browser_execution_required") before sending a server-side call. Python actions can prepare business data, but cannot connect to the user's localhost. Keep signing keys in secure integration settings; do not add raw localhost requests or a server fallback.

SOAP/WSDL operations

Requires Automio Python SDK 0.5.2 or newer.

SOAP uses the WSDL operation contract returned by automio-cli integrations schema <integration_id> --json. Choose a service/port operation ID from that catalog. protocol=soap and schema_format=wsdl identify SOAP independently of account authentication. Public operations work with an empty account list; private operations need an active secure connection allowed for the application.

integration = api.integrations.get_integration("dataaccess")
data, response = api.integrations.invoke(
    integration,
    "NumberToWords",
    {"ubiNum": 1234},
    idempotency_key="conversion-job-1234",  # persist for retries of the same job
)
if response.outcome == "unknown":
    status = api.integrations.get_invocation(integration, response.invocation_id)
    # Reconcile a write with the provider before submitting a new invocation.
elif response.ok:
    print(data)

Use a distinct key for each logical operation and reuse it after interrupted requests. SDK transport retries retain the key automatically. The backend reauthorizes replay and returns the saved result without sending the SOAP operation again. response.invocation_id, .outcome, .business_ok and .may_have_executed describe the durable outcome. ok includes configured provider business rules; an HTTP 200 is insufficient to verify credentials.

Authenticate through secure connection settings; never put provider secrets, SOAP envelopes, Authorization or SOAPAction headers in action code. SOAP 1.1/1.2, authentication and XML serialization belong to the backend. For authenticated operations pass connection_id in invoke. Public Ping operations do not verify that private credentials work. The same permission, accounting and delegation rules apply to scheduled actions and application APIs.

The result can be a scalar, object, list or file descriptor. Binary and MTOM content uses short-lived protected handles:

pdf_bytes = api.integrations.download_result_file(data["LabelData"])

File downloads require current account/application access and expire after 24 hours. For batch calls use the catalog operation as endpoint and each item's data/arguments as operation arguments. Responses retain per-item invocation IDs; streaming returns results as they finish. Existing call(method="POST", endpoint=operation, data=arguments) syntax remains supported.

api.integrations.call()

Make synchronous API calls to integrated services.

# Basic API call (default connection)
integration = api.integrations.get_integration("github")
data, response = api.integrations.call(
    integration,
    method="GET",
    endpoint="/user"
)

# With parameters and specific connection (connection_id is an integer ID)
integration = api.integrations.get_integration("allegro_sandbox")
for connection_id in integration.connected_accounts:
    data, response = api.integrations.call(
        integration,
        method="GET",
        endpoint="/sale/offers",
        params={"limit": 10, "offset": 0},
        connection_id=connection_id
    )

print(integration.user_connections)  # {4: "foobar@baz.com"}

# POST with JSON payload
data, response = api.integrations.call(
    integration,
    method="POST",
    endpoint="/messages/submit",
    json={
        "from": {"name": "John Doe", "address": "john@example.com"},
        "to": [{"name": "Jane Doe", "address": "jane@example.com"}],
        "subject": "Test Email",
        "text": "Hello from Python client!"
    },
    connection_id=connection_id
)

# With custom request headers
data, response = api.integrations.call(
    integration,
    method="GET",
    endpoint="/sale/offers",
    headers={"Accept": "application/vnd.allegro.public.v1+json", "X-Custom-Header": "value"},
    connection_id=connection_id
)

# Raw binary body (e.g. image upload via PUT)
declaration, _ = api.integrations.call(
    integration,
    method="POST",
    endpoint="/messaging/message-attachments",
    data={"filename": "photo.jpg", "size": len(image_bytes)},
    headers={"Content-Type": "application/vnd.allegro.public.v1+json"},
    connection_id=connection_id,
)
upload_data, upload_response = api.integrations.call(
    integration,
    method="PUT",
    endpoint=f"/messaging/message-attachments/{declaration['id']}",
    raw_body=image_bytes,
    headers={"Content-Type": "image/jpeg"},
    connection_id=connection_id,
)

Notes:

  • connection_id is the integration connection ID.
  • organization_id is optional.
  • headers (optional) — custom HTTP headers forwarded to the external API. The integration's authorization headers are always added automatically by the backend; use headers only for extra headers required by the API (e.g. Accept, versioning headers).
  • raw_body (optional) — raw bytes to send as the request body. Use this when the external API expects binary content (images, PDFs, etc.) instead of JSON or multipart. The Content-Type from headers is forwarded as the body content type.
  • In app_action, when connection_id comes from APP_CONNECTIONS_BY_INTEGRATION, the backend can infer the target organization automatically. You do not need to pass organization_id.

Note: Canonical account IDs are integers. Every integration method accepts connection_id as a positive integer ID, numeric text, a nonempty provider alias, or None. This includes get_integration() and get_integration_status(); no manual str() conversion is needed. Use integration.connected_accounts to iterate over all connected account IDs, integration.user_connections to get {connection_id: name}, or api.integrations.get_table_connections() to get full table-scoped connection objects.

Returns: (data, response) tuple where:

  • data: Parsed JSON response data
  • response: HTTP response object with .ok, .status_code, .text, .headers, .url attributes

Parallel Methods Return: List[ParallelCallResponse] objects where each response contains:

  • .api_data: Parsed JSON response data from the external service
  • .api_response: HTTP response object (same as above)
  • .connection_id: ID of the connection used for this request
  • .organization_id: Organization ID associated with the connection

Parallel API Calls

api.integrations.parallel_call()

REST batch calls (including parallel_call_for_connection() and parallel_call_stream()) do not return raw binary files. A file response produces an item error binary_response_not_supported: api_data=None, api_response.ok=False, error_info.retryable=False; the provider HTTP status is preserved and may be 200. Other items continue. Read item.error_info.detail (stream: event["response"].error_info) or explicitly call raise_for_error(). Use single integrations.call() for downloads. The provider request was already sent: never automatically replay writes or the entire batch. SOAP JSON file descriptors are unaffected.

Execute multiple API calls concurrently using different connections per request for maximum performance and flexibility.

# Multi-connection parallel calls (recommended for scaling across accounts)
responses = api.integrations.parallel_call(
    integration,
    method="GET",
    endpoint="/sale/product-offers/{offerId}",
    data_list=[
        {
            "connection_id": 123,
            "organization_id": 456,
            "url_params": {"offerId": "offer_1"},
            "params": {"include": "details"}
        },
        {
            "connection_id": 789,
            "organization_id": 101,
            "url_params": {"offerId": "offer_2"},
            "data": {"expand": True}
        }
    ],
    table="app_123_products"
)

# Process results with new object-based API
for response in responses:
    print(f"Connection {response.connection_id}, Org {response.organization_id}")
    if response.api_response.ok:
        print(f"Offer: {response.api_data['name']}")
        print(f"Status: {response.api_response.status_code}")
    else:
        print(f"Error: {response.api_response.text}")

api.integrations.parallel_call_for_connection()

Execute multiple API calls in parallel using a single connection (simpler for single-account operations).

# Single-connection parallel calls
responses = api.integrations.parallel_call_for_connection(
    integration,
    method="GET",
    endpoint="/sale/product-offers/{offerId}",
    data_list=[
        {"url_params": {"offerId": "123"}},
        {"url_params": {"offerId": "456"}},
        {"url_params": {"offerId": "789"}}
    ],
    connection_id="user@domain.com",
    organization_id=123,
    table="app_124_offers"
)

# Process results
for response in responses:
    if response.api_response.ok:
        print(f"Offer: {response.api_data['name']}")
    else:
        print(f"Error: {response.api_response.text}")

api.integrations.parallel_call_stream()

Stream parallel API calls for real-time processing and progress visibility.

# Stream parallel calls with real-time processing (single connection)
for result in api.integrations.parallel_call_stream(
    integration,
    method="GET",
    endpoint="/sale/product-offers/{offerId}",
    data_list=[{"url_params": {"offerId": offer["id"]}} for offer in offers],
    connection_id=connection_id
):

    if result.get("final"):
        print(f" Completed! Processed {result['total_processed']} requests")
        break
    else:
        # Process individual response as it arrives
        data = result["data"]
        response = result["response"]
        index = result["index"]

        if response.ok:
            # Process immediately without waiting for all requests
            processed_data = process_data(data)
            save_to_database(processed_data)
        else:
            print(f"❌ Error for request {index}: {response.text}")

Plugins

Plugins let you run shared, reusable Python code per integration - defined once in a Plugin Interface, implemented separately for each integration.

Concepts:

  • Plugin Interface - a contract identified by a namespace and a list of capabilities (function names). Think of it as an abstract class. Example: test_interface with capability foo.
  • Plugin Interface code - shared Python code available to all plugins under that interface (helpers, base functions, common constants).
  • Plugin - a concrete implementation of that interface for a specific integration (e.g., allegro_sandbox). It can override selected capabilities and reuse the interface code.

Shared Interface Code

When a Plugin Interface defines code, plugins in that interface can import it with:

from plugins.interfaces.<namespace> import <name>

Example for namespace test_interface:

from plugins.interfaces.test_interface import test_ifc

Or import everything from the interface module:

from plugins.interfaces.test_interface import *

api.plugins.get_list(namespace)

List all enabled plugins registered under a given interface namespace.

for plugin in api.plugins.get_list("test_interface"):
    print(f"Plugin ID: {plugin.id}")
    print(f"Connection IDs: {plugin.connection_ids}")

api.plugins.invoke(plugin, integration, connection_ids, **payload)

Invoke a capability from a plugin. The first argument is "namespace.capability", the second is the integration ID string.

integration = api.integrations.get_integration("allegro_sandbox")

for plugin in api.plugins.get_list("test_interface"):
    result = api.plugins.invoke(
        "test_interface.foo",        # namespace.capability
        integration.integration_id,  # integration name as string
        connection_ids=plugin.connection_ids,
    )

The plugin code (written in the platform's code editor) receives connection_ids as a keyword argument:

# Plugin code for test_interface / allegro_sandbox integration:
def foo(connection_ids: list):
    for connection_id in connection_ids:
        data, response = api.integrations.call(
            api.integrations.get_integration("allegro_sandbox"),
            method="GET",
            endpoint="/sale/offers",
            connection_id=connection_id,
        )
        print(data)

APP_CONNECTIONS_BY_INTEGRATION in app_action

For actions of type app_action, the runtime injects:

APP_CONNECTIONS_BY_INTEGRATION = {
    "allegro_sandbox": [
        {"organization_id": 3, "connection_ids": [34, 9438]},
        {"organization_id": 2, "connection_ids": [102]},
    ]
}

Use this variable only in app_action. It is not available in user_action, table_action, trigger_action, or webhook_action.

Typical usage:

from automio.wrapper import API

api = API()

for integration_id, organization_groups in APP_CONNECTIONS_BY_INTEGRATION.items():
    for group in organization_groups:
        organization_id = group["organization_id"]
        connection_ids = group["connection_ids"]

        result = api.plugins.invoke(
            "test_interface.foo",
            integration_id,
            connection_ids=connection_ids,
        )
        print(f"Processed org {organization_id}: {result}")

You can also call integration APIs directly from app_action using only connection_id:

for group in APP_CONNECTIONS_BY_INTEGRATION["allegro_sandbox"]:
    for connection_id in group["connection_ids"]:
        data, response = api.integrations.call(
            api.integrations.get_integration("allegro_sandbox"),
            method="GET",
            endpoint="/sale/offers",
            connection_id=connection_id,
        )
        print(group["organization_id"], connection_id, data)

Notes:

  • Keys are integration_id values, for example allegro_sandbox or gmail.
  • Each integration contains a list of organization groups.
  • Each organization group has:
    • organization_id: the organization that granted the connections to the application,
    • connection_ids: the enabled connection IDs for that integration and organization.
  • The data includes only connections explicitly enabled for the app through ApplicationIntegrationAccountAccess.
  • The delegated api.integrations.call(..., connection_id=...) flow described above is available only in app_action.

Connection Management

integration.connected_accounts

The simplest way to iterate over all connected account IDs for an integration. Returns an iterable of integer connection IDs.

integration = api.integrations.get_integration("allegro_sandbox")
for connection_id in integration.connected_accounts:
    data, response = api.integrations.call(
        integration,
        method="GET",
        endpoint="/billing/billing-entries",
        connection_id=connection_id,
        params={"limit": 100},
    )

integration.user_connections

Contains the same connections as integration.connected_accounts, but as a dictionary where each key is the connection ID and each value is the display name.

integration = api.integrations.get_integration("allegro_sandbox")

for connection_id, name in integration.user_connections.items():
    print(connection_id, name)
    data, response = api.integrations.call(
        integration,
        method="GET",
        endpoint="/billing/billing-entries",
        connection_id=connection_id,
    )

api.integrations.get_table_connections()

Get all connected accounts for an integration. Returns list of connections with id and name.

# Get all connected accounts
connections = api.integrations.get_table_connections(integration: Integration, table_name: str)
for connection in connections:
    print(f"ID: {connection.id}, Name: {connection.name}")

    # Use connection ID in API calls
    data, response = api.integrations.call(
        integration,
        method="GET",
        endpoint="/sale/offers",
        connection_id=connection.id  # integer ID
    )

Caching System

The SDK exposes two cache scopes:

API Scope Typical use
api.app_cache current app + current organization data reused by actions in the same app for the same organization
api.org_cache current organization data shared between apps and actions in the same organization

api.user_cache is kept as a backwards-compatible alias for api.org_cache, but new code should use api.org_cache.

Both cache APIs expose:

  • set(key, value, ttl=None)
  • get(key)
  • delete(key)

Response Shape

get() returns cache metadata, not only the raw value:

{
    "key": "api_data",
    "value": {"rates": [1.2, 1.5, 1.8]},
    "exists": True,
    "ttl": 300,
}

For a missing key:

{
    "key": "api_data",
    "value": None,
    "exists": False,
    "ttl": None,
}

Always read your cached data from the value field after checking exists.

App Cache

Shared cache for the current app and organization. Use it for data that should not cross app boundaries.

api.app_cache.set(
    key="api_data",
    value={"rates": [1.2, 1.5, 1.8]},
    ttl=300  # 5 minutes
)

cached_data = api.app_cache.get(key="api_data")
if cached_data and cached_data["exists"]:
    print(cached_data["value"])  # {'rates': [1.2, 1.5, 1.8]}

# Delete cache entry
api.app_cache.delete(key="api_data")

Organization Cache

Shared cache for the current organization, independent of the app. Use it when multiple apps or actions in the same organization should share the same cached value.

api.org_cache.set(
    key="my_key",
    value="my_value",
    ttl=3600  # 1 hour
)

cached = api.org_cache.get(key="my_key")
if cached and cached["exists"]:
    print(cached["value"])

# Delete organization cache
api.org_cache.delete(key="my_key")

TTL

ttl is optional and is expressed in seconds.

api.org_cache.set("temporary_state", {"step": 2}, ttl=900)

If ttl is omitted, the value remains until deleted or evicted by the underlying Redis/cache service.

Cache Keys

Keys are strings. The SDK supports keys with slashes and spaces, but stable simple names are easier to inspect and clean up.

api.app_cache.set("imports/allegro/page-1", {"processed": 100}, ttl=900)

Errors and Availability

Cache HTTP requests use a 3.05-second connect timeout and 10-second read timeout. Direct Redis uses the same bounded connect/read timeouts. An explicitly configured HTTP cache service never silently falls back to a different store. Constructing API() without a cache backend does not emit an error; attempting to use an unavailable cache still raises the explicit exception below.

If the hosted cache service returns an error response, cache calls raise CacheServiceError.

If cache cannot be initialized in the current environment, api.app_cache, api.org_cache, api.user_cache, and api.task still exist, but using them raises CacheUnavailableError with the initialization reason.

Notifications

api.runtime.send_notification()

Send an in-app notification to the current runtime user. The backend resolves the recipient from the current APP_TOKEN/session, so do not pass a user id.

api.runtime.send_notification(
    title="Import finished",
    description="128 rows are ready to review.",
    kind="success",  # info | success | warning | error
    event_key="import_finished",
    image="https://example.com/import-summary.png",
    data={"batch_id": "batch_123"},
    actions=[
        {
            "title": "Review rows",
            "app_path": "/imports/batch_123",
        },
    ],
)

APP_ID and the notification source are resolved automatically from the runtime environment and headers. The backend stores runtime events under the app_runtime. namespace automatically. image and actions[].url accept https://... URLs or internal paths starting with /.

This method requires a valid hosted runtime APP_TOKEN for the current APP_ID. Local direct-runs without that token raise a clear runtime error instead of sending a notification.

Notification action destinations

Each action has a title and exactly one target:

  • app_path: "/radar/#/alerts" opens a page inside the exact application identified by the runtime APP_ID.
  • url: "/account/notifications" opens a page on the Automio platform.
  • url: "https://example.com/report" opens an external HTTPS address.

For Python, use the same fields as dictionary keys. Application paths must start with a single /; absolute URLs and //host are rejected in app_path. The backend stores app_path as intent and returns a fully resolved url to notification viewers. It uses the application's active primary custom domain, or its configured runtime subdomain. Development links remain tied to the development app; they never switch to production. Query strings and fragments are preserved exactly, so use the fragment expected by your UI router. Links have the same destination in the platform, application UI, and Web Push. Local preview captures preserve app_path for inspection. url does not infer an application destination from the notification category or page displaying it.

api.notify_me()

Send notifications (via email) to yourself (useful for monitoring and alerts).

# Send notification
api.notify_me(
    subject="API Process Completed",
    text="Successfully processed 1000 records",
    html="<h1>Success!</h1><p>Processed <strong>1000</strong> records</p>"
)

notify_me is an email helper with signature api.notify_me(subject, text, html=None). It is separate from in-app runtime notifications.

Task Progress Tracking

api.task.set_progress(progress: int, info: str, status: 'pending' | 'completed' | 'failed')

Update task progress for long-running operations. progress and info are displayed in the UI during task execution, while status indicates the task state.

Allowed statuses:

Status Meaning
pending Work is still running
completed Work finished successfully
failed Work failed
# Initialize progress
api.task.set_progress(0, "Starting data processing...", "pending")

# Update progress throughout your task
for i, item in enumerate(large_dataset):
    # Process item
    process_item(item)

    # Update progress every 100 items
    if i % 100 == 0:
        progress = int((i / len(large_dataset)) * 100)
        api.task.set_progress(
            progress,
            f"Processed {i}/{len(large_dataset)} items",
            "pending"
        )

# Complete the task
api.task.set_progress(100, "Processing completed!", "completed")

In the hosted cache service, status="completed" or status="failed" forces progress to 100. A progress value of 100 with any other status is normalized to completed.

For local Redis development, progress is stored under task:progress:{TASK_ID} and logged to the console. In Automio.ai runtime, progress updates are written to the code runner task state and displayed in the UI.

Configuration & Environment

Cache & Progress Service Configuration

The client automatically detects and adapts to your environment:

Automio.ai Runtime (Automatic)

When running inside the Automio.ai action runtime:

  • Uses the hosted cache service API
  • TASK_ID is automatically assigned by the platform
  • CACHE_SERVICE_URL and CACHE_SERVICE_TOKEN are provided by the platform
  • Progress tracking is displayed in the Automio.ai UI
  • app_cache is scoped to the current app and organization
  • org_cache is scoped to the current organization and can be shared between apps
  • The cache service derives the real namespace from TASK_ID, so action code does not pass app or organization IDs manually

Local Development with automio-cli (Automatic)

The CLI injects TASK_ID, CACHE_SERVICE_URL, and a per-run CACHE_SERVICE_TOKEN. The existing HTTP transport talks to the local gateway backed by SQLite. Neither Redis nor the redis Python package is required. Cache persists between action processes, preserving app/organization scopes and TTL. Preview, CLI/TUI, cron, webhooks and triggers use the same configuration. Local cache is separate from hosted cache even when the app uses remote GraphQL data.

The CLI status endpoint and SSE status events carry actual progress and info. Only process completion ends the run; reporting completion early cannot mask a later exception. Restart an existing local gateway after upgrading the CLI. No application changes or manual cache environment variables are needed.

Standalone SDK (Redis)

When running outside automio-cli without CACHE_SERVICE_URL:

  • Automatically uses direct Redis connection
  • TASK_ID is generated as a random UUID4
  • Progress is logged to console
  • Requires Redis server running locally
  • Uses ORGANIZATION_ID or ACTION_OWNER_ORGANIZATION_ID for local org cache namespacing; falls back to local

Local Redis namespaces match hosted runtime semantics:

app:{APP_ID}:code_owner:{ORGANIZATION_ID}:{key}
org:{ORGANIZATION_ID}:{key}

Optional Local Redis Dependency

The hosted Automio.ai runtime does not require the Redis Python package in your action dependencies. Install redis yourself only when you want to use the direct local Redis fallback without CACHE_SERVICE_URL.

pip install redis

Usage Impact

From the user perspective, there are no code changes required. The client automatically:

  • Detects environment and chooses appropriate backend
  • Maintains consistent API across both configurations
  • Handles serialization/deserialization transparently
  • Provides same response format regardless of backend
# This code works identically in both environments
api.app_cache.set("my_key", {"data": "value"}, ttl=300)
cached_data = api.app_cache.get("my_key")
if cached_data and cached_data["exists"]:
    print(cached_data["value"])
api.task.set_progress(50, "Halfway done", "pending")

Cache Use-Case Script

The repository includes a plain Python script that exercises common cache scenarios using the current .env:

python cache_usecase.py

It checks:

  • api.app_cache and api.org_cache
  • JSON and scalar roundtrips
  • missing keys
  • overwrites
  • deletion
  • TTL expiry
  • keys with slashes/spaces
  • task progress
  • optional api.user_cache alias with --include-user-cache-alias

Useful flags:

python cache_usecase.py --skip-ttl
python cache_usecase.py --skip-progress
python cache_usecase.py --include-user-cache-alias

Environment Detection Logic

# The client automatically determines configuration:
if CACHE_SERVICE_URL:
    # Use Automio.ai cache service API
    # - HTTP requests to cache service
    # - Progress updates sent to platform
    # - Task ID from runtime environment
else:
    # Use local Redis connection
    # - Direct Redis operations
    # - Progress logged to console
    # - UUID4 generated for task tracking

Integration Management

api.integrations.get_integration()

Get integration configuration for API calls.

# Get integration
integration = api.integrations.get_integration("allegro_sandbox")
# Now use this integration object in .call() methods

print(integration.user_connections)  # {4: "foobar@baz.com"}

api.integrations.get_integrations()

List all available integrations.

integrations = api.integrations.get_integrations()
for integration in integrations.results:
    print(f"ID: {integration.integration_id}, Name: {integration.name}")

Common Patterns

1. Parallel Data Processing

# Efficient parallel processing pattern
integration = api.integrations.get_integration("api_service")

# Step 1: Get list of items
list_data, response = api.integrations.call(
    integration, method="GET", endpoint="/items",
    params={"limit": 50}, connection_id="user@domain.com"
)

# Step 2: Process details in parallel (single connection)
detail_requests = [
    {"url_params": {"id": item["id"]}}
    for item in list_data["items"]
]

responses = api.integrations.parallel_call_for_connection(
    integration,
    method="GET",
    endpoint="/items/{id}/details",
    data_list=detail_requests,
    connection_id="user@domain.com",
    organization_id=123
)

# Step 3: Process results with new object API
processed_data = []
for response in responses:
    if response.api_response.ok:
        processed_data.append(transform_data(response.api_data))
    else:
        print(f"Error for connection {response.connection_id}: {response.api_response.text}")

2. Multi-Connection Parallel Processing

# Advanced: Parallel processing across multiple connections simultaneously
integration = api.integrations.get_integration("api_service")

# Get all connections for the service
table_connections = api.integrations.get_table_connections(integration, "data_table")

# Build parallel requests for multiple connections
data_list = []
for org_id, connections in table_connections.items():
    for connection in connections:
        data_list.append({
            "connection_id": connection["id"],
            "organization_id": org_id,
            "params": {"limit": 50},
            "url_params": {"account_id": connection["id"]}
        })

# Execute all requests in parallel across all connections
responses = api.integrations.parallel_call(
    integration,
    method="GET",
    endpoint="/accounts/{account_id}/data",
    data_list=data_list,
    table="app_123_consolidated_data"
)

# Process results with full traceability
for response in responses:
    print(f"Org {response.organization_id}, Connection {response.connection_id}")
    if response.api_response.ok:
        save_data(response.api_data, response.connection_id, response.organization_id)
    else:
        log_error(response.connection_id, response.api_response.text)

3. Multi-Account Operations

# Process data across multiple connected accounts
connections = api.integrations.get_table_connections("service_name", "table_name")

for connection in connections:
    print(f"Processing account: {connection.name}")

    data, response = api.integrations.call(
        integration,
        method="GET",
        endpoint="/data",
        connection_id=connection.id
    )

    if response.ok:
        # Process account-specific data
        process_account_data(data, connection.id)

3. Progress Tracking with Caching

def long_running_task():
    api.task.set_progress(0, "Initializing...", "in_progress")

    # Cache intermediate results
    api.app_cache.set("task_checkpoint", {"processed": 0}, ttl=3600)

    for i in range(1000):
        # Do work
        process_item(i)

        # Update progress and cache
        if i % 100 == 0:
            progress = int((i / 1000) * 100)
            api.task.set_progress(progress, f"Processed {i}/1000", "in_progress")
            api.app_cache.set("task_checkpoint", {"processed": i}, ttl=3600)

    api.task.set_progress(100, "Completed!", "completed")
    api.app_cache.delete("task_checkpoint")

Performance Tips

  • Use parallel calls for multiple API requests to the same service
  • Cache frequently accessed data to reduce API calls
  • Stream parallel calls for real-time processing of large datasets
  • Set appropriate TTL for cached data based on update frequency
  • Monitor progress for long-running tasks to improve user experience

Error Handling

Single API Calls

data, response = api.integrations.call(integration, method="GET", endpoint="/data")

if not response.ok:
    print(f"API Error: {response.status_code} - {response.text}")
    return

if not data:
    print("No data received")
    return

# Process successful response
process_data(data)

Parallel API Calls

responses = api.integrations.parallel_call(
    integration, method="GET", endpoint="/data",
    data_list=requests_data
)

for response in responses:
    if not response.api_response.ok:
        print(f"Error for connection {response.connection_id}: {response.api_response.text}")
        continue

    if not response.api_data:
        print(f"No data received for connection {response.connection_id}")
        continue

    # Process successful response
    process_data(response.api_data, response.connection_id)

SOAP soap_headers accepts only WSDL-declared business header fields; managed authentication headers cannot be overridden. Binary descriptors also expose mcp_resource_uri for authenticated retrieval through the MCP connector.

Connection contract (SDK 0.5.4)

ConnectionRef = int | str | None is shared by metadata, single, SOAP, parallel and streaming calls. Floats, booleans, containers and blank aliases are rejected. CONNECTION_ID in an action remains int | None; pass it directly to the SDK. Metadata lookup does not select an account for later calls: pass the chosen ID to each call. Returned IDs and table account columns remain integers. Integration.account is typed safe metadata (id, name, email, picture); provider uid and extra_data are not part of that public contract. Integration.user_connections is a typed dict[int, str] property.

The generated wrapper reference is imported into agent knowledge from docs/app/actions/sdk-reference/page.mdx. Regenerate it with python scripts/generate_sdk_reference.py. To regenerate the connection SDK surface, export Django spectacular JSON and run python scripts/generate_connection_contract.py --schema /path/to/schema.json. The committed scoped OpenAPI snapshot supports reproducible --check without a server.

Metadata

Release files for automio 0.5.11

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for automio 0.5.11
File Size Uploaded Provenance Actions
automio-0.5.11.tar.gz 194.2 kB Without provenance Details for automio-0.5.11.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for automio 0.5.11
File Interpreter ABI Platform Actions
automio-0.5.11-py3-none-any.whl Python 3 none any Details for automio-0.5.11-py3-none-any.whl

Total release size: 392.2 kB

Release files / automio-0.5.11.tar.gz

Download URL automio-0.5.11.tar.gz
Size 194.2 kB
Tags Source
SHA-256 checksum
How to use checksums
fd1abd30f924e1a2106ce07f8f092381b873879122899fa932d8a73e25ed55b2
BLAKE2b-256 checksum
How to use checksums
f671e267c52fe2ba932fb0fc59e0e8e1315068d20e658bbc074a8c9c017f8689
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.12.16

Release files / automio-0.5.11-py3-none-any.whl

Download URL automio-0.5.11-py3-none-any.whl
Size 198.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bdbbb08cfc2ec3ac9bd6c277efcb7235754abd5f9117731458fca756860fea1f
BLAKE2b-256 checksum
How to use checksums
c0c6eca3d3c4b2cddf0a1f3e1b5ec025c7a6c1e2d3fbbdfc2fa80e637565288e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.12.16

Security for automio 0.5.11

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.5.11 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page