Гадаад API (External API)
OpenAgentAGI нь workflow гүйцэтгэлийн логийг асууж авах, мөн workflow дуусах үед бодит цагийн мэдэгдэл авах webhook-уудыг тохируулах боломжтой, иж бүрэн гадаад API-г санал болгодог.
Authentication
Бүх API хүсэлтүүд нь x-api-key header-д дамжуулсан API түлхүүрийг заавал шаарддаг:
curl -H "x-api-key: YOUR_API_KEY" \
https://www.openagentagi.com/api/v1/logs?workspaceId=YOUR_WORKSPACE_IDYou can generate API keys from your user settings in the OpenAgentAGI dashboard.
Logs API
All API responses include information about your workflow execution limits and usage:
"limits": {
"workflowExecutionRateLimit": {
"sync": {
"limit": 60, // Max sync workflow executions per minute
"remaining": 58, // Remaining sync workflow executions
"resetAt": "..." // When the window resets
},
"async": {
"limit": 60, // Max async workflow executions per minute
"remaining": 59, // Remaining async workflow executions
"resetAt": "..." // When the window resets
}
},
"usage": {
"currentPeriodCost": 1.234, // Current billing period usage in USD
"limit": 10, // Usage limit in USD
"plan": "pro", // Current subscription plan
"isExceeded": false // Whether limit is exceeded
}
}Note: The rate limits in the response body are for workflow executions. The rate limits for calling this API endpoint are in the response headers (X-RateLimit-*).
Query Logs
Query workflow execution logs with extensive filtering options.
GET /api/v1/logsRequired Parameters:
workspaceId- Your workspace ID
Optional Filters:
workflowIds- Comma-separated workflow IDsfolderIds- Comma-separated folder IDstriggers- Comma-separated trigger types:api,webhook,schedule,manual,chatlevel- Filter by level:info,errorstartDate- ISO timestamp for date range startendDate- ISO timestamp for date range endexecutionId- Exact execution ID matchminDurationMs- Minimum execution duration in millisecondsmaxDurationMs- Maximum execution duration in millisecondsminCost- Minimum execution costmaxCost- Maximum execution costmodel- Filter by AI model used
Pagination:
limit- Results per page (default: 100)cursor- Cursor for next pageorder- Sort order:desc,asc(default: desc)
Detail Level:
details- Response detail level:basic,full(default: basic)includeTraceSpans- Include trace spans (default: false)includeFinalOutput- Include final output (default: false)
{
"data": [
{
"id": "log_abc123",
"workflowId": "wf_xyz789",
"executionId": "exec_def456",
"level": "info",
"trigger": "api",
"startedAt": "2025-01-01T12:34:56.789Z",
"endedAt": "2025-01-01T12:34:57.123Z",
"totalDurationMs": 334,
"cost": {
"total": 0.00234
},
"files": null
}
],
"nextCursor": "eyJzIjoiMjAyNS0wMS0wMVQxMjozNDo1Ni43ODlaIiwiaWQiOiJsb2dfYWJjMTIzIn0",
"limits": {
"workflowExecutionRateLimit": {
"sync": {
"limit": 60,
"remaining": 58,
"resetAt": "2025-01-01T12:35:56.789Z"
},
"async": {
"limit": 60,
"remaining": 59,
"resetAt": "2025-01-01T12:35:56.789Z"
}
},
"usage": {
"currentPeriodCost": 1.234,
"limit": 10,
"plan": "pro",
"isExceeded": false
}
}
}Get Log Details
Retrieve detailed information about a specific log entry.
GET /api/v1/logs/{id}{
"data": {
"id": "log_abc123",
"workflowId": "wf_xyz789",
"executionId": "exec_def456",
"level": "info",
"trigger": "api",
"startedAt": "2025-01-01T12:34:56.789Z",
"endedAt": "2025-01-01T12:34:57.123Z",
"totalDurationMs": 334,
"workflow": {
"id": "wf_xyz789",
"name": "My Workflow",
"description": "Process customer data"
},
"executionData": {
"traceSpans": [...],
"finalOutput": {...}
},
"cost": {
"total": 0.00234,
"tokens": {
"prompt": 123,
"completion": 456,
"total": 579
},
"models": {
"gpt-4o": {
"input": 0.001,
"output": 0.00134,
"total": 0.00234,
"tokens": {
"prompt": 123,
"completion": 456,
"total": 579
}
}
}
},
"limits": {
"workflowExecutionRateLimit": {
"sync": {
"limit": 60,
"remaining": 58,
"resetAt": "2025-01-01T12:35:56.789Z"
},
"async": {
"limit": 60,
"remaining": 59,
"resetAt": "2025-01-01T12:35:56.789Z"
}
},
"usage": {
"currentPeriodCost": 1.234,
"limit": 10,
"plan": "pro",
"isExceeded": false
}
}
}
}Get Execution Details
Retrieve execution details including the workflow state snapshot.
GET /api/v1/logs/executions/{executionId}{
"executionId": "exec_def456",
"workflowId": "wf_xyz789",
"workflowState": {
"blocks": {...},
"edges": [...],
"loops": {...},
"parallels": {...}
},
"executionMetadata": {
"trigger": "api",
"startedAt": "2025-01-01T12:34:56.789Z",
"endedAt": "2025-01-01T12:34:57.123Z",
"totalDurationMs": 334,
"cost": {...}
}
}Webhook Subscriptions
Workflow execution дуусах үед бодит цагийн мэдэгдэл авах боломжийг олгоно. Webhook-уудыг workflow editor доторх OpenAgentAGI UI-ээр дамжуулан тохируулна.
Configuration
Webhook-уудыг workflow бүрийн хувьд workflow editor UI-ээр дамжуулан тохируулж болно. Control bar дээрх webhook icon дээр дарж webhook subscription-оо тохируулна.
Боломжит тохиргооны сонголтууд:
url: Таны webhook endpoint URLsecret: HMAC гарын үсгийг баталгаажуулахад ашиглах нэмэлт secretincludeFinalOutput: Workflow-ийн эцсийн үр дүнг payload-д оруулахincludeTraceSpans: Гүйцэтгэлийн дэлгэрэнгүй trace span-уудыг оруулахincludeRateLimits: Workflow эзэмшигчийн rate limit мэдээллийг оруулахincludeUsageData: Workflow эзэмшигчийн хэрэглээ болон billing мэдээллийг оруулахlevelFilter: Хүлээн авах log түвшнүүдийн массив (info,error)triggerFilter: Хүлээн авах trigger төрлүүдийн массив (api,webhook,schedule,manual,chat)active: Webhook subscription-ийг идэвхжүүлэх / идэвхгүй болгох
Webhook Payload
Workflow execution дуусах үед OpenAgentAGI таны webhook URL руу POST хүсэлт илгээнэ:
{
"id": "evt_123",
"type": "workflow.execution.completed",
"timestamp": 1735925767890,
"data": {
"workflowId": "wf_xyz789",
"executionId": "exec_def456",
"status": "success",
"level": "info",
"trigger": "api",
"startedAt": "2025-01-01T12:34:56.789Z",
"endedAt": "2025-01-01T12:34:57.123Z",
"totalDurationMs": 334,
"cost": {
"total": 0.00234,
"tokens": {
"prompt": 123,
"completion": 456,
"total": 579
},
"models": {
"gpt-4o": {
"input": 0.001,
"output": 0.00134,
"total": 0.00234,
"tokens": {
"prompt": 123,
"completion": 456,
"total": 579
}
}
}
},
"files": null,
"finalOutput": {...}, // Only if includeFinalOutput=true
"traceSpans": [...], // Only if includeTraceSpans=true
"rateLimits": {...}, // Only if includeRateLimits=true
"usage": {...} // Only if includeUsageData=true
},
"links": {
"log": "/v1/logs/log_abc123",
"execution": "/v1/logs/executions/exec_def456"
}
}Webhook Headers
Webhook бүрийн хүсэлт дараах header-үүдийг агуулна:
openagentagi-event: Event-ийн төрөл (үргэлжworkflow.execution.completed)openagentagi-timestamp: Миллисекундээр илэрхийлсэн Unix timestampopenagentagi-delivery-id: Idempotency-д зориулсан давтагдашгүй delivery IDopenagentagi-signature: Баталгаажуулалтад ашиглах HMAC-SHA256 гарын үсэг (secret тохируулсан бол)Idempotency-Key: Давхардлыг илрүүлэхэд ашиглах, delivery ID-тэй ижил утгатай
Signature Verification
Хэрэв та webhook secret тохируулсан бол, webhook нь OpenAgentAGI-ээс ирсэн эсэхийг баталгаажуулахын тулд гарын үсгийг шалгана уу:
import crypto from 'crypto';
function verifyWebhookSignature(body, signature, secret) {
const [timestampPart, signaturePart] = signature.split(',');
const timestamp = timestampPart.replace('t=', '');
const expectedSignature = signaturePart.replace('v1=', '');
const signatureBase = `${timestamp}.${body}`;
const hmac = crypto.createHmac('sha256', secret);
hmac.update(signatureBase);
const computedSignature = hmac.digest('hex');
return computedSignature === expectedSignature;
}
// In your webhook handler
app.post('/webhook', (req, res) => {
const signature = req.headers['openagentagi-signature'];
const body = JSON.stringify(req.body);
if (!verifyWebhookSignature(body, signature, process.env.WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
// Process the webhook...
});import hmac
import hashlib
import json
def verify_webhook_signature(body: str, signature: str, secret: str) -> bool:
timestamp_part, signature_part = signature.split(',')
timestamp = timestamp_part.replace('t=', '')
expected_signature = signature_part.replace('v1=', '')
signature_base = f"{timestamp}.{body}"
computed_signature = hmac.new(
secret.encode(),
signature_base.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(computed_signature, expected_signature)
# In your webhook handler
@app.route('/webhook', methods=['POST'])
def webhook():
signature = request.headers.get('openagentagi-signature')
body = json.dumps(request.json)
if not verify_webhook_signature(body, signature, os.environ['WEBHOOK_SECRET']):
return 'Invalid signature', 401
# Process the webhook...Retry Policy
Амжилтгүй болсон webhook илгээлтүүдийг экспоненциал backoff болон jitter ашиглан дахин оролдоно:
- Дахин оролдох дээд тоо: 5
- Дахин оролдох хоцролтууд: 5 секунд, 15 секунд, 1 минут, 3 минут, 10 минут
- Jitter: “thundering herd” үзэгдлээс сэргийлэхийн тулд 10% хүртэл нэмэлт хоцролт
- Зөвхөн HTTP 5xx болон 429 хариунууд дахин оролтыг өдөөдөг
- Илгээлтүүд 30 секундын дараа timeout болно
Webhook илгээлтүүд асинхрон байдлаар боловсруулагддаг бөгөөд workflow гүйцэтгэлийн гүйцэтгэлд нөлөөлөхгүй.
Best Practices
-
Polling Strategy: Логуудыг polling хийхдээ
order=ascболонstartDate-тай cursor-д суурилсан pagination ашиглаж, шинэ логийг үр ашигтай татаж аваарай. -
Webhook Security: Заавал webhook secret тохируулж, гарын үсгийг баталгаажуулан хүсэлтүүд OpenAgentAGI-ээс ирж буйг шалгаарай.
-
Idempotency: Давхардсан webhook илгээлтийг илрүүлж, зөв зохицуулахын тулд
Idempotency-Keyheader ашиглаарай. -
Privacy: Анхдагчаар
finalOutputболонtraceSpansнь хариунаас хасагдсан байдаг. Зөвхөн өгөгдөл хэрэгтэй бөгөөд нууцлалын үр дагаврыг ойлгож байгаа тохиолдолд л идэвхжүүлээрэй. -
Rate Limiting: 429 хариу авсан тохиолдолд экспоненциал backoff хэрэгжүүлж, санал болгож буй хүлээлгийн хугацааг
Retry-Afterheader-ээс шалгаарай.
Rate Limiting
API нь шударга хэрэглээг хангахын тулд rate limiting хэрэгжүүлдэг:
- Free plan: минутанд 10 хүсэлт
- Pro plan: минутанд 30 хүсэлт
- Team plan: минутанд 60 хүсэлт
- Enterprise plan: Custom хязгаарууд
Rate limit-ийн мэдээлэл нь response header-үүдэд багтана:
X-RateLimit-Limit: Нэг цонхонд зөвшөөрөгдөх хамгийн их хүсэлтX-RateLimit-Remaining: Одоогийн цонхонд үлдсэн хүсэлтийн тооX-RateLimit-Reset: Цонх дахин эхлэх ISO timestamp
Example: Polling for New Logs
let cursor = null;
const workspaceId = 'YOUR_WORKSPACE_ID';
const startDate = new Date().toISOString();
async function pollLogs() {
const params = new URLSearchParams({
workspaceId,
startDate,
order: 'asc',
limit: '100'
});
if (cursor) {
params.append('cursor', cursor);
}
const response = await fetch(
`https://www.openagentagi.com/api/v1/logs?${params}`,
{
headers: {
'x-api-key': 'YOUR_API_KEY'
}
}
);
if (response.ok) {
const data = await response.json();
// Process new logs
for (const log of data.data) {
console.log(`New execution: ${log.executionId}`);
}
// Update cursor for next poll
if (data.nextCursor) {
cursor = data.nextCursor;
}
}
}
// Poll every 30 seconds
setInterval(pollLogs, 30000);Example: Processing Webhooks
import express from 'express';
import crypto from 'crypto';
const app = express();
app.use(express.json());
app.post('/openagentagi-webhook', (req, res) => {
// Verify signature
const signature = req.headers['openagentagi-signature'];
const body = JSON.stringify(req.body);
if (!verifyWebhookSignature(body, signature, process.env.WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
// Check timestamp to prevent replay attacks
const timestamp = parseInt(req.headers['openagentagi-timestamp']);
const fiveMinutesAgo = Date.now() - (5 * 60 * 1000);
if (timestamp < fiveMinutesAgo) {
return res.status(401).send('Timestamp too old');
}
// Process the webhook
const event = req.body;
switch (event.type) {
case 'workflow.execution.completed':
const { workflowId, executionId, status, cost } = event.data;
if (status === 'error') {
console.error(`Workflow ${workflowId} failed: ${executionId}`);
// Handle error...
} else {
console.log(`Workflow ${workflowId} completed: ${executionId}`);
console.log(`Cost: $${cost.total}`);
// Process successful execution...
}
break;
}
// Return 200 to acknowledge receipt
res.status(200).send('OK');
});
app.listen(3000, () => {
console.log('Webhook server listening on port 3000');
});