Learn how HITL.sh integrates with your existing systems, tools, and platforms to create seamless human-in-the-loop workflows
import requests class HITLClient: def __init__(self, api_key, base_url="https://api.hitl.sh/v1"): self.api_key = api_key self.base_url = base_url self.headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } def create_request(self, loop_id, data): response = requests.post( f"{self.base_url}/loops/{loop_id}/requests", headers=self.headers, json=data ) return response.json() def get_response(self, request_id): response = requests.get( f"{self.base_url}/requests/{request_id}/response", headers=self.headers ) return response.json()
def submit_content_for_review(content, loop_id): client = HITLClient(API_KEY) request_data = { "content": content.text, "content_type": "text", "priority": "normal", "ai_analysis": { "confidence": content.ai_confidence, "flags": content.ai_flags, "risk_score": content.risk_score }, "metadata": { "user_id": content.user_id, "timestamp": content.created_at.isoformat(), "source": "content_api" } } try: response = client.create_request(loop_id, request_data) return response["id"] except Exception as e: logger.error(f"Failed to submit request: {e}") raise
def process_human_decision(request_id): client = HITLClient(API_KEY) # Poll for response (in production, use webhooks instead) while True: response = client.get_response(request_id) if response and response.get("status") == "completed": decision = response["decision"] if decision == "approved": handle_approval(request_id, response) elif decision == "rejected": handle_rejection(request_id, response) elif decision == "needs_changes": handle_modification_request(request_id, response) break time.sleep(30) # Wait 30 seconds before checking again
def configure_webhook(loop_id, webhook_url): client = HITLClient(API_KEY) webhook_data = { "url": webhook_url, "events": ["request.completed", "request.escalated"], "loop_id": loop_id, "secret": generate_webhook_secret() } response = client.create_webhook(webhook_data) return response["id"]
from flask import Flask, request, jsonify import hmac import hashlib app = Flask(__name__) WEBHOOK_SECRET = "your_webhook_secret" @app.route('/webhooks/hitl', methods=['POST']) def handle_hitl_webhook(): # Verify webhook signature signature = request.headers.get('X-HITL-Signature') if not verify_signature(request.data, signature): return jsonify({"error": "Invalid signature"}), 401 payload = request.json event_type = payload["event"] if event_type == "request.completed": process_completed_request(payload["data"]) elif event_type == "request.escalated": handle_escalation(payload["data"]) return jsonify({"status": "success"}), 200 def verify_signature(payload, signature): expected_signature = hmac.new( WEBHOOK_SECRET.encode(), payload, hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected_signature, signature) def process_completed_request(data): request_id = data["request_id"] decision = data["decision"] # Process the human decision if decision == "approved": approve_content(request_id) elif decision == "rejected": reject_content(request_id)
class HITLIntegration { constructor(apiKey, baseUrl) { this.apiKey = apiKey; this.baseUrl = baseUrl; } async submitForReview(content, loopId) { const response = await fetch(`${this.baseUrl}/loops/${loopId}/requests`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ content: content.text, content_type: 'text', priority: 'normal' }) }); return response.json(); } async checkStatus(requestId) { const response = await fetch(`${this.baseUrl}/requests/${requestId}/status`, { headers: { 'Authorization': `Bearer ${this.apiKey}` } }); return response.json(); } } // Usage in your application const hitl = new HITLIntegration(API_KEY, 'https://api.hitl.sh/v1'); document.getElementById('submit-button').addEventListener('click', async () => { const content = document.getElementById('content-input').value; const request = await hitl.submitForReview(content, 'loop_123'); // Show pending status showPendingStatus(request.id); // Poll for completion pollForCompletion(request.id); });
# Django integration example from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json class HITLService: def __init__(self, api_key): self.client = HITLClient(api_key) def submit_content_review(self, content, user_id): """Submit content for human review""" request_data = { "content": content, "content_type": "text", "priority": "normal", "metadata": { "user_id": str(user_id), "timestamp": timezone.now().isoformat() } } response = self.client.create_request("content_moderation", request_data) return response["id"] def handle_webhook(self, payload): """Process webhook notifications""" event_type = payload["event"] if event_type == "request.completed": self.process_completed_request(payload["data"]) elif event_type == "request.escalated": self.handle_escalation(payload["data"]) # Django view for webhook handling @csrf_exempt def hitl_webhook(request): if request.method == 'POST': payload = json.loads(request.body) hitl_service = HITLService(settings.HITL_API_KEY) hitl_service.handle_webhook(payload) return JsonResponse({"status": "success"}) return JsonResponse({"error": "Method not allowed"}, status=405)
Asynchronous Processing
Batch Operations
Caching
Connection Pooling