Triggering Agents with Webhooks
Agent Webhooks provide a powerful mechanism to trigger an agentโs execution from external systems. Unlike the direct API which provides an immediate response, webhooks are designed for asynchronous operations. When you call a webhook, DocsGPT enqueues the agentโs task for background processing and immediately returns a task_id. You then use this ID to poll for the result.
This workflow is ideal for integrating with services that expect a quick initial response (e.g., form submissions) or for triggering long-running tasks without tying up a client connection.
Each agent has its own unique webhook URL. Generate it in the agentโs Access Details (the builderโs More actions menu), or with GET /api/agent_webhook?id=<agent_id>. The URL contains a secret token, and anyone who has the URL can run the agent; see Keep the URL secret. A workflow agentโs webhook runs its saved graph, so a draft whose workflow isnโt finished gets no URL: the request answers 400 with the graph rules it breaks.
API Endpoints
- Webhook URL:
http://localhost:7091/api/webhooks/agents/{AGENT_WEBHOOK_TOKEN} - Task Status URL:
http://localhost:7091/api/task_status
For DocsGPT Cloud, use https://gptcloud.arc53.com/ as the base URL.
Both endpoints are also in the REST API reference and in your instanceโs own Swagger UI (see the API overview).
The Webhook Workflow
The process involves two main steps: triggering the task and polling for the result.
Step 1: Trigger the Webhook
Send an HTTP POST request to the agentโs unique webhook URL with the required payload. The structure of this payload should match what the agentโs prompt and tools are designed to handle.
- Method:
POST, with a JSON body andContent-Type: application/json. Another content type returns415; a body that isnโt valid JSON, or isnull, returns400. - Response:
{"success": true, "task_id": "a1b2c3d4-e5f6-..."}
The whole JSON body becomes the agentโs input, serialized as JSON text; no field has a special meaning to the agent. (The agentโs sources are searched with the bodyโs text fields; see How a webhook run behaves.) The request {"question": "Summarize order 4567"} reaches the agent as the message {"question": "Summarize order 4567"}, so write the agentโs prompt to expect the payload your system sends. Non-ASCII text reaches it as written ({"question": "Rรฉsumรฉ"}), not as \u00e9 escapes; the agentโs input guardrails scan the payload as that message.
curl -X POST \
http://localhost:7091/api/webhooks/agents/your_webhook_token \
-H "Content-Type: application/json" \
-d '{"question": "Your message to agent"}'import requests
WEBHOOK_URL = "http://localhost:7091/api/webhooks/agents/your_webhook_token"
payload = {"question": "Your message to agent"}
try:
response = requests.post(WEBHOOK_URL, json=payload)
response.raise_for_status()
task_id = response.json().get("task_id")
print(f"Task successfully created with ID: {task_id}")
except requests.exceptions.RequestException as e:
print(f"Error triggering webhook: {e}")const webhookUrl = 'http://localhost:7091/api/webhooks/agents/your_webhook_token';
const payload = { question: 'Your message to agent' };
async function triggerWebhook() {
try {
const response = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) throw new Error(`HTTP error! ${response.status}`);
const data = await response.json();
console.log(`Task successfully created with ID: ${data.task_id}`);
return data.task_id;
} catch (error) {
console.error('Error triggering webhook:', error);
}
}
triggerWebhook();Triggering with GET (query parameters)
The webhook listener also accepts GET requests, mapping the query string to the payload. This is handy for systems that can only issue a simple GET (for example a โping this URLโ integration):
curl "http://localhost:7091/api/webhooks/agents/your_webhook_token?question=Your+message+to+agent"As with POST, the response is a JSON object containing the task_id, and the query parameters, as a JSON object, become the agentโs input.
Preventing duplicate triggers (Idempotency-Key)
To make a trigger safe to retry, send an optional Idempotency-Key header. If the same key is seen again within 24 hours, DocsGPT does not enqueue a second task โ it returns the original task_id instead. This prevents a retried or double-fired webhook from running the agent twice. If the response is "task_id": "deduplicated" instead, a request with the same key was being enqueued at the same moment and its record is already gone, most likely because that enqueue failed, so the agent may not have run at all. There is no task to poll (/api/task_status answers 404 for it): send the request again.
curl -X POST \
http://localhost:7091/api/webhooks/agents/your_webhook_token \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-4567-created" \
-d '{"question": "Your message to agent"}'Step 2: Poll for the Result
Once you have the task_id, periodically send a GET request to the /api/task_status endpoint until the task status is SUCCESS or FAILURE.
status: The current state of the task:PENDING,PROGRESS,SUCCESSorFAILURE(Celery can also reportSTARTEDorRETRY).result:{"current": <percent>}while the status isPROGRESS, the outcome when it isSUCCESS, and the error text when it isFAILURE.
A successful run nests the agentโs output under result.result:
{
"status": "SUCCESS",
"result": {
"status": "success",
"result": {
"answer": "Order 4567 shipped on May 2...",
"sources": [],
"tool_calls": [],
"thought": ""
}
}
}When the agentโs own limit is reached, the agent does not run, but the task still ends with SUCCESS: check result.status. A run that reaches the limit part way stops before its next model call and returns the same status, with what it did so far under result.
{
"status": "SUCCESS",
"result": {"status": "quota_exceeded", "error": "..."}
}While outside access is paused, the task ends the same way with "status": "agent_paused": the usage quota of the person who pays for the agentโs outside access is used up (before the run or part way, with what it did so far under result), the payerโs account is deactivated or, on a team agent, the payer is no longer an Admin there. The error says only that the agent is paused, never whose quota or how much is used. A team agent with nobody to pay for its outside access ends with "status": "no_payer". See Who pays.
A run that takes longer than WEBHOOK_RUN_TIMEOUT (default 600 seconds) is stopped, and the task also ends with SUCCESS, with "status": "timeout". Anything the agent did before it was stopped, such as a tool action, has already taken effect. On a self-hosted instance, raise the setting if your agent legitimately needs longer.
{
"status": "SUCCESS",
"result": {"status": "timeout", "error": "The run exceeded WEBHOOK_RUN_TIMEOUT and was stopped."}
}While a task is PENDING, /api/task_status returns 503 if no worker answers; a PENDING task and no reachable worker usually means the worker isnโt running.
The task_id is the only credential the poll needs, so keep it as private as the webhook URL. /api/task_status answers 404 for an id it doesnโt know, or once the result has expired (7 days after the trigger).
Two more cases to handle:
- A run that fails inside the agent still ends
SUCCESS. When the model or a workflow node reports an error during the run, the task finishes with"status": "success"and an empty or partialanswer; the error itself is not in the result. An emptyanswerusually means the run failed; the agentโs logs in DocsGPT (Settings > Logs) show why. - A crashed run is not retried. If the run raises an error (for example the model provider is unreachable), the task ends
FAILUREand the agent does not run again on its own: a retry would repeat any tool actions that already took effect. To try again, send the webhook again, with a newIdempotency-Keyif you set one. If the worker process itself dies mid-run (a restart or a deploy), the task is delivered again and the agent runs from the start.
# Replace the task_id with the one you received
curl http://localhost:7091/api/task_status?task_id=YOUR_TASK_IDimport requests
import time
STATUS_URL = "http://localhost:7091/api/task_status"
task_id = "YOUR_TASK_ID"
while True:
response = requests.get(STATUS_URL, params={"task_id": task_id})
data = response.json()
status = data.get("status")
print(f"Current task status: {status}")
if status == "SUCCESS":
outcome = data["result"]
if outcome.get("status") == "success":
print(outcome["result"]["answer"])
else:
print(f"Agent did not run: {outcome}")
break
if status == "FAILURE":
print(f"Run failed: {data.get('result')}")
break
time.sleep(2)const statusUrl = 'http://localhost:7091/api/task_status';
const taskId = 'YOUR_TASK_ID';
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function pollForResult() {
while (true) {
const response = await fetch(`${statusUrl}?task_id=${taskId}`);
const data = await response.json();
const status = data.status;
console.log(`Current task status: ${status}`);
if (status === 'SUCCESS') {
const outcome = data.result;
if (outcome.status === 'success') {
console.log(outcome.result.answer);
} else {
console.log('Agent did not run:', outcome);
}
break;
}
if (status === 'FAILURE') {
console.log('Run failed:', data.result);
break;
}
await sleep(2000);
}
}
pollForResult();How a webhook run behaves
A webhook run happens in the background, with nobody watching it. While it runs, the agentโs owner sees it under Running in Activity โ Now:
- It acts as the agentโs owner. Tools use the ownerโs connected accounts and saved credentials. A webhook is the ownerโs own automation, so the API write allowlist that limits API-key and widget callers does not apply to it.
- Nobody can approve. A tool action that needs approval is refused, and the agent is told so and carries on. So are client-side tools and tools whose connection needs signing in again.
- Wikis are read-only unless their owner allows outside edits. Anyone with the URL decides the runโs input, so the agent edits a wiki source only when the wikiโs owner turned on Let API and widget users edit this wiki. It can always read the wiki.
- Sources are searched with the payloadโs text, not the whole payload. An agent that searches its sources before it answers (a classic agent does) searches them with the payloadโs human-written fields: the values of
question,query,prompt,title,subject,summary,name,description,body,text,messageandcontent, from the top three levels of the payload (and the first five items of each list). Each distinct value is used once, and the search is cut at 2,000 characters. A payload without any of those fields is searched with its JSON, cut the same way. Searching with the raw JSON would match on keys, ids and URLs rather than on what the event is about. The agent still receives the whole payload. - Chat-only tools are unavailable. The
schedulertool is not offered to the agent during a webhook run. - Usage counts against the quota of whoever pays for the agentโs outside access. On a personal agent that is its owner; on a team agent, the Admin who turned outside access on or took it over. When it is used up, the run is skipped (see the
agent_pausedresult above).
Keep the URL secret
The token in the URL is the only credential: anyone who has the URL can run the agent as its owner, with the ownerโs accounts and quota. The token never changes and there is no way to rotate it yet, so treat the URL like a password: keep it out of client-side code and logs, and call it only from systems you control. If it leaks, the only way to stop it is to delete the agent. You can export the agent first, delete it and import the file again; the new agent gets a new webhook URL.
Last updated on
๐ OpenAI-Compatible API
Connect any OpenAI-compatible client to DocsGPT Agents via /v1/chat/completions โ streaming, structured output, files and images, tool calling, reasoning, and idempotent retries.
๐ก Realtime Events
Subscribe to DocsGPT's server-sent events channel for live notifications โ ingestion progress, tool approvals, MCP OAuth completion โ and reconnect to an in-flight chat answer.