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

These errors come from the Tork REST API, so you branch on the error.code in the response body. There is no Python cloud SDK — @torknetwork/sdk is npm-only, and tork-governance on PyPI decides on-device, so it returns a verdict rather than raising API errors. Handle the REST responses directly:

python
import os
import time
import requests

# There is no Python cloud SDK — use the REST API.
TORK_API_KEY = os.environ["TORK_API_KEY"]

response = requests.post(
    "https://tork.network/api/v1/govern",
    headers={
        "Authorization": f"Bearer {TORK_API_KEY}",
        "Content-Type": "application/json",
    },
    json={"content": "..."},
)

if response.ok:
    result = response.json()
else:
    error = response.json().get("error", {})
    code = error.get("code")

    if code == "policy_violation":
        print(f"Policy blocked: {error.get('message')}")
        # Log for audit, notify user

    elif code == "budget_exceeded":
        print("Budget exceeded")
        # Queue for later or request a budget increase

    elif code == "approval_required":
        print(f"Approval needed: {error.get('details', {}).get('approval_id')}")
        # Wait for approval or notify approvers

    elif code == "rate_limit_exceeded":
        # Honour Retry-After when the server sends it
        wait = int(response.headers.get("Retry-After", 1))
        print(f"Rate limited, retry after: {wait}s")
        time.sleep(wait)

    else:
        print(f"API error {response.status_code}: {code} - {error.get('message')}")

    # Always log the request_id — support needs it to trace the call
    print(f"Request ID: {error.get('request_id')}")

Retry Strategy

Implement exponential backoff for transient errors:

python
import time
import requests

def with_retry(send, max_retries=3):
    """Send a Tork API request, retrying 429s and 5xx with backoff."""
    for attempt in range(max_retries):
        response = send()

        if response.status_code == 429:
            if attempt == max_retries - 1:
                return response
            wait = int(response.headers.get("Retry-After", 2 ** attempt))
            time.sleep(wait)
            continue

        # Only retry server-side failures; 4xx will not succeed on replay
        if response.status_code >= 500:
            if attempt == max_retries - 1:
                return response
            time.sleep(2 ** attempt)
            continue

        return response

    return response

# Usage
response = with_retry(lambda: requests.post(
    "https://tork.network/api/v1/govern",
    headers={"Authorization": f"Bearer {TORK_API_KEY}"},
    json={"content": "..."},
))

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