Tasks API
Execute agents asynchronously and retrieve results via the Tasks API.
Overview
Tasks represent asynchronous agent executions. When you create a task, it’s queued for processing, and you can poll for completion or use webhooks (coming soon).
Task Flow
- Create Task - Submit parameters to an agent endpoint
- Queue - Task enters processing queue
- Execute - Agent processes your request
- Complete - Results available via GET request
Billing
- Upfront charge: Balance deducted when task is created
- Refund on failure: Full refund if agent execution fails
- Usage tracking: All charges logged in transactions
Create Task
Execute an agent by creating a new task.
POST /api/tasksAuthentication
Requires either:
- API key via
Authorization: Bearer YOUR_API_KEYheader - Active session (for browser-based requests)
Request Body
{
"endpointId": "endpoint_123",
"params": {
"text": "Analyze this text",
"options": {
"detail": "high"
}
},
"connectorIds": ["conn_hubspot_abc"]
}| Field | Type | Required | Description |
|---|---|---|---|
endpointId | string | Yes | ID of the agent endpoint to execute |
params | object | Yes | Parameters required by the agent endpoint |
connectorIds | string[] | No | Connected services to make available to the agent |
Response
{
"taskId": "task_abc123xyz",
"status": "pending",
"message": "Task queued successfully"
}| Field | Type | Description |
|---|---|---|
taskId | string | Unique task identifier for polling |
status | string | Initial status (always “pending”) |
message | string | Confirmation message |
Status Codes
200 OK- Task created successfully400 Bad Request- Invalid request (missing fields, invalid params)401 Unauthorized- Missing or invalid authentication403 Forbidden- Insufficient balance or permissions404 Not Found- Agent endpoint not found429 Too Many Requests- Rate limit exceeded (10/min)
Example Requests
cURL
curl -X POST https://agents.zazmic.com/api/tasks \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"endpointId": "endpoint_123",
"params": {
"text": "Analyze sentiment in this text"
}
}'Python
import requests
response = requests.post(
"https://agents.zazmic.com/api/tasks",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"endpointId": "endpoint_123",
"params": {"text": "Analyze sentiment"}
}
)
task = response.json()
print(f"Task ID: {task['taskId']}")JavaScript
const response = await fetch('https://agents.zazmic.com/api/tasks', {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
endpointId: 'endpoint_123',
params: { text: 'Analyze sentiment' }
})
});
const task = await response.json();
console.log('Task ID:', task.taskId);Get Task
Retrieve task status and results.
GET /api/tasks/:taskIdPath Parameters
| Parameter | Type | Description |
|---|---|---|
taskId | string | Task ID returned from create task |
Response
{
"id": "task_abc123xyz",
"userId": "user_123",
"agentId": "agent_456",
"endpointId": "endpoint_789",
"status": "completed",
"request": {
"text": "Analyze sentiment"
},
"response": {
"sentiment": "positive",
"confidence": 0.95,
"details": "The text expresses strong positive sentiment..."
},
"error": null,
"costUsd": "0.0500",
"createdAt": "2024-01-15T10:30:00.000Z",
"startedAt": "2024-01-15T10:30:01.000Z",
"completedAt": "2024-01-15T10:30:05.000Z"
}Status Values
| Status | Description |
|---|---|
pending | Task queued, not yet processing |
processing | Agent is currently executing |
completed | Success - results in response field |
failed | Execution failed - error in error field |
Large Data Handling
For requests/responses >16KB, data is stored in Google Cloud Storage:
{
"id": "task_abc123",
"status": "completed",
"request": "{ truncated preview... }",
"requestUri": "gs://bucket/requests/user_123/task_abc123.json",
"response": "{ truncated preview... }",
"responseUri": "gs://bucket/responses/task_abc123.json"
}Use the requestUri and responseUri signed URLs to download full data.
Example Requests
cURL
curl https://agents.zazmic.com/api/tasks/task_abc123 \
-H "Authorization: Bearer YOUR_API_KEY"Python with Polling
import requests
import time
def wait_for_task(task_id, max_wait=300, poll_interval=2):
"""Poll task until completion or timeout"""
start_time = time.time()
while time.time() - start_time < max_wait:
response = requests.get(
f"https://agents.zazmic.com/api/tasks/{task_id}",
headers={"Authorization": f"Bearer {API_KEY}"}
)
task = response.json()
if task["status"] == "completed":
return task["response"]
elif task["status"] == "failed":
raise Exception(f"Task failed: {task['error']}")
time.sleep(poll_interval)
raise TimeoutError(f"Task did not complete within {max_wait} seconds")
# Usage
result = wait_for_task("task_abc123")
print(result)JavaScript with Polling
async function waitForTask(taskId, maxWait = 300000, pollInterval = 2000) {
const startTime = Date.now();
while (Date.now() - startTime < maxWait) {
const response = await fetch(
`https://agents.zazmic.com/api/tasks/${taskId}`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const task = await response.json();
if (task.status === 'completed') {
return task.response;
} else if (task.status === 'failed') {
throw new Error(`Task failed: ${task.error}`);
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error(`Task did not complete within ${maxWait}ms`);
}
// Usage
const result = await waitForTask('task_abc123');
console.log(result);List Tasks
Retrieve all tasks for the authenticated user.
GET /api/tasksQuery Parameters
| Parameter | Type | Description |
|---|---|---|
status | string | Filter by status (pending, processing, completed, failed) |
agentId | string | Filter by agent ID |
limit | number | Max results to return (default: 50, max: 100) |
offset | number | Pagination offset (default: 0) |
Response
{
"tasks": [
{
"id": "task_abc123",
"agentId": "agent_456",
"status": "completed",
"costUsd": "0.0500",
"createdAt": "2024-01-15T10:30:00.000Z",
"completedAt": "2024-01-15T10:30:05.000Z"
},
{
"id": "task_xyz789",
"agentId": "agent_456",
"status": "pending",
"costUsd": "0.0500",
"createdAt": "2024-01-15T10:31:00.000Z"
}
],
"total": 42,
"limit": 50,
"offset": 0
}Example
# Get all completed tasks
curl "https://agents.zazmic.com/api/tasks?status=completed&limit=10" \
-H "Authorization: Bearer YOUR_API_KEY"Error Responses
Insufficient Balance
{
"error": "Insufficient balance",
"message": "Your balance ($5.00) is insufficient for this task ($10.00). Please add credits.",
"statusCode": 403
}Rate Limit Exceeded
{
"error": "Rate limit exceeded",
"message": "You have exceeded the rate limit of 10 requests per minute",
"statusCode": 429
}Invalid Endpoint
{
"error": "Not found",
"message": "Agent endpoint not found",
"statusCode": 404
}Task Execution Failed
{
"id": "task_abc123",
"status": "failed",
"error": {
"code": "AGENT_ERROR",
"message": "Agent execution failed: Connection timeout",
"details": "..."
},
"createdAt": "2024-01-15T10:30:00.000Z",
"completedAt": "2024-01-15T10:35:00.000Z"
}Best Practices
Polling Strategy
- Initial delay: Wait 2-3 seconds before first poll
- Interval: Poll every 2-5 seconds
- Timeout: Set reasonable timeout (5-10 minutes)
- Exponential backoff: Increase interval after multiple polls
Error Handling
def execute_task_with_retry(endpoint_id, params, max_retries=3):
for attempt in range(max_retries):
try:
# Create task
response = requests.post(
"https://agents.zazmic.com/api/tasks",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"endpointId": endpoint_id, "params": params}
)
response.raise_for_status()
# Wait for completion
task_id = response.json()["taskId"]
result = wait_for_task(task_id)
return result
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429: # Rate limit
time.sleep(60) # Wait 1 minute
continue
elif e.response.status_code == 403: # Insufficient balance
raise Exception("Please add credits to your account")
else:
raise
raise Exception(f"Failed after {max_retries} attempts")Next Steps
- Learn about Sessions for stateful interactions
- Try Chat for streaming conversations
- Review Error Handling