API Reference

Error Handling

Understanding and handling Tork API errors in your applications.

Error Format

All API errors follow a consistent JSON format:

json
{
  "error": {
    "code": "policy_violation",
    "message": "Action blocked by policy: block-pii-sharing",
    "status": 403,
    "details": {
      "policy_name": "block-pii-sharing",
      "agent_id": "agent-123",
      "violation_type": "pii_detected"
    },
    "request_id": "req_abc123def456",
    "documentation_url": "https://docs.tork.network/errors/policy_violation"
  }
}

HTTP Status Codes

Standard HTTP status codes indicate the general category of error:

200Success - Request completed successfully
400Bad Request - Invalid parameters or malformed request
401Unauthorized - Missing or invalid API key
403Forbidden - Policy violation or insufficient permissions
404Not Found - Resource doesn't exist
409Conflict - Resource already exists or state conflict
422Unprocessable - Valid JSON but semantic errors
429Too Many Requests - Rate limit exceeded
500Internal Error - Server-side issue
503Service Unavailable - Temporary outage

Error Codes

Specific error codes for programmatic handling:

invalid_api_key

The API key provided is invalid or expired

Resolution: Check your API key in the dashboard

policy_violation

Action was blocked by a governance policy

Resolution: Review the policy or request an exception

budget_exceeded

The action would exceed the budget limit

Resolution: Wait for budget reset or increase limit

approval_required

Human approval is required for this action

Resolution: Wait for approval or check approval queue

circuit_breaker_open

Circuit breaker is in open state

Resolution: Wait for cooldown or manual reset

rate_limit_exceeded

Too many requests in the time window

Resolution: Implement backoff and retry

agent_not_found

The specified agent doesn't exist

Resolution: Register the agent first

invalid_policy

Policy configuration is invalid

Resolution: Check policy syntax and conditions

jailbreak_detected

Jailbreak attempt was detected

Resolution: Review the input content

pii_detected

PII was found in the content

Resolution: Redact PII before proceeding

Error Handling Examples

Best practices for handling errors in your code:

python
from tork_governance import TorkClient
from tork_governance.exceptions import (
    TorkAPIError,
    PolicyViolationError,
    BudgetExceededError,
    ApprovalRequiredError,
    RateLimitError
)

client = TorkClient()

try:
    result = client.policies.check(
        agent_id="agent-123",
        action_type="send_email",
        content="..."
    )
except PolicyViolationError as e:
    print(f"Policy blocked: {e.policy_name}")
    print(f"Reason: {e.message}")
    # Log for audit, notify user

except BudgetExceededError as e:
    print(f"Budget exceeded: {e.overage}")
    # Queue for later or request budget increase

except ApprovalRequiredError as e:
    print(f"Approval needed: {e.approval_id}")
    # Wait for approval or notify approvers

except RateLimitError as e:
    print(f"Rate limited, retry after: {e.retry_after}s")
    time.sleep(e.retry_after)
    # Retry the request

except TorkAPIError as e:
    print(f"API error: {e.code} - {e.message}")
    print(f"Request ID: {e.request_id}")
    # Log and handle gracefully

Retry Strategy

Implement exponential backoff for transient errors:

python
import time
from tork_governance.exceptions import TorkAPIError, RateLimitError

def with_retry(func, max_retries=3):
    """Execute function with exponential backoff."""
    for attempt in range(max_retries):
        try:
            return func()
        except RateLimitError as e:
            if attempt == max_retries - 1:
                raise
            wait = e.retry_after or (2 ** attempt)
            time.sleep(wait)
        except TorkAPIError as e:
            # Only retry on 5xx errors
            if e.status < 500 or attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)

# Usage
result = with_retry(lambda: client.policies.check(...))

Debugging: Always log the request_id from error responses. Include it when contacting support.

Documentation

Learn to integrate TORK

Upgrade Plan

Current: free

Support

Get help from our team