Inferensys

Prompt

Long-Running Tool Status Polling Prompt Template

A practical prompt playbook for using Long-Running Tool Status Polling Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user profile, required context, and explicit boundaries for the long-running tool status polling prompt.

This prompt is for agent developers who need to manage tool calls with unknown or variable completion times. Instead of blocking the agent loop, this prompt instructs the model to decide when to poll for status, how to interpret progress signals, when to escalate a stalled tool, and when to terminate the polling loop. Use this when your agent orchestrates long-running operations such as report generation, model training jobs, batch data processing, or any external API that returns a job ID and requires status checks. This prompt assumes you have a check_tool_status function available and that the agent operates in a loop where it can act on the polling decision.

Do not use this prompt for synchronous tool calls that return results within a single request cycle, or for streaming tools that push incremental results without polling. It is also inappropriate when the agent has no ability to store state across loop iterations, or when the tool's status endpoint does not provide structured progress information. If the long-running operation requires human approval at specific checkpoints, pair this prompt with a human-in-the-loop approval prompt rather than embedding approval logic directly into the polling loop. For tools that return partial results during execution, use the Streaming Tool Partial-Result Handling Prompt Template instead.

Before implementing this prompt, ensure you have defined the polling tool's contract: the input parameters (such as job ID), the expected status schema (including terminal states like completed, failed, cancelled), and any rate limits. The prompt works best when the agent has access to a check_tool_status function that returns structured JSON with at minimum a status field and optionally progress_percentage, error_message, and result fields. Wire this prompt into your agent loop so that the model's polling decision—whether to continue polling, escalate, or terminate—directly controls the next iteration's behavior.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Long-Running Tool Status Polling Prompt Template works and where it introduces risk. Use these cards to decide whether this prompt fits your agent architecture before wiring it into production.

01

Good Fit: Async Jobs with Unknown Duration

Use when: your agent triggers a tool that returns a job ID and requires polling for completion. Guardrail: the prompt must produce polling intervals that adapt to the tool's observed response time, not a fixed loop.

02

Bad Fit: Sub-Second Synchronous Calls

Avoid when: the tool completes in under 500ms. Risk: polling adds unnecessary latency, token burn, and loop overhead. Guardrail: wrap the tool in a synchronous timeout before falling back to the polling prompt.

03

Required Input: Tool Status Contract

What to watch: the prompt needs a defined status schema (e.g., pending, running, completed, failed). Guardrail: validate the tool's status endpoint returns a machine-readable state enum before deploying the polling prompt. Ambiguous status strings cause infinite loops.

04

Operational Risk: Unbounded Polling Loops

Risk: a stalled tool with no timeout produces infinite polling, burning tokens and compute. Guardrail: the prompt must include explicit max-poll-count and max-wall-clock-time constraints, with escalation to a human or dead-letter queue on breach.

05

Operational Risk: Stale Progress Interpretation

Risk: the model misinterprets a stuck progress percentage as forward motion and continues polling. Guardrail: the prompt must track progress deltas across polls and escalate when progress stalls for N consecutive intervals.

06

Bad Fit: Tools Without Idempotent Status Endpoints

Avoid when: polling the status endpoint mutates state or has side effects. Risk: each poll advances or corrupts the job. Guardrail: verify the status endpoint is a safe read-only GET before using this prompt; otherwise, use a webhook or callback pattern instead.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A system prompt that teaches an agent to poll long-running tools, interpret status responses, and decide when to wait, escalate, or fail.

This prompt template gives an agent explicit rules for managing tool calls with unknown completion times. Instead of assuming a synchronous response, the agent learns to inspect status payloads, respect polling intervals, detect stalls, and terminate loops cleanly. Replace the square-bracket placeholders with your specific tool names, status schemas, timeout values, and escalation policies before deploying.

text
You are an agent that invokes long-running tools and polls their status until completion or timeout.

Available tools:
- [TOOL_NAME]: initiates the long-running operation. Accepts [INPUT_SCHEMA]. Returns a tracking ID.
- [STATUS_TOOL_NAME]: checks the status of a running operation. Accepts a tracking ID. Returns a JSON object matching [STATUS_SCHEMA].

When you call [TOOL_NAME], follow these rules:

1. POLLING INTERVAL
   - Start with an initial poll delay of [INITIAL_DELAY_SECONDS] seconds.
   - If the status is [PENDING_STATUS_VALUE], wait [POLL_INTERVAL_SECONDS] seconds before polling again.
   - If the tool returns a [RETRY_AFTER_HEADER], use that value as the next delay.
   - Never poll more frequently than [MIN_POLL_INTERVAL_SECONDS] seconds.

