Asynchronous Batch API, Background Runs, Polling, and Cancellation
How to submit long agent jobs in the background or via JSONL batch files, poll status, stream with reconnect, cancel runs, and download results.
This page summarises Perplexity documentation on running Agent API work without holding an open HTTP connection: background mode for single long agentic runs, and the Batch API for large sets of requests from a JSONL file. It also notes how Cloudflare Workers AI batches inference in one call. Unrelated items in the same documentation set (browser chat UIs, unrelated download helpers) are out of scope here.
When to use background mode vs Batch API vs synchronous calls
Section titled “When to use background mode vs Batch API vs synchronous calls”Background mode fits one run that may take minutes—deep research, heavy sandbox work, or multi-step tool use—when your client must not time out or drop the connection. Batch API fits many independent Agent API requests that do not need an immediate answer: evaluations, classification, enrichment, or offline research over a dataset. A normal synchronous call (no background, no batch file) is appropriate when you need the full result in the same HTTP response and the run is short.
| Pattern | Best for | You get back | Typical follow-up |
|---|---|---|---|
| Synchronous Agent API | Interactive, short runs | Output in the create response | None |
background: true |
One long run | Response id immediately; results via poll or stream |
GET /v1/agent/{id} |
| Batch API | Thousands of similar runs | Batch id; output/error JSONL files |
Poll batch; download files |
Perplexity states that batch requests do not count toward Agent API request rate limits, though token rate limits still apply and failed token-limit hits are retried inside the batch. See Batch API.
Cloudflare’s Workers AI batch path is narrower: you send a collection of inference requests in one call, the platform queues them, and you poll by request_id later—suited to summarization or embeddings at scale without live user interaction.
Background mode: submit a long run without timeouts
Section titled “Background mode: submit a long run without timeouts”Background mode runs long agentic tasks asynchronously: you submit with background=true, store the response id, then poll (or stream) for the result while execution continues on the server even if the client disconnects.
Run long agentic tasks asynchronously — submit with background, poll by response id, stream, reconnect, and cancel.
— Perplexity, Background Mode
Long agentic runs, such as deep research or heavy sandbox work, can take several minutes. Background mode runs these tasks asynchronously so your application can avoid timeouts and dropped connections: submit the run, store its response id, then poll for the result. The run continues server-side even if your client disconnects.
— Perplexity, Background Mode
background=true: how to create a background Agent API request
Section titled “background=true: how to create a background Agent API request”Set background=true on POST https://api.perplexity.ai/v1/agent (or the SDK equivalent). The create call returns a Response object immediately with an id and an initial status (for example queued).
For multi-step research, set max_steps when you do not set an effort level—a direct-model run defaults to one step, which is too few for multi-step work. See Background Mode — Submit a background request.
curl https://api.perplexity.ai/v1/agent \ -H "Authorization: Bearer $PERPLEXITY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.6-sol", "input": "Research the current EV charging market and summarize the main segments.", "tools": [{ "type": "web_search" }, { "type": "sandbox" }], "max_steps": 10, "background": true }' | jq '{id, status}'Poll GET /v1/agent/{id} until terminal status
Section titled “Poll GET /v1/agent/{id} until terminal status”Poll with Retrieve Agent Response (GET https://api.perplexity.ai/v1/agent/{id}). A background response is non-terminal while status is queued or in_progress. It is terminal when status is completed, failed, cancelled, or incomplete (incomplete means the run stopped before finishing, for example on truncation).
After the loop, branch on the final state: read output for completed, inspect error for failed, treat cancelled as intentional stop, and treat incomplete as an unfinished run.
Background stream: stream=true, sequence_number, and reconnect
Section titled “Background stream: stream=true, sequence_number, and reconnect”You can stream a long background run by setting both background=true and stream=true. Track sequence_number on each streamed event as a cursor. Token pause notices (response.paused and response.resumed) have no sequence_number—do not advance the cursor on those events.
If the connection drops, reconnect with GET /v1/agent/{id}?stream=true&starting_after=N to resume after sequence number N. Reconnect is only valid within the response’s reconnect window; if it expires, the endpoint returns 400 and you should fall back to a plain GET /v1/agent/{id} for the final snapshot. Details are in Background Mode — Stream and reconnect and Output Control — Background Runs.
Cancel a background response with POST /v1/agent/{id}/cancel
Section titled “Cancel a background response with POST /v1/agent/{id}/cancel”Cancel an in-flight background response when the result is no longer needed using Cancel Agent Response. Cancellation is asynchronous: HTTP 200 returns status: "cancelling" and the run stops shortly after—poll GET /v1/agent/{id} until status is the terminal cancelled. Cancelling an already-terminal response returns 400; unknown id or another account’s response returns 404.
Requests cancellation of response
{id}. Acts on durable state, so it works for background runs that outlive the client connection.— Perplexity, Cancel Agent Response
Batch API: JSONL upload, batch lifecycle, and result files
Section titled “Batch API: JSONL upload, batch lifecycle, and result files”The Perplexity Batch API runs many Agent API requests asynchronously from a UTF-8 JSONL file: upload, create a batch, poll the batch, then download output and error files when processing finishes.
The Batch API runs many Agent API requests asynchronously. You upload a JSONL file of requests, create a batch from it, poll the batch, and download an output file when it finishes.
— Perplexity, Batch API
Use it for work that does not need an immediate answer. Each line runs the full Agent API loop, so built-in tools such as web_search work inside a batch. The Batch and Files endpoints follow the shape of OpenAI’s Batch API. Batch is available to every API organization except organizations with zero data retention; batch inputs and outputs are kept 30 days. See Batch API — Overview.
Upload input with POST /v1/files and create with POST /v1/batches
Section titled “Upload input with POST /v1/files and create with POST /v1/batches”-
Upload a JSONL input file with Upload a file:
POST /v1/fileswithpurpose=batch. The service validates every line before storing. Files expire after 30 days;expires_afteris not supported and is rejected with 400. -
Create a batch with Create a batch:
POST /v1/batcheswithinput_file_idandendpoint: "/v1/responses". The batch starts invalidating. Send anIdempotency-Keyheader so retries return the original batch. -
Poll with Retrieve a batch until the batch reaches a final status, then download
output_file_idanderror_file_idvia Download file content.
Batch request rules: model, tools, and rejected fields
Section titled “Batch request rules: model, tools, and rejected fields”Every line must use the same model. stream: true is rejected. background, store, and service_tier are ignored—every batch request already runs in the background, is stored, and uses the tier described in billing. Built-in tools are allowed; function, connector, and advisor tools are rejected at upload with 400. Requests using an anthropic/* model must include max_output_tokens on each line or the error file records a 400 validation failure. Full rules are in Batch API — Supported requests.
Batch status, expires_at, and per-request errors
Section titled “Batch status, expires_at, and per-request errors”Batch-level statuses include validating, in_progress, finalizing, and finals completed, expired, cancelling, cancelled, and failed. See Batch API — Batch statuses.
| Batch status | Meaning (short) |
|---|---|
validating |
Created; requests being queued |
in_progress |
Requests running |
finalizing |
Writing output/error files |
completed |
Final; batch not cancelled; no batch-level expiry failure |
expired |
Final; at least one request hit the 48h deadline |
cancelled / cancelling |
User cancel in progress or done |
failed |
Batch itself could not be processed |
Batches target completion within 24 hours (completion_window); that is a target, not a guarantee. The hard deadline is expires_at, 48 hours after creation. Requests not started or waiting for capacity at the deadline expire with batch_expired and are not billed; requests already running continue and bill normally. See Batch API — Timing and expiry.
Per-request errors land in the error file with codes such as batch_expired, batch_cancelled, poll_timeout (single run over 30 minutes), response_too_large (over 20 MB), and response_unavailable. See Batch API — Error file format.
Cancel batch with POST /v1/batches/{batch_id}/cancel
Section titled “Cancel batch with POST /v1/batches/{batch_id}/cancel”Cancel while the batch is validating or in_progress using Cancel a batch. Completed lines stay in the output file and are billed. Running lines may finish briefly after cancel (often up to about a minute); stopped lines go to the error file with batch_cancelled. Cancelling a batch that is finalizing, completed, expired, or failed returns 409. Operational detail is in Batch API — Cancel a batch.
Batch limits, retention, and unfinished-request caps
Section titled “Batch limits, retention, and unfinished-request caps”| Limit | Value |
|---|---|
| Requests per file | 50,000 |
| File size | 200 MB |
| Line size | 4 MB |
| Combined output + error files | 8 GB (batch ends failed if exceeded) |
| Input/output/error file retention | 30 days |
Unfinished batch request count per organization depends on usage tier (from 50,000 at Tier 0 up to 1,000,000 at Tier 6+). Exceeding the cap returns 429—wait for earlier batches or use a smaller file. See Batch API — Limits and Batch API — Files and retention.
store, previous_response_id, and durable conversation state
Section titled “store, previous_response_id, and durable conversation state”Background and batch runs often pair with multi-turn flows. The Agent API persists conversation state server-side so you can retrieve responses or continue with previous_response_id.
Retrieval: GET /v1/agent/{id} returns 404 for responses created with store: false, even though those responses can still be continuation sources. For responses you must retrieve reliably, create them with background: true (or store omitted/true). See Conversation state — Retrieve a response and Retrieve Agent Response.
Continuation: previous_response_id must reference a completed prior response from the same account; otherwise the API returns 400. Send only the new user turn in input. See Conversation state — Resume from a prior response and Keep context.
Alternatively, replay prior turns yourself in the input array when you need to summarize, redact, or reorder context—at the cost of resending history each call. See Conversation state — Replay conversation turns yourself.
Sandbox share_file outputs: list and download by response id
Section titled “Sandbox share_file outputs: list and download by response id”When sandbox code writes a file and delivers it with share_file, bytes are not inline. List with GET /v1/agent/{id}/files and download with GET /v1/agent/{id}/files/{file_id}/content (raw bytes, not JSON). The file_id is distinct from the response id. See Working with Files, List Agent Response Files, and Download Agent Response File.
Long sandbox jobs should use background=true and poll before listing files, as described in Sandbox — Running in the background.
Batch files under /v1/files with purpose=batch or batch_output are separate from per-response sandbox files. See Working with Files — Overview and Batch API — Files and retention.
Cloudflare Workers AI asynchronous batch inference
Section titled “Cloudflare Workers AI asynchronous batch inference”For Workers AI (not the Perplexity Agent API), batch processing queues a collection of inference requests from one call and returns a request_id for later polling—useful for summarization or embeddings without human interaction.
Asynchronous batch processing lets you send a collection (batch) of inference requests in a single call. Instead of expecting immediate responses for every request, the system queues them for processing and returns the results later.
— Cloudflare, Asynchronous Batch API
Using the batch API will guarantee that your requests are fulfilled eventually, rather than erroring out if Cloudflare does not have enough capacity at a given time.
— Cloudflare, Asynchronous Batch API
When you send a batch request, the API acknowledges receipt with a status such as queued and a unique request_id for polling. Keep the total payload under 10 MB. You can use the Batch API from a Worker with the AI binding, the REST API, or a template—see Asynchronous Batch API.
Common conclusion: both Perplexity and Cloudflare separate submission from result delivery for heavy AI work: acknowledge quickly, process asynchronously, and use an id plus polling (and Perplexity adds batch files, stream reconnect, and explicit cancel endpoints for agent runs).
Common mistakes when polling batch and background jobs
Section titled “Common mistakes when polling batch and background jobs”Practical failures called out in Perplexity’s batch cookbook and API docs:
- Resubmitting a background run after a token-rate pause instead of continuing to poll the same
id. - Upload validation: blank lines, two different
modelvalues,stream: true, disallowed tools, or oversizedcustom_idcause 400 on upload with the first bad line named—nothing is stored. See Enrich a CSV — Troubleshooting. - Idempotency-Key misuse: reusing a key with a different body returns 400 on batch create. See Create a batch.
- HTTP 402: credits exhausted—a running batch may pause unstarted requests until credits return; the batch deadline does not move. See Enrich a CSV — Troubleshooting.
- Expired files: after 30 days,
GET /v1/files/{file_id}/contentreturns 404—download batch output beforeexpires_at. See Download file content. - Assuming
store: falseblocks continuation: retrieval returns 404, butprevious_response_idstill works. See Conversation state — Storage behavior.
How to check this on your site
Section titled “How to check this on your site”- Submit a small test with
background: truevia Background Mode, then confirmGET https://api.perplexity.ai/v1/agent/{id}moves fromqueued/in_progressto a terminal status using Retrieve Agent Response. - Upload a two-line JSONL file with Upload a file, create a batch with Create a batch, and poll Retrieve a batch until
statusis final. - Download batch output with Download file content and reconcile
request_counts.completed/failedwith line counts in the JSONL files, per Batch API — Batch statuses. - If you use sandbox file output, list files with List Agent Response Files and fetch bytes with Download Agent Response File.
- You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about so it can be corrected.