Orchestrating Asynchronous AI Workflows and Multi-Tenant Projects via REST API
Table of contents:
A single prompt finishes in a couple of seconds. Production pipelines take much longer. Once your server fetches a web page, parses the text, checks conditions, and calls two heavy reasoning models in a row, wait times easily pass the one-minute mark. At that point, a standard HTTP request simply times out. The client gets a 504 Gateway Timeout error, while you still pay for the tokens spent on earlier steps.
Instead of setting up custom Celery workers or RabbitMQ queues for every multi-step prompt, you can run long tasks in the background. This guide shows how to trigger AI workflows asynchronously via REST API, separate client balances by project, recover interrupted runs, and check the exact cost of every step in a pipeline.
TL;DR: how the asynchronous AI workflow API and project orchestration work
-
Two separate execution paths: synchronous chat at /v1/chat/completions closes connections after 60 seconds, so multi-step pipelines run through the asynchronous AI workflow API under /api/v1/workflows/.
-
Different auth headers: project, workflow, and billing routes use X-Api-Key authentication, while Authorization: Bearer is only used for the OpenAI-compatible chat proxy.
-
Root-level input format: when calling /run/ with an X-Api-Key, send parameters directly at the root of the request body as a flat JSON payload without wrapping them inside input_data.
-
Database write lag: keep polling the workflow_result endpoint until the data.data dictionary is populated. The database finishes saving node outputs 1 to 2 seconds after the run status switches to "succeed".
-
Replay and cost tracking: restart interrupted jobs through the re-run endpoint with their original inputs, and check per-step charges in USD and internal SR credits via /api/v1/billing-history/workflowrun/{run_id}/.
Handling 60-second timeout by offloading LLM tasks to workflows
ScriptRun splits model calls into two separate paths. The synchronous chat route POST /v1/chat/completions replaces the standard OpenAI SDK directly. Here, the server waits up to 60 seconds for a model to reply. That is plenty of time for live chat or Server-Sent Events SSE streaming while a user watches the screen.
Background automation needs more headroom. Network load balancers like Cloudflare or corporate proxies drop connections that hang open for minutes. Handling 60-second timeout by offloading LLM tasks to workflows solves three backend problems right away:
-
Your server threads stay free: the backend sends a POST request to start the workflow, gets back a WorkflowRun UUID with status "in queue", and immediately moves on to other requests.
-
Branching logic without extra code: inside a single workflow graph, you can link a starting trigger-node, conditional if-else-node branches, external calls via http-node, MCP tools discovered through /api/v1/workflows/mcp-tools/, and model prompts in basic-node blocks.
-
No lost progress on failure: if an external site fails to respond on step four of a five-step pipeline, the platform saves the outputs from the first three blocks in the run history.
Feature | Synchronous chat proxy: POST /v1/chat/completions | Asynchronous engine: /api/v1/workflows/* & /api/v1/projects/* |
Best for | Live chat, SSE streaming, Vision, Embeddings | Multi-step pipelines, branching, HTTP calls, background jobs |
Auth header | Authorization: Bearer <API_KEY> | X-Api-Key: <API_KEY> |
Time limit | 60-second server timeout | Runs in the background without holding sockets open |
Response format | Immediate model reply or SSE chunk stream | Returns a WorkflowRun UUID in data.id for status polling |
Cost breakdown | Total token count in usage for one call | Step-by-step billing history by node UUID in USD and SR |
⚡ Connect 50+ LLMs via unified Open-API
Multi-tenant AI projects API and X-Api-Key authentication
When an agency or SaaS team builds AI features for multiple clients, putting every workflow into one shared account quickly gets messy. Execution logs mix together in one feed. Worse, a traffic spike from one busy customer can burn through your shared rate limits and block everyone else. Accounting also has no clean way to split the monthly bill. The multi-tenant AI projects API at /api/v1/projects/ keeps clients separate. Each project acts as its own container with dedicated workflows, custom provider keys in attached_provider_keys, webhook settings, and an isolated spend counter in total_spent.
All calls to /api/v1/* routes use X-Api-Key authentication in the request headers. By default, each key allows 60 requests per minute alongside token-aware rate limiting. If your service needs higher throughput, message support on Telegram at @scriptrunai or email support@scriptrun.ai to raise the limit.
To browse workspaces or run logs, list endpoints use page and size pagination, returning 10 items by default and up to 100 per page. You can also filter projects by name via name__icontains and update project webhook configuration in code using the webhook_url and is_webhook_enabled fields:
import requests
PROJECTS_URL = "https://scriptrun.ai/api/v1/projects/"
HEADERS = {
"X-Api-Key": "sr_live_your_api_key",
"Content-Type": "application/json"
}
# 1. Create a separate project container for a new client
create_body = {
"name": "Tenant_Acme_Automation",
"webhook_url": "https://api.yourdomain.com/webhooks/acme/",
"is_webhook_enabled": True
}
project = requests.post(PROJECTS_URL, headers=HEADERS, json=create_body, timeout=15).json()
project_id = project["id"]
print(f"Created project {project_id} | Current spend: {project['total_spent']}")
# 2. List projects using page and size pagination with name filtering
query_params = {
"page": 1,
"size": 25,
"name__icontains": "acme"
}
page_data = requests.get(PROJECTS_URL, headers=HEADERS, params=query_params, timeout=15).json()
print(f"Matching projects: {page_data['total']} | Items on page: {len(page_data['items'])}")
# 3. Update project webhook configuration via PATCH
patch_body = {
"name": "Tenant_Acme_Prod",
"webhook_url": "https://api.yourdomain.com/webhooks/v2/acme/",
"is_webhook_enabled": True
}
requests.patch(f"{PROJECTS_URL}{project_id}/", headers=HEADERS, json=patch_body, timeout=15)
Every project record shows accumulated costs in two currencies inside total_spent, such as {"USD": "0.00038", "SR": "0.038"}. To invoice a specific client at the end of the month, pull that summary with a single GET /api/v1/projects/{id}/ request.
🗂️ Create isolated projects for your clients
How to trigger AI workflows asynchronously via REST API
Before running a workflow from your code, check what inputs it expects and make sure all blocks are connected properly. First, call GET /api/v1/workflows/{id}/check_workflow/ to verify the workflow structure, and then request GET /api/v1/workflows/{id}/input-fields/. The second endpoint lists all variables from the starting Trigger block: field names in id, data types like text, select, or number, required flags in input_requirements, and secret markers in is_secret.
Working with secret tokens and passwords: if an input field has is_secret: true, the server hides its real value behind ******** in every API response. When you update or run a workflow and want to keep the saved password, send ******** in that field. The backend will automatically use the stored credential from the database. If you send any other string, it overwrites the old secret.
To set a tested run configuration as the active version for API calls, send {"is_api_run": true} to POST /api/v1/workflows/{id}/history/{run_id}/toggle-api-run/. The platform marks that version as the default for external requests and clears the flag on the older one.
Root-level JSON inputs and HTTP 422 node validation
To understand how to trigger AI workflows asynchronously via REST API, start with the body format accepted by POST /api/v1/workflows/{id}/run/. The endpoint expects different JSON structures depending on which auth header you send:
-
Server requests with X-Api-Key: pass your variables right at the top level of the request body without extra nesting, which the documentation calls a flat JSON payload. For example, send {"user_name": "John", "email": "john@example.com"} directly and do not wrap those fields inside an input_data object. You can also send raw text with Content-Type: text/plain, which lands automatically in {{ input._raw_input_ }}.
-
Browser sessions with Authorization: Bearer <JWT>: used by the web editor, and only this mode wraps variables inside {"input_data": {...}}.
Inside workflow blocks, reference your input variables with double curly braces: {{ input.user_name }} for simple keys, {{ input.company.departments$0$.name }} for nested lists, and {{ <nodeId>.result.content }} to pass one block's output into the next prompt.
Pay attention to how /api/v1/workflows/{id}/run/ reports startup errors. The web server always returns an HTTP 200 OK wrapper, while the actual queue status sits inside the JSON body under response$"status"$:
-
status == 201: the workflow is queued and running. Save the UUID string from response$"data"$$"id"$ to poll for results.
-
status == 422: HTTP 422 node validation failed on a specific block, such as when a required trigger field is missing or a prompt message is empty. The run does not start, and data.data returns the UUID of the broken node along with the error text.
-
status == 400: invalid JSON syntax or broken workflow schema.
The full workflow lifecycle from launch to cost auditing looks like this:
$Your Backend$
│
├─ 1. POST /api/v1/workflows/{id}/run/ (X-Api-Key header + root-level JSON fields)
│ ◄── HTTP 200 wrapper: check inner status field (201 = queued, 422 = validation error)
│
├─ 2. Poll loop: GET /api/v1/workflows/workflow_result/?id=<run_uuid> (every 3-5s)
│ ├─ Status "in queue" / "in progress" / "not found" ──► wait and keep polling
│ └─ Status "succeed" ──► check if database finished writing node outputs to data.data
│ ├─ data.data empty ──► wait 2s and retry GET (up to 3 attempts)
│ └─ data.data present ──► strip markdown fences & parse JSON
│
├─ 3. (If run hits "failed") POST /api/v1/workflows/{id}/history/{run_id}/re-run/
│ ◄── Replay failed run from DLQ / history with original or updated JSON inputs
│
└─ 4. GET /api/v1/billing-history/workflowrun/{run_id}/
◄── Check per-node charges in USD and SR tokens for every step
⚙️ Build multi-step AI workflows visually now
LLM workflow execution polling and database write lag
Once POST /api/v1/workflows/{id}/run/ returns inner status 201, grab the UUID string from data.id and start LLM workflow execution polling via the workflow_result endpoint at GET /api/v1/workflows/workflow_result/?id=<run_uuid>.
When writing your polling loop, account for a short database write lag, which the documentation calls the temporal consistency window. The overall run status in data.status switches to "succeed" or "failed" 1 to 2 seconds before the outputs from individual blocks finish saving into the data.data dictionary. If your script stops polling the exact millisecond it sees "succeed", data.data might still be empty.
A similar delay can happen right after launch. The run is registered in the database, but the background runner has not created the result record yet, so workflow_result returns HTTP 200 with data.status: "not found" and data.data: null. Do not treat "not found" as a fatal error at the start of polling. Wait 3 seconds and try again.
You should also clean up the text inside result.content before parsing it. Language models frequently wrap JSON replies inside Markdown code fences like ```json ... ```. Because the server returns model output as-is, strip those backticks on the client side before calling json.loads().
Here is a ready-to-use Python script that submits a flat JSON body, checks for inner 422 errors, waits for database writes to finish, and strips Markdown code fences:
import json
import re
import time
import requests
API_KEY = "sr_live_your_api_key"
WORKFLOW_ID = 65
HEADERS = {
"X-Api-Key": API_KEY,
"Content-Type": "application/json"
}
def parse_node_content(content: str):
"""Remove optional markdown JSON code fences and parse JSON if valid."""
fence_match = re.match(r"```(?:json)?\s*([\s\S]*?)\s*```", content.strip())
if fence_match:
content = fence_match.group(1)
try:
return json.loads(content)
except (json.JSONDecodeError, ValueError):
return content
def execute_and_poll_workflow(workflow_id: int, flat_payload: dict, timeout_seconds: int = 180) -> dict:
# 1. Start workflow run with root-level JSON parameters (flat JSON payload)
run_url = f"https://scriptrun.ai/api/v1/workflows/{workflow_id}/run/"
run_resp = requests.post(run_url, headers=HEADERS, data=json.dumps(flat_payload), timeout=15)
run_body = run_resp.json()
inner_status = run_body.get("status")
if inner_status == 422:
validation_errors = run_body.get("data", {}).get("data", {})
raise ValueError(f"HTTP 422 node validation error: {validation_errors}")
if inner_status != 201:
raise RuntimeError(f"Workflow failed to start: {run_body}")
run_id = run_body["data"]["id"]
print(f"Workflow queued. Run UUID: {run_id}")
# 2. Poll workflow_result endpoint and wait for database writes to finish
result_url = "https://scriptrun.ai/api/v1/workflows/workflow_result/"
terminal_states = {"succeed", "failed"}
deadline = time.time() + timeout_seconds
consistency_retries = 0
while time.time() < deadline:
poll_resp = requests.get(result_url, headers={"X-Api-Key": API_KEY}, params={"id": run_id}, timeout=15)
executor_data = poll_resp.json().get("data", {})
status = executor_data.get("status")
if status in terminal_states:
node_map = executor_data.get("data")
# Confirm that node outputs have finished saving to data.data
if node_map:
if status == "failed":
raise RuntimeError(f"Workflow run failed: {node_map}")
parsed_results = {}
for node_uuid, node_payload in node_map.items():
if node_payload.get("status") == "succeed" and "result" in node_payload:
raw_str = node_payload["result"].get("content", "")
parsed_results[node_uuid] = parse_node_content(raw_str)
return {"run_id": run_id, "nodes": parsed_results}
# Status is terminal, but data.data is still empty (wait 2s for DB write)
if consistency_retries < 3:
consistency_retries += 1
time.sleep(2)
continue
return {"run_id": run_id, "nodes": {}}
# Keep polling on "in queue", "in progress", or initial "not found"
time.sleep(3)
raise TimeoutError(f"Workflow run {run_id} timed out after {timeout_seconds}s")
Keep in mind that data.data stores outputs by node UUID, and key order inside a JSON object can change between runs. Rather than grabbing the last key in the dictionary, look up the specific UUID of your final output block from GET /api/v1/workflows/{id}/.
Dead letter queue workflow replay and manual step approvals
External services fail from time to time. A third-party server might drop a request from an http-node, or an upstream model provider might hit a brief outage. ScriptRun saves interrupted runs in the workflow history and holds them for dead letter queue workflow replay along with their original input_data and workflow snapshot.
You can browse past runs through GET /api/v1/workflows/{id}/history/ and sort them via ordering by creation time with created_at or -created_at, or by cost with cost or -cost. Stored history items use archive status labels: In Progress, Succeeded, Cancelled, Error, and Draft. Do not confuse these with the live polling statuses in queue, in progress, succeed, and failed returned by workflow_result.
Once the external service is back online, call the re-run endpoint at POST /api/v1/workflows/{id}/history/{run_id}/re-run/ to restart the job. Sending an empty body re-runs the workflow with the old inputs, while sending new root-level JSON fields updates the parameters for the new run:
import requests
API_KEY = "sr_live_your_api_key"
WORKFLOW_ID = 65
FAILED_RUN_UUID = "d2d20381-85c5-4a2d-8680-a2134dc8854f"
rerun_url = f"https://scriptrun.ai/api/v1/workflows/{WORKFLOW_ID}/history/{FAILED_RUN_UUID}/re-run/"
headers = {
"X-Api-Key": API_KEY,
"Content-Type": "application/json"
}
# Re-run with updated fields (or omit data to reuse the original input_data)
replay_resp = requests.post(
rerun_url,
headers=headers,
data='{"category": "positive", "retry_count": 1}',
timeout=15
).json()
if replay_resp.get("status") == 201:
new_uuid = replay_resp["data"]["id"]
print(f"Replay started. Poll workflow_result with new UUID: {new_uuid}")
Sometimes a pipeline needs human review before running a sensitive action, such as sending an invoice or publishing a post. You can set this up with Agent nodes. When execution reaches an agent block, the run pauses and waits for sign-off. Your backend can then approve or reject the pending request through two routes:
-
Approve the step and continue: POST /api/v1/workflows/workflow_run/{workflow_run_id}/agent-approval/{request_id}/approve/
-
Reject the agent action: POST /api/v1/workflows/workflow_run/{workflow_run_id}/agent-approval/{request_id}/reject/
Per-node token cost audit and the SR token ledger
If a workflow chains three or four models together, a single total price at the end hides which prompt actually burned through your budget. You need to see what each individual block cost to run.
ScriptRun tracks every charge in both US dollars USD and its internal SR token ledger, where 1 SR equals $0.01 on standard plans. If you copy a ready-made workflow from the public Marketplace via POST /api/v1/workflows/marketplace/{slug}/add-from-marketplace/, the platform adds a Hidden Copy to your project. The author's internal prompts stay private, and the external_cost_usd object splits the run price into two numbers:
-
cost: total amount charged for the run, such as $0.002424.
-
commission: creator fee for the Marketplace template, such as $0.000764. Subtracting commission from cost gives you a net model execution cost of $0.001660.
To audit token billing history per workflow node via API, send a request to GET /api/v1/billing-history/workflowrun/{run_id}/. This route gives you a per-node token cost audit by returning a paginated list of charges for every step that ran:
import requests
API_KEY = "sr_live_your_api_key"
RUN_UUID = "0781b175-2135-45ec-9063-ad3e0d929adc"
billing_url = f"https://scriptrun.ai/api/v1/billing-history/workflowrun/{RUN_UUID}/"
params = {"page": 1, "size": 50}
headers = {"X-Api-Key": API_KEY}
ledger = requests.get(billing_url, headers=headers, params=params, timeout=15).json()
print(f"Total node charges recorded: {ledger.get('total')}")
for item in ledger.get("items", []):
node_name = item.get("description")
charge_status = item.get("status") # Failed nodes show status as "Error"
amounts = item.get("amount", {})
print(f"Node: {node_name} | Status: {charge_status} | Charge: {amounts}")
Each record in items includes the block name in description, the operation type in operation, the charge status in status where failed blocks show Error, and the amount dictionary in USD and SR. Checking step-by-step costs makes it easy to spot expensive prompts and switch those blocks to faster, cheaper models like gemini-2.5-flash-lite or deepseek-v4.1-flash without rebuilding the whole workflow.
🚀 Launch ready-made AI workflows from Marketplace
Key takeaways
Moving multi-step tasks from synchronous chat at /v1/chat/completions to background workflows at /api/v1/workflows/ avoids 60-second timeout errors and frees up your server threads. Keep client budgets separate through /api/v1/projects/ and send root-level JSON fields with the X-Api-Key header. When polling for results, wait until data.data is populated, and use the billing history endpoint to track costs step by step.
FAQs about asynchronous AI workflow API
Why does ScriptRun use both Authorization: Bearer and X-Api-Key headers?
The chat route /v1/chat/completions uses Authorization: Bearer <API_KEY> so standard OpenAI SDKs connect right away without changing client code. All other platform endpoints under /api/v1/projects/, /api/v1/workflows/, and /api/v1/billing-history/ use the X-Api-Key: <API_KEY> header.
Why does POST /api/v1/workflows/{id}/run/ return HTTP 200 when a workflow fails to start?
The web server always returns an HTTP 200 wrapper and puts the real startup status inside response["status"]. A value of 422 means one of the blocks failed input validation, such as a missing required field, with the exact error listed inside data.data. A successful launch always returns inner status 201.
Why is data.data sometimes empty right after workflow_result returns "succeed"?
The run status switches to "succeed" 1 to 2 seconds before all node outputs finish saving to the database, which the docs refer to as the temporal consistency window. If data.data is empty when you see "succeed", wait 2 seconds and call GET /api/v1/workflows/workflow_result/ again to grab the saved output.
Do I need to wrap workflow inputs inside an input_data object when using an API key?
No. When calling the API with an X-Api-Key header, pass your fields directly at the root of the JSON body as a flat JSON payload, such as {"user_name": "John"}. The {"input_data": {...}} wrapper is only used by browser sessions with JWT tokens.
What should I do if a model inside a node wraps its JSON reply in Markdown backticks?
Some models wrap JSON output inside ```json ... ``` code fences. Because the API returns result.content without changes, strip those backticks on the client side with the regex r"```(?:json)?\s*([\s\S]*?)\s*```" before calling json.loads().
How can I replay a failed workflow run without rebuilding the initial request?
Send a POST request to /api/v1/workflows/{id}/history/{run_id}/re-run/ with your X-Api-Key header and the failed run's UUID in the URL. Leave the request body empty, and the platform will automatically start a new run using the saved inputs from history.
Related posts
Zapier Alternatives: 8 Tools Compared on Price (2026)
Zapier alternatives compared: what each tool costs, how it counts usage, a 10,000-action cost example, and open-source and enterprise picks.
LLM Vision API: Processing Images and PDFs Across OpenAI, Claude, and Gemini
Run images and PDFs through OpenAI, Claude, and Gemini from one OpenAI-compatible LLM vision API. Includes Python and TypeScript base64 examples, 2026 token math, pre-resizing, JSON extraction, and async Workflow API batch jobs.
What Is OpenRouter? How It Works, Pricing and Limits (2026)
What is OpenRouter and should you use it? How the gateway works, what it costs, free limits, Auto Router and Fusion, privacy and who owns it.
OpenAI API Alternative: 8 Providers Compared for 2026
Eight OpenAI API alternatives compared on current prices, speed, context and what changes when you switch, with a checklist and a gateway option.