2. STATUS INTERPRETATION
   - [COMPLETED_STATUS_VALUE]: extract the result from [RESULT_FIELD_PATH] and present it to the user.
   - [FAILED_STATUS_VALUE]: extract the error from [ERROR_FIELD_PATH], classify it as retryable or fatal, and act according to [ERROR_CLASSIFICATION_RULES].
   - [PROGRESS_STATUS_VALUE]: report progress to the user using [PROGRESS_MESSAGE_TEMPLATE]. Continue polling.
   - [STALLED_STATUS_VALUE]: if the status hasn't changed for [STALL_THRESHOLD_SECONDS] seconds, escalate according to [ESCALATION_POLICY].

3. TERMINATION CONDITIONS
   - Stop polling after [MAX_POLL_ATTEMPTS] attempts and report a timeout to the user.
   - Stop polling if total elapsed time exceeds [MAX_TOTAL_SECONDS] seconds.
   - If the user sends an interrupt command ([INTERRUPT_COMMAND]), cancel the operation by calling [CANCEL_TOOL_NAME] and report the cancellation.

4. OUTPUT FORMAT
   - On completion, return the result in [OUTPUT_SCHEMA] format.
   - On failure, return an error object with { "error_type": "...", "message": "...", "retryable": true/false, "tracking_id": "..." }.
   - On timeout, return { "error_type": "timeout", "message": "Operation did not complete within [MAX_TOTAL_SECONDS]s", "tracking_id": "..." }.

5. RESOURCE CLEANUP
   - After completion, failure, timeout, or cancellation, call [CLEANUP_TOOL_NAME] if defined in [CLEANUP_POLICY].
   - Log the final state to [LOGGING_CHANNEL] with the tracking ID, total attempts, and total elapsed time.

To adapt this template, start by mapping your tool's real status values into the placeholder slots. If your tool returns RUNNING instead of PENDING, replace [PENDING_STATUS_VALUE] with "RUNNING". Define [STALL_THRESHOLD_SECONDS] based on your tool's observed behavior—set it to 3x the normal progress interval. For high-risk operations, wire [ESCALATION_POLICY] to a human approval queue rather than an automated retry. Test the prompt with status payloads that include unexpected fields, missing fields, and malformed JSON to verify the agent doesn't hallucinate completion. Before production, add an eval that asserts the agent stops polling after exactly [MAX_POLL_ATTEMPTS] attempts and never exceeds [MAX_TOTAL_SECONDS].

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. Fill these from your agent runtime context, tool registry, and execution state.

PlaceholderPurposeExampleValidation Notes

[TOOL_NAME]

Identifies the specific long-running tool being polled

batch_export_job

Must match a registered tool ID in the agent's tool registry; reject if tool is not async-capable

[JOB_ID]

Unique identifier for the specific tool execution instance

exp_8a7b3c2d-4e5f

Must be a non-empty string; validate format against tool's ID schema; reject null or empty

[POLLING_INTERVAL_SECONDS]

Base interval between status checks in seconds

5

Must be an integer between 1 and 300; validate range; reject values that would exceed rate limits

[MAX_POLLING_DURATION_SECONDS]

Hard deadline for total polling time before escalation

600

Must be an integer greater than [POLLING_INTERVAL_SECONDS]; reject if less than or equal to interval

[STATUS_ENDPOINT]

The tool's status-check endpoint or method signature

/v1/jobs/{job_id}/status

Must be a valid URI or fully qualified method name; validate against tool contract schema

[TERMINAL_STATUSES]

List of status values that indicate completion, success, or failure

['completed', 'failed', 'cancelled']

Must be a non-empty array of strings; each value must exist in the tool's documented status enum

[HEARTBEAT_TIMEOUT_SECONDS]

Maximum silence before assuming the tool is unresponsive

30

Must be an integer less than [MAX_POLLING_DURATION_SECONDS]; reject if greater than max duration

[ESCALATION_ACTION]

Action to take when polling exceeds max duration or heartbeat is lost

notify_oncall_channel

Must reference a valid escalation handler registered in the agent runtime; reject unrecognized actions

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the polling prompt into an agent loop with validation, retries, state management, and termination guards.

This prompt is not a standalone chat interaction; it is a decision module inside a polling loop. The agent invokes a long-running tool, receives an initial status handle or job ID, and then enters a loop where this prompt is called on each tick. The prompt's job is to interpret the raw tool status response, decide the next polling interval, detect completion or failure, and produce a structured decision object that the surrounding harness can act on. The harness owns the actual sleep/delay, the tool invocation, and the loop termination logic. The prompt owns the interpretation and recommendation.

The implementation harness should wrap this prompt in a function with a strict contract: input: { tool_name, job_id, status_payload, elapsed_time_ms, max_timeout_ms, previous_attempts } and output: { decision: 'poll' | 'complete' | 'escalate' | 'abandon', next_poll_ms: number | null, progress_summary: string, confidence: 0-1, escalation_reason: string | null }. Validate the output schema before acting on it. If the model returns decision: 'poll' but next_poll_ms is missing or zero, default to a configured floor (e.g., 2000ms). If decision: 'complete' but the status payload indicates an error state, flag a schema-semantic mismatch and re-prompt with the contradiction highlighted. Log every decision with the raw status payload, the model's reasoning, and the harness action taken. This trace is essential for debugging polling loops that spin forever or terminate early.

The harness must enforce hard loop boundaries that the prompt cannot override. Maintain a max_total_polls cap (e.g., 60 attempts) and a wall-clock max_timeout_ms. If either is exceeded, force decision: 'escalate' regardless of the model's output. Similarly, implement exponential backoff clamping: if the model requests next_poll_ms: 100 but the tool's documented rate limit is 1000ms, the harness should clamp to the safe minimum. The prompt can recommend aggressive polling, but the harness enforces the contract. For high-stakes workflows where a false completion signal could cause downstream data loss, insert a human review gate when confidence < 0.85 or when the status payload contains error codes the model has not seen before.

Wire this into an agent framework as a tool-call post-processor. After the agent invokes start_long_running_job, the framework spawns a polling coroutine that calls this prompt module on a timer. The coroutine yields structured status updates back to the agent's context so the agent can communicate progress to the user. When the polling loop terminates with decision: 'complete', return the final result to the agent. On escalate, surface the escalation_reason and the full polling trace to a human operator or a supervisor agent. On abandon, clean up any resources associated with the job ID and log the abandonment reason. Never let the polling loop block the agent's main turn loop; use async/await or background threads so the agent remains responsive to user interrupts and cancellation signals.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the model's JSON decision when polling a long-running tool. Use this contract to parse, validate, and act on the agent's polling decision before the next tool call.

Field or ElementType or FormatRequiredValidation Rule

polling_decision

enum: poll | wait | escalate | abort

Must be exactly one of the four allowed values. Reject any other string.

next_poll_interval_seconds

integer

Must be >= 1 and <= 3600. Required when polling_decision is 'poll' or 'wait'. Null allowed for 'escalate' and 'abort'.

status_interpretation

string

Must be a non-empty string summarizing the current tool status. Max 500 characters. Reject empty or whitespace-only strings.

progress_percentage

integer | null

If present, must be an integer between 0 and 100 inclusive. Null allowed when progress is unknown or not reported by the tool.

heartbeat_healthy

boolean

Must be true or false. True indicates the tool responded within the expected heartbeat window. False triggers escalation logic.

escalation_reason

string | null

Required when polling_decision is 'escalate' or 'abort'. Must be a non-empty string <= 200 characters. Null allowed otherwise.

stall_detected

boolean

Must be true or false. True indicates no progress change across [STALL_THRESHOLD_COUNT] consecutive polls. Triggers escalation regardless of heartbeat.

resource_cleanup_required

boolean

Must be true or false. True indicates the agent should release handles, close connections, or cancel the tool call. Required for 'abort' decisions.

PRACTICAL GUARDRAILS

Common Failure Modes

Production failures in long-running tool status polling often stem from unbounded loops, stale state, and silent timeouts. These cards cover the most frequent breakages and the operational guardrails that prevent them.

01

Infinite Polling Loop

What to watch: The agent enters an unbounded polling loop because the tool never returns a terminal status (e.g., COMPLETED or FAILED). This burns tokens, saturates rate limits, and eventually times out the agent run. Guardrail: Enforce a hard max_polling_attempts and a total wall-clock deadline. If either is exceeded, the agent must escalate or return a degraded result with the last known status.

02

Stale Status Interpretation

What to watch: The agent misinterprets a transient status like QUEUED or IN_PROGRESS as a terminal failure or success. This causes premature finalization or incorrect error handling. Guardrail: Maintain an explicit allowlist of terminal states. The agent must continue polling for any status not on that list. Log every status transition for traceability.

03

Missing Progress Context

What to watch: The agent receives a progress percentage or message but fails to surface it to the user, leaving them blind during a long wait. This erodes trust and prevents manual intervention. Guardrail: Require the prompt to extract and relay human-readable progress on every poll cycle. Include a last_progress_summary field in the agent's working state.

04

Heartbeat vs. Completion Confusion

What to watch: The agent treats a successful heartbeat or keep-alive response as a completed result, or vice versa. This leads to truncated outputs or unnecessary retries. Guardrail: Separate the heartbeat check from the result check in the prompt logic. Heartbeat failures should trigger a connection health path, not a result-finalization path.

05

Resource Leak on Abandonment

What to watch: The agent stops polling due to a timeout or error but never sends a cancellation signal to the external tool. The backend job continues running, consuming resources and potentially locking records. Guardrail: The prompt must include a cleanup step on any exit path. Before finalizing, the agent must attempt to cancel the remote job and verify the cancellation was received.

06

Silent Polling Interval Collapse

What to watch: Under backpressure or retry logic, the agent reduces the polling interval to zero or near-zero, effectively hammering the status endpoint. This causes rate limiting and cascading failures. Guardrail: Define a minimum polling interval floor. The agent must never poll faster than this floor, even during retry storms. Implement exponential backoff on status-check failures, not just on invocation failures.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these test cases against your long-running tool status polling prompt to validate polling interval decisions, progress interpretation, heartbeat monitoring, and escalation triggers before shipping.

CriterionPass StandardFailure SignalTest Method

Polling interval decision with known ETA

Prompt selects interval ≤ [MAX_INTERVAL_SECONDS] and ≥ [MIN_INTERVAL_SECONDS] when tool reports ETA within [ACCEPTABLE_RANGE]

Interval exceeds max, falls below min, or prompt ignores provided ETA entirely

Feed mock tool status with explicit ETA field; parse interval from output; assert bounds

Progress percentage interpretation

Prompt correctly maps [PROGRESS_FIELD] value to one of [PROGRESS_STATES] and does not claim completion when progress < 100

Output declares done when progress < 100, or misclassifies stalled as in-progress

Provide status payloads at 0%, 50%, 99%, 100%; check state label and completion flag

Heartbeat timeout detection

Prompt triggers escalation when [LAST_HEARTBEAT_AGE] exceeds [HEARTBEAT_TIMEOUT_SECONDS]

Prompt continues polling silently after heartbeat timeout or escalates prematurely

Inject status with stale heartbeat timestamp; verify escalation action appears in output

Stalled tool escalation trigger

Prompt escalates when progress unchanged for [STALL_THRESHOLD_SECONDS] and tool is not in a known waiting state

Prompt loops indefinitely on stalled progress or escalates on first unchanged poll

Feed sequence of identical progress values across multiple poll cycles; check escalation decision

Polling loop termination on terminal state

Prompt emits terminal action when tool status matches any value in [TERMINAL_STATES] and does not schedule another poll

Output schedules another poll after terminal state or fails to recognize completion

Provide status with terminal state value; assert no next_poll_interval field and action is terminal

Resource cleanup instruction generation

Prompt includes cleanup action when tool reaches terminal state or escalation, referencing [RESOURCE_IDS] from context

Cleanup action missing, references wrong resource IDs, or fires during active polling

Verify output contains cleanup action with correct resource references only in terminal/escalation paths

Error state classification

Prompt distinguishes transient errors from fatal errors using [ERROR_CLASSIFICATION_RULES] and adjusts retry behavior accordingly

Prompt retries fatal errors, abandons transient errors, or ignores error codes entirely

Inject status with error codes from both categories; verify retry decision and error classification label

Partial result salvage on timeout

Prompt extracts and preserves [PARTIAL_RESULT_FIELDS] when escalating due to timeout, marking them with incomplete flag

Partial results discarded, marked as complete, or missing required fields

Trigger timeout escalation; check output for partial result payload with incomplete=true and all required fields present

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base polling loop prompt but relax strict schema enforcement. Use a simple polling interval of [BASE_INTERVAL_SECONDS] with linear backoff. Accept natural-language status summaries instead of structured JSON.

code
You are monitoring a long-running tool call with ID [TOOL_CALL_ID].
Current status: [STATUS_RESPONSE]
Elapsed time: [ELAPSED]

Decide next action: POLL, ESCALATE, or COMPLETE.
If POLL, suggest next poll delay in seconds.
If ESCALATE, explain why.
If COMPLETE, summarize the result.

Watch for

  • Infinite polling loops when the tool never reaches a terminal state
  • Missing timeout ceiling causing runaway cost
  • No distinction between "still running" and "stuck"
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.