# Create Agent Source: https://docs.rotavision.com/api-reference/dastavez/create-agent POST /dastavez/agents Create a browser automation agent ## Request Human-readable name for the agent. Description of the agent's purpose. Agent capabilities: * `navigate` - Navigate to URLs * `click` - Click elements * `type` - Type text into inputs * `extract` - Extract data from pages * `screenshot` - Take screenshots * `download` - Download files * `login` - Handle authentication * `captcha` - Solve simple captchas Stored credentials for authentication. Unique key to reference this credential. Credential type: `basic`, `form`, `oauth`. Username or email. Password (encrypted at rest). Agent configuration. Default timeout for actions. Browser viewport size. Custom user agent string. Proxy server URL. ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/dastavez/agents \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "name": "GST Portal Agent", "description": "Fetches GST returns and invoices from GST portal", "capabilities": ["navigate", "login", "extract", "download", "screenshot"], "credentials": [ { "key": "gst_portal", "type": "form", "username": "gstin@company.com", "password": "encrypted_password" } ], "config": { "timeout_ms": 60000, "viewport": {"width": 1920, "height": 1080} } }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() agent = client.dastavez.create_agent( name="GST Portal Agent", description="Fetches GST returns and invoices from GST portal", capabilities=["navigate", "login", "extract", "download", "screenshot"], credentials=[ { "key": "gst_portal", "type": "form", "username": "gstin@company.com", "password": "encrypted_password" } ], config={ "timeout_ms": 60000, "viewport": {"width": 1920, "height": 1080} } ) print(f"Agent ID: {agent.id}") ``` ```json 201 - Created theme={null} { "id": "agent_xyz789", "name": "GST Portal Agent", "description": "Fetches GST returns and invoices from GST portal", "status": "ready", "capabilities": ["navigate", "login", "extract", "download", "screenshot"], "credentials": [ { "key": "gst_portal", "type": "form", "username": "gstin@company.com" } ], "config": { "timeout_ms": 60000, "viewport": {"width": 1920, "height": 1080} }, "created_at": "2026-02-01T10:00:00Z" } ``` # Extract Document Source: https://docs.rotavision.com/api-reference/dastavez/extract-document POST /dastavez/extract Extract structured data from Indian documents ## Request Type of document: * `aadhaar` - Aadhaar card * `pan` - PAN card * `voter_id` - Voter ID card * `passport` - Indian passport * `driving_license` - Driving license * `bank_statement` - Bank account statement * `itr` - Income Tax Return * `form_16` - Form 16 * `gst_invoice` - GST invoice * `salary_slip` - Salary slip * `auto` - Auto-detect document type Document file (multipart upload). Supports PDF, PNG, JPG, TIFF. URL to document file. Either `file` or `file_url` required. Extraction options. Mask sensitive fields (Aadhaar number, account numbers). Extract photo from ID documents. Validate checksums and formats. Hint for document language: `hi`, `en`, `ta`, etc. Auto-enhance low-quality images. URL for completion webhook. ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/dastavez/extract \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "document_type": "aadhaar", "file_url": "https://storage.example.com/docs/aadhaar-123.pdf", "options": { "mask_sensitive": true, "extract_photo": true, "validate": true } }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() # From URL result = client.dastavez.extract( document_type="aadhaar", file_url="https://storage.example.com/docs/aadhaar-123.pdf", options={ "mask_sensitive": True, "extract_photo": True } ) # From file with open("aadhaar.pdf", "rb") as f: result = client.dastavez.extract( document_type="aadhaar", file=f, options={"mask_sensitive": True} ) print(f"Name: {result.fields['name']}") print(f"Name (English): {result.fields['name_english']}") ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; import fs from 'fs'; const client = new Rotavision(); // From URL const result = await client.dastavez.extract({ documentType: 'aadhaar', fileUrl: 'https://storage.example.com/docs/aadhaar-123.pdf', options: { maskSensitive: true, extractPhoto: true } }); console.log(`Name: ${result.fields.name}`); console.log(`Name (English): ${result.fields.nameEnglish}`); ``` ```json 200 - Aadhaar theme={null} { "id": "extract_abc123", "document_type": "aadhaar", "status": "completed", "confidence": 0.97, "fields": { "name": "राहुल शर्मा", "name_english": "Rahul Sharma", "dob": "1990-05-15", "gender": "Male", "aadhaar_number": "XXXX-XXXX-1234", "address": { "full": "123, MG Road, Koramangala, Bangalore - 560034", "line1": "123, MG Road", "line2": "Koramangala", "city": "Bangalore", "state": "Karnataka", "pincode": "560034" }, "issue_date": "2019-03-20" }, "validation": { "checksum_valid": true, "format_valid": true, "verhoeff_check": "pass" }, "photo": { "url": "https://storage.rotavision.com/photos/extract_abc123.jpg", "expires_at": "2026-02-02T10:30:00Z" }, "metadata": { "pages": 1, "file_type": "pdf", "processing_time_ms": 1250 }, "created_at": "2026-02-01T10:30:00Z" } ``` ```json 200 - PAN Card theme={null} { "id": "extract_def456", "document_type": "pan", "status": "completed", "confidence": 0.98, "fields": { "name": "RAHUL SHARMA", "father_name": "VIJAY SHARMA", "dob": "1990-05-15", "pan_number": "ABCDE1234F" }, "validation": { "checksum_valid": true, "format_valid": true }, "created_at": "2026-02-01T10:30:00Z" } ``` ```json 200 - GST Invoice theme={null} { "id": "extract_ghi789", "document_type": "gst_invoice", "status": "completed", "confidence": 0.95, "fields": { "invoice_number": "INV-2026-001234", "invoice_date": "2026-01-15", "seller": { "name": "ABC Electronics Pvt Ltd", "gstin": "29ABCDE1234F1Z5", "address": "123 Industrial Area, Bangalore" }, "buyer": { "name": "XYZ Corporation", "gstin": "27XYZAB5678C1D6", "address": "456 Commercial Complex, Mumbai" }, "items": [ { "description": "Laptop Computer", "hsn_code": "8471", "quantity": 5, "unit_price": 45000, "total": 225000 } ], "subtotal": 225000, "cgst": 20250, "sgst": 20250, "igst": 0, "total": 265500, "amount_in_words": "Two Lakh Sixty Five Thousand Five Hundred Rupees Only" }, "created_at": "2026-02-01T10:30:00Z" } ``` # Dastavez Overview Source: https://docs.rotavision.com/api-reference/dastavez/overview Document AI & Browser Agent APIs ## Introduction Dastavez provides intelligent document extraction for Indian documents and browser automation agents for web-based workflows. Extract structured data from documents Create browser automation agents Execute agent workflows ## Document Extraction ### Supported Documents | Category | Document Types | | -------------- | ---------------------------------------------------------------- | | **Identity** | Aadhaar, PAN, Voter ID, Passport, Driving License | | **Financial** | Bank Statements, ITR, Form 16, Salary Slips | | **Business** | GST Invoice, GST Returns, Company Registration, MSME Certificate | | **Legal** | Property Documents, Sale Deed, Rental Agreement | | **Education** | Mark Sheets, Degree Certificates, Transcripts | | **Healthcare** | Prescriptions, Lab Reports, Insurance Claims | ### Multi-Language OCR Dastavez supports extraction from documents in: * Hindi, English, Tamil, Telugu, Bengali * Marathi, Gujarati, Kannada, Malayalam * Punjabi, Odia, Assamese ### Extraction Quality | Feature | Capability | | ----------------- | --------------------------------------- | | **Accuracy** | 98%+ for standard Indian documents | | **Handwriting** | Supported for select fields | | **Image Quality** | Auto-enhancement for low-quality scans | | **Validation** | Built-in checksum and format validation | ## Browser Agents ### Capabilities * Navigate websites and web applications * Fill forms and submit data * Extract data from web pages * Handle authentication flows * Take screenshots and generate PDFs ### Use Cases * Government portal automation (GST, MCA, EPFO) * Bank statement downloads * Insurance policy retrieval * Compliance data collection ## Quick Example ```python theme={null} from rotavision import Rotavision client = Rotavision() # Extract from Aadhaar card result = client.dastavez.extract( document_type="aadhaar", file_url="s3://my-bucket/aadhaar-scan.pdf", options={ "mask_number": True, # Mask Aadhaar number in response "extract_photo": True } ) print(f"Name: {result.fields['name']}") print(f"DOB: {result.fields['dob']}") print(f"Confidence: {result.confidence}") # Create browser agent for GST portal agent = client.dastavez.create_agent( name="GST Returns Fetcher", capabilities=["navigate", "login", "extract", "download"] ) # Run workflow execution = client.dastavez.run_workflow( agent_id=agent.id, workflow={ "steps": [ {"action": "navigate", "url": "https://gst.gov.in"}, {"action": "login", "credentials_key": "gst_portal"}, {"action": "extract", "selector": ".returns-table"}, {"action": "download", "selector": ".gstr1-pdf"} ] } ) ``` ## Endpoints | Method | Endpoint | Description | | ------ | --------------------------------- | --------------------- | | `POST` | `/dastavez/extract` | Extract from document | | `GET` | `/dastavez/extractions/{id}` | Get extraction result | | `GET` | `/dastavez/extractions` | List extractions | | `POST` | `/dastavez/agents` | Create browser agent | | `GET` | `/dastavez/agents/{id}` | Get agent details | | `POST` | `/dastavez/agents/{id}/workflows` | Run agent workflow | | `GET` | `/dastavez/workflows/{id}` | Get workflow status | # Run Workflow Source: https://docs.rotavision.com/api-reference/dastavez/run-workflow POST /dastavez/agents/{agent_id}/workflows Execute a browser automation workflow ## Request The agent ID to run the workflow on. Workflow definition. Ordered list of workflow steps. Error handling: `stop`, `continue`, `retry`. Maximum retries per step. Input variables for the workflow. URL for completion webhook. ### Step Types | Action | Description | Parameters | | ------------- | --------------------- | ----------------------------------- | | `navigate` | Go to URL | `url` | | `click` | Click element | `selector`, `wait_for` | | `type` | Type text | `selector`, `text`, `clear` | | `extract` | Extract data | `selector`, `attribute`, `multiple` | | `screenshot` | Capture screen | `full_page`, `selector` | | `download` | Download file | `selector`, `wait_for` | | `wait` | Wait for element/time | `selector`, `timeout`, `duration` | | `login` | Authenticate | `credentials_key` | | `conditional` | If/else logic | `condition`, `then`, `else` | | `loop` | Iterate | `items`, `steps` | ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/dastavez/agents/agent_xyz789/workflows \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "workflow": { "steps": [ { "action": "navigate", "url": "https://services.gst.gov.in" }, { "action": "login", "credentials_key": "gst_portal" }, { "action": "wait", "selector": ".dashboard-loaded", "timeout": 10000 }, { "action": "click", "selector": "[data-menu=\"returns\"]" }, { "action": "extract", "selector": ".returns-table tr", "multiple": true, "fields": { "period": "td:nth-child(1)", "status": "td:nth-child(2)", "filed_date": "td:nth-child(3)" } }, { "action": "screenshot", "full_page": false } ] }, "inputs": { "financial_year": "2025-26" } }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() execution = client.dastavez.run_workflow( agent_id="agent_xyz789", workflow={ "steps": [ {"action": "navigate", "url": "https://services.gst.gov.in"}, {"action": "login", "credentials_key": "gst_portal"}, {"action": "wait", "selector": ".dashboard-loaded", "timeout": 10000}, {"action": "click", "selector": "[data-menu='returns']"}, { "action": "extract", "selector": ".returns-table tr", "multiple": True, "fields": { "period": "td:nth-child(1)", "status": "td:nth-child(2)", "filed_date": "td:nth-child(3)" } }, {"action": "screenshot", "full_page": False} ] }, inputs={"financial_year": "2025-26"} ) # Poll for completion result = client.dastavez.get_workflow(execution.id) print(f"Extracted data: {result.outputs['extracted_data']}") ``` ```json 202 - Running theme={null} { "id": "workflow_exec_123", "agent_id": "agent_xyz789", "status": "running", "progress": { "current_step": 2, "total_steps": 6, "current_action": "login" }, "created_at": "2026-02-01T10:30:00Z" } ``` ```json 200 - Completed theme={null} { "id": "workflow_exec_123", "agent_id": "agent_xyz789", "status": "completed", "outputs": { "extracted_data": [ { "period": "January 2026", "status": "Filed", "filed_date": "2026-02-10" }, { "period": "December 2025", "status": "Filed", "filed_date": "2026-01-11" } ], "screenshots": [ { "step": 6, "url": "https://storage.rotavision.com/screenshots/workflow_exec_123_step6.png", "expires_at": "2026-02-02T10:30:00Z" } ] }, "steps_completed": 6, "duration_ms": 45000, "created_at": "2026-02-01T10:30:00Z", "completed_at": "2026-02-01T10:30:45Z" } ``` # Optimize Routes Source: https://docs.rotavision.com/api-reference/gati/optimize-routes POST /gati/routes/optimize Find optimal routes for vehicle fleet ## Request Available vehicles. Vehicle identifier. Vehicle capacity (units). Starting location with lat/lng. End location (defaults to start). Shift start time (HH:MM). Shift end time (HH:MM). Orders/deliveries to fulfill. Order identifier. Delivery location with lat/lng. Demand/weight/volume. \[start, end] delivery window. Time at stop in minutes. Priority: `low`, `normal`, `high`. Optimization options. Objective: `distance`, `time`, `cost`, `balanced`. Consider real-time traffic. Vehicles return to start. Maximum route duration. ```python Python theme={null} result = client.gati.optimize_routes( vehicles=[ { "id": "v1", "capacity": 50, "start_location": {"lat": 12.9716, "lng": 77.5946}, "shift_start": "08:00", "shift_end": "18:00" }, { "id": "v2", "capacity": 50, "start_location": {"lat": 12.9716, "lng": 77.5946}, "shift_start": "08:00", "shift_end": "18:00" } ], orders=[ { "id": "order_1", "location": {"lat": 12.9352, "lng": 77.6245}, "demand": 5, "time_window": ["09:00", "12:00"], "service_time_min": 10 }, { "id": "order_2", "location": {"lat": 12.9698, "lng": 77.7500}, "demand": 8, "time_window": ["10:00", "14:00"] } ], options={ "optimize_for": "time", "traffic": True } ) ``` ```json 200 - Success theme={null} { "id": "opt_abc123", "status": "completed", "summary": { "total_vehicles_used": 2, "total_orders": 15, "orders_assigned": 15, "orders_unassigned": 0, "total_distance_km": 45.2, "total_duration_min": 180, "estimated_cost_inr": 450 }, "routes": [ { "vehicle_id": "v1", "stops": [ { "type": "start", "location": {"lat": 12.9716, "lng": 77.5946}, "arrival": "08:00", "departure": "08:00" }, { "type": "delivery", "order_id": "order_1", "location": {"lat": 12.9352, "lng": 77.6245}, "arrival": "08:35", "departure": "08:45", "demand": 5 }, { "type": "delivery", "order_id": "order_3", "location": {"lat": 12.9256, "lng": 77.6389}, "arrival": "09:05", "departure": "09:15", "demand": 12 }, { "type": "end", "location": {"lat": 12.9716, "lng": 77.5946}, "arrival": "12:30" } ], "distance_km": 22.5, "duration_min": 270, "load": 35, "polyline": "encoded_polyline_string..." }, { "vehicle_id": "v2", "stops": [...], "distance_km": 22.7, "duration_min": 255, "load": 42 } ], "created_at": "2026-02-01T10:30:00Z" } ``` # Gati Overview Source: https://docs.rotavision.com/api-reference/gati/overview Fleet & Mobility Intelligence APIs ## Introduction Gati provides AI-powered route optimization, demand forecasting, and fleet analytics for logistics and mobility companies. Find optimal routes for deliveries Real-time fleet tracking Demand forecasting ## Key Features ### Route Optimization * **Vehicle Routing Problem (VRP)** solving at scale * Support for time windows, capacity constraints * Real-time traffic integration * Multi-depot and multi-day planning ### Demand Forecasting * Predict demand by location and time * Factor in events, weather, holidays * Indian market-specific patterns (festivals, cricket matches) ### Fleet Analytics * Real-time vehicle tracking * Driver performance scoring * Maintenance prediction * Fuel efficiency analysis ## Quick Example ```python theme={null} from rotavision import Rotavision client = Rotavision() # Optimize delivery routes result = client.gati.optimize_routes( vehicles=[ {"id": "v1", "capacity": 100, "start_location": {"lat": 12.97, "lng": 77.59}}, {"id": "v2", "capacity": 100, "start_location": {"lat": 12.97, "lng": 77.59}} ], orders=[ {"id": "o1", "location": {"lat": 12.93, "lng": 77.63}, "demand": 10, "time_window": ["09:00", "12:00"]}, {"id": "o2", "location": {"lat": 12.95, "lng": 77.55}, "demand": 15, "time_window": ["10:00", "14:00"]}, # ... more orders ], options={ "optimize_for": "distance", "traffic": True, "return_to_depot": True } ) for route in result.routes: print(f"Vehicle {route.vehicle_id}: {len(route.stops)} stops, {route.distance_km:.1f} km") ``` ## Endpoints | Method | Endpoint | Description | | ------ | --------------------------- | ------------------------ | | `POST` | `/gati/routes/optimize` | Optimize routes | | `GET` | `/gati/routes/{id}` | Get optimization result | | `POST` | `/gati/fleet/track` | Update vehicle locations | | `GET` | `/gati/fleet/vehicles` | List vehicles | | `GET` | `/gati/fleet/vehicles/{id}` | Get vehicle details | | `POST` | `/gati/demand/predict` | Predict demand | | `GET` | `/gati/analytics/summary` | Fleet analytics | # Predict Demand Source: https://docs.rotavision.com/api-reference/gati/predict-demand POST /gati/demand/predict Forecast demand by location and time ## Request Regions to predict demand for. Region identifier. Geographic bounds (north, south, east, west). Center point with radius\_km. Indian pincode. Prediction period. Start date/time (ISO 8601). End date/time (ISO 8601). Time granularity: `hour`, `day`, `week`. Additional factors to consider. Include weather impact. Include local events. Include holiday patterns. ```python Python theme={null} forecast = client.gati.predict_demand( regions=[ {"id": "koramangala", "pincode": "560034"}, {"id": "indiranagar", "pincode": "560038"}, {"id": "whitefield", "pincode": "560066"} ], period={ "start": "2026-02-01", "end": "2026-02-07", "granularity": "hour" }, factors={ "weather": True, "events": True, "holidays": True } ) for region in forecast.predictions: print(f"{region.id}: Peak demand at {region.peak_hour} ({region.peak_demand} orders)") ``` ```json 200 - Success theme={null} { "id": "forecast_xyz789", "period": { "start": "2026-02-01T00:00:00Z", "end": "2026-02-07T23:59:59Z" }, "predictions": [ { "region_id": "koramangala", "total_demand": 4250, "daily_average": 607, "peak_day": "2026-02-02", "peak_hour": "19:00", "peak_demand": 85, "hourly": [ {"hour": "2026-02-01T00:00:00Z", "demand": 12, "confidence": 0.85}, {"hour": "2026-02-01T01:00:00Z", "demand": 8, "confidence": 0.82} ], "factors": { "weekend_boost": 1.15, "weather_impact": 0.95, "event_impact": 1.0 } }, { "region_id": "indiranagar", "total_demand": 3890, "daily_average": 556, "peak_day": "2026-02-02", "peak_hour": "20:00", "peak_demand": 78 }, { "region_id": "whitefield", "total_demand": 2150, "daily_average": 307, "peak_day": "2026-02-01", "peak_hour": "18:00", "peak_demand": 52, "notes": ["IPL match on Feb 2 may increase demand by 25%"] } ], "created_at": "2026-02-01T10:30:00Z" } ``` # Track Fleet Source: https://docs.rotavision.com/api-reference/gati/track-fleet POST /gati/fleet/track Update vehicle locations for real-time tracking ## Request Vehicle location updates. Vehicle identifier. Current location with lat/lng. Current speed. Heading in degrees (0-360). ISO 8601 timestamp. Vehicle status: `moving`, `stopped`, `idle`. ```python Python theme={null} client.gati.track_fleet( updates=[ { "vehicle_id": "v1", "location": {"lat": 12.9450, "lng": 77.6100}, "speed_kmh": 35, "heading": 90, "status": "moving" }, { "vehicle_id": "v2", "location": {"lat": 12.9600, "lng": 77.7200}, "speed_kmh": 0, "status": "stopped" } ] ) ``` ```json 200 - Success theme={null} { "processed": 2, "vehicles": [ { "vehicle_id": "v1", "status": "moving", "current_route": "opt_abc123", "next_stop": { "order_id": "order_5", "eta": "2026-02-01T11:15:00Z", "distance_km": 2.3 } }, { "vehicle_id": "v2", "status": "stopped", "stopped_duration_min": 12, "current_stop": { "order_id": "order_8", "arrived_at": "2026-02-01T11:03:00Z" } } ] } ``` # Create Monitor Source: https://docs.rotavision.com/api-reference/guardian/create-monitor POST /guardian/monitors Create a new monitoring configuration for a model ## Request Unique identifier for the model to monitor. Human-readable name for the monitor. Description of what this monitor tracks. Metrics to track: * `prediction_drift` - Output distribution drift (PSI) * `data_drift` - Input feature drift * `accuracy` - Accuracy vs ground truth (requires labels) * `latency_p50` - 50th percentile latency * `latency_p95` - 95th percentile latency * `latency_p99` - 99th percentile latency * `error_rate` - Percentage of failed predictions * `throughput` - Requests per second Baseline data for drift comparison. URL to baseline dataset (CSV/Parquet). Use recent production data as baseline: `7d`, `30d`, `90d`. Alert configurations. Metric to alert on. Threshold value. Comparison: `gt`, `lt`, `gte`, `lte`. Alert severity: `info`, `warning`, `critical`. Evaluation window: `5m`, `15m`, `1h`, `6h`, `24h`. Notification channels. Email addresses for alerts. Slack incoming webhook URL. PagerDuty integration key. Custom webhook URL. Monitoring schedule. How often to evaluate metrics: `5m`, `15m`, `1h`, `6h`, `24h`. Only monitor during specific hours (UTC). ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/guardian/monitors \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "model_id": "recommendation-v3", "name": "Production Recommendations", "description": "Monitoring for product recommendation model", "metrics": ["prediction_drift", "data_drift", "latency_p99", "error_rate"], "baseline": { "window": "30d" }, "alerts": [ { "metric": "prediction_drift", "threshold": 0.1, "severity": "warning" }, { "metric": "prediction_drift", "threshold": 0.2, "severity": "critical" }, { "metric": "latency_p99", "threshold": 500, "severity": "warning" }, { "metric": "error_rate", "threshold": 0.01, "severity": "critical" } ], "notifications": { "email": ["ml-team@company.com"], "slack_webhook": "https://hooks.slack.com/services/..." } }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() monitor = client.guardian.create_monitor( model_id="recommendation-v3", name="Production Recommendations", description="Monitoring for product recommendation model", metrics=["prediction_drift", "data_drift", "latency_p99", "error_rate"], baseline={"window": "30d"}, alerts=[ {"metric": "prediction_drift", "threshold": 0.1, "severity": "warning"}, {"metric": "prediction_drift", "threshold": 0.2, "severity": "critical"}, {"metric": "latency_p99", "threshold": 500, "severity": "warning"}, {"metric": "error_rate", "threshold": 0.01, "severity": "critical"}, ], notifications={ "email": ["ml-team@company.com"], "slack_webhook": "https://hooks.slack.com/services/..." } ) print(f"Monitor ID: {monitor.id}") ``` ```json 201 - Created theme={null} { "id": "mon_abc123", "model_id": "recommendation-v3", "name": "Production Recommendations", "description": "Monitoring for product recommendation model", "status": "active", "metrics": ["prediction_drift", "data_drift", "latency_p99", "error_rate"], "baseline": { "type": "rolling_window", "window": "30d", "status": "collecting" }, "alerts": [ { "id": "alert_cfg_1", "metric": "prediction_drift", "threshold": 0.1, "operator": "gt", "severity": "warning", "window": "1h" }, { "id": "alert_cfg_2", "metric": "prediction_drift", "threshold": 0.2, "operator": "gt", "severity": "critical", "window": "1h" } ], "notifications": { "email": ["ml-team@company.com"], "slack_webhook": "https://hooks.slack.com/services/..." }, "schedule": { "evaluation_interval": "1h" }, "created_at": "2026-02-01T10:00:00Z" } ``` # Get Alerts Source: https://docs.rotavision.com/api-reference/guardian/get-alerts GET /guardian/monitors/{monitor_id}/alerts Retrieve alerts for a monitor ## Request The monitor ID to get alerts for. Filter by status: `active`, `acknowledged`, `resolved`, `all`. Filter by severity: `info`, `warning`, `critical`. Filter by metric name. Filter alerts created after this timestamp (ISO 8601). Filter alerts created before this timestamp (ISO 8601). Number of alerts to return (max 100). Pagination cursor. ```bash cURL theme={null} curl "https://api.rotavision.com/v1/guardian/monitors/mon_abc123/alerts?status=active&severity=critical" \ -H "Authorization: Bearer rv_live_..." ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() alerts = client.guardian.get_alerts( monitor_id="mon_abc123", status="active", severity="critical" ) for alert in alerts.data: print(f"[{alert.severity}] {alert.metric}: {alert.message}") ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; const client = new Rotavision(); const alerts = await client.guardian.getAlerts({ monitorId: 'mon_abc123', status: 'active', severity: 'critical' }); alerts.data.forEach(alert => { console.log(`[${alert.severity}] ${alert.metric}: ${alert.message}`); }); ``` ```json 200 - Success theme={null} { "data": [ { "id": "alert_def456", "monitor_id": "mon_abc123", "model_id": "recommendation-v3", "metric": "prediction_drift", "severity": "critical", "status": "active", "value": 0.25, "threshold": 0.2, "message": "Significant prediction drift detected. PSI increased from 0.08 to 0.25 over the last hour.", "details": { "baseline_mean": 0.42, "current_mean": 0.58, "psi_breakdown": { "bucket_1": 0.02, "bucket_2": 0.08, "bucket_3": 0.15 } }, "triggered_at": "2026-02-01T10:30:00Z", "last_evaluated_at": "2026-02-01T11:00:00Z" }, { "id": "alert_ghi789", "monitor_id": "mon_abc123", "model_id": "recommendation-v3", "metric": "error_rate", "severity": "critical", "status": "active", "value": 0.023, "threshold": 0.01, "message": "Error rate exceeded threshold. Current: 2.3%, Threshold: 1%", "details": { "error_breakdown": { "timeout": 45, "invalid_input": 12, "internal_error": 8 }, "total_requests": 2826 }, "triggered_at": "2026-02-01T10:45:00Z", "last_evaluated_at": "2026-02-01T11:00:00Z" } ], "has_more": false } ``` ## Acknowledging Alerts Mark an alert as acknowledged: ```bash theme={null} curl -X POST https://api.rotavision.com/v1/guardian/alerts/alert_def456/acknowledge \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "acknowledged_by": "jane@company.com", "note": "Investigating - may be related to recent model update" }' ``` ## Resolving Alerts Mark an alert as resolved: ```bash theme={null} curl -X POST https://api.rotavision.com/v1/guardian/alerts/alert_def456/resolve \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "resolved_by": "jane@company.com", "resolution": "Rolled back to model v2. Drift caused by training data issue.", "root_cause": "data_quality" }' ``` ```json 200 - Resolved theme={null} { "id": "alert_def456", "status": "resolved", "resolved_by": "jane@company.com", "resolution": "Rolled back to model v2. Drift caused by training data issue.", "root_cause": "data_quality", "resolved_at": "2026-02-01T12:00:00Z", "duration_minutes": 90 } ``` # Log Inference Source: https://docs.rotavision.com/api-reference/guardian/log-inference POST /guardian/monitors/{monitor_id}/inferences Log a model inference for monitoring ## Request The monitor ID to log to. Input features for the inference. Used for data drift detection. The model's prediction output. Ground truth label (if available). Used for accuracy monitoring. Inference latency in milliseconds. Error details if the inference failed. Error code. Error message. Additional metadata for segmentation and analysis. ISO 8601 timestamp. Defaults to current time. ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/guardian/monitors/mon_abc123/inferences \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "input_data": { "user_id": "u123", "category": "electronics", "price_range": "mid", "session_duration": 245 }, "prediction": { "product_ids": ["p456", "p789", "p012"], "scores": [0.92, 0.87, 0.81] }, "latency_ms": 45, "metadata": { "user_segment": "premium", "region": "north", "platform": "mobile" } }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() # Log individual inference client.guardian.log_inference( monitor_id="mon_abc123", input_data={ "user_id": "u123", "category": "electronics", "price_range": "mid", "session_duration": 245 }, prediction={ "product_ids": ["p456", "p789", "p012"], "scores": [0.92, 0.87, 0.81] }, latency_ms=45, metadata={ "user_segment": "premium", "region": "north", "platform": "mobile" } ) ``` ```json 200 - Success theme={null} { "id": "inf_xyz789", "monitor_id": "mon_abc123", "logged_at": "2026-02-01T10:30:00Z" } ``` ## Batch Logging For high-throughput scenarios, use the batch endpoint: ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/guardian/monitors/mon_abc123/inferences/batch \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "inferences": [ { "input_data": {...}, "prediction": {...}, "latency_ms": 45, "timestamp": "2026-02-01T10:30:00Z" }, { "input_data": {...}, "prediction": {...}, "latency_ms": 52, "timestamp": "2026-02-01T10:30:01Z" } ] }' ``` ```python Python theme={null} # Log batch of inferences client.guardian.log_inferences( monitor_id="mon_abc123", inferences=[ { "input_data": {...}, "prediction": {...}, "latency_ms": 45, }, { "input_data": {...}, "prediction": {...}, "latency_ms": 52, } ] ) ``` Batch endpoint accepts up to 1,000 inferences per request. For very high throughput, consider using async logging with a queue. ## Async Logging For minimal latency impact on your serving path: ```python theme={null} from rotavision import Rotavision from rotavision.logging import AsyncLogger # Create async logger (uses background thread) logger = AsyncLogger( api_key="rv_live_...", monitor_id="mon_abc123", batch_size=100, flush_interval_ms=1000 ) # In your serving code - returns immediately logger.log( input_data=features, prediction=prediction, latency_ms=latency ) # Ensure flushing on shutdown logger.flush() ``` # Guardian Overview Source: https://docs.rotavision.com/api-reference/guardian/overview AI Reliability Monitoring APIs ## Introduction Guardian provides real-time monitoring for AI systems in production. Detect drift, anomalies, and performance degradation before they impact users. Set up monitoring for a model Log predictions for monitoring Retrieve triggered alerts ## Key Features ### Drift Detection | Type | Description | Method | | -------------------- | ----------------------------------------------- | -------------------------- | | **Data Drift** | Input feature distribution changes | PSI, KS Test, Chi-Square | | **Prediction Drift** | Output distribution changes | KL Divergence, JS Distance | | **Concept Drift** | Relationship between inputs and outputs changes | Performance monitoring | | **Label Drift** | Ground truth distribution changes | Distribution comparison | ### Anomaly Detection Guardian identifies unusual patterns in: * **Input anomalies**: Out-of-distribution inputs * **Output anomalies**: Unexpected predictions * **Latency anomalies**: Performance degradation * **Error spikes**: Increased failure rates ### Alerting Configure alerts based on: * Metric thresholds (e.g., PSI > 0.2) * Percentage changes (e.g., accuracy drops 5%) * Anomaly detection * SLA violations ## Quick Example ```python theme={null} from rotavision import Rotavision client = Rotavision() # Create a monitor monitor = client.guardian.create_monitor( model_id="recommendation-v3", name="Prod Recommendations", metrics=["prediction_drift", "latency_p99", "error_rate"], alerts=[ {"metric": "prediction_drift", "threshold": 0.1, "severity": "warning"}, {"metric": "prediction_drift", "threshold": 0.2, "severity": "critical"}, {"metric": "latency_p99", "threshold": 500, "severity": "warning"}, ] ) # Log inferences (typically in your serving code) client.guardian.log_inference( monitor_id=monitor.id, input_data=features, prediction=prediction, latency_ms=45, metadata={"user_segment": "premium"} ) # Check for alerts alerts = client.guardian.get_alerts( monitor_id=monitor.id, status="active" ) ``` ## Endpoints | Method | Endpoint | Description | | -------- | ------------------------------------------ | ----------------------- | | `POST` | `/guardian/monitors` | Create a monitor | | `GET` | `/guardian/monitors/{id}` | Get monitor details | | `GET` | `/guardian/monitors` | List monitors | | `PATCH` | `/guardian/monitors/{id}` | Update monitor config | | `DELETE` | `/guardian/monitors/{id}` | Delete a monitor | | `POST` | `/guardian/monitors/{id}/inferences` | Log single inference | | `POST` | `/guardian/monitors/{id}/inferences/batch` | Log batch of inferences | | `GET` | `/guardian/monitors/{id}/metrics` | Get monitoring metrics | | `GET` | `/guardian/monitors/{id}/alerts` | Get monitor alerts | | `POST` | `/guardian/alerts/{id}/acknowledge` | Acknowledge an alert | | `POST` | `/guardian/alerts/{id}/resolve` | Resolve an alert | # Create Workflow Source: https://docs.rotavision.com/api-reference/orchestrate/create-workflow POST /orchestrate/workflows Create a multi-agent workflow definition ## Request Human-readable workflow name. Workflow description. Agent definitions. Unique agent identifier within workflow. Agent type: `llm`, `code`, `search`, `tool`, `human`. LLM model (for llm agents). System prompt (for llm agents). Available tools (for tool agents). Workflow steps. Step identifier. Auto-generated if not provided. Agent ID to execute step. Action for the agent to perform. Input template (supports `{{variable}}` syntax). Conditional expression for step execution. Steps to run in parallel. Workflow configuration. Maximum execution time. Retries per step. Maximum cost budget. ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/orchestrate/workflows \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "name": "Customer Support Triage", "agents": [ { "id": "classifier", "type": "llm", "model": "gpt-5-mini", "system_prompt": "Classify customer support tickets..." }, { "id": "responder", "type": "llm", "model": "claude-4.5-sonnet", "system_prompt": "Generate helpful customer support responses..." }, { "id": "escalation", "type": "human", "assignees": ["support-lead@company.com"] } ], "steps": [ { "agent": "classifier", "action": "classify", "input": "{{ticket}}" }, { "condition": "{{classifier.priority}} == \"high\"", "agent": "escalation", "action": "approve", "input": "High priority ticket requires approval" }, { "agent": "responder", "action": "respond", "input": "Category: {{classifier.category}}\nTicket: {{ticket}}" } ] }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() workflow = client.orchestrate.create_workflow( name="Customer Support Triage", agents=[ { "id": "classifier", "type": "llm", "model": "gpt-5-mini", "system_prompt": "Classify customer support tickets by category and priority." }, { "id": "responder", "type": "llm", "model": "claude-4.5-sonnet", "system_prompt": "Generate helpful, empathetic customer support responses." }, { "id": "escalation", "type": "human", "assignees": ["support-lead@company.com"] } ], steps=[ {"agent": "classifier", "action": "classify", "input": "{{ticket}}"}, { "condition": "{{classifier.priority}} == 'high'", "agent": "escalation", "action": "approve", "input": "High priority ticket requires approval" }, {"agent": "responder", "action": "respond", "input": "{{ticket}}"} ] ) ``` ```json 201 - Created theme={null} { "id": "wf_abc123", "name": "Customer Support Triage", "status": "active", "version": 1, "agents": [...], "steps": [...], "config": { "timeout_ms": 300000, "max_retries": 3 }, "created_at": "2026-02-01T10:00:00Z" } ``` # Get Execution Source: https://docs.rotavision.com/api-reference/orchestrate/get-execution GET /orchestrate/executions/{execution_id} Get workflow execution status and results ## Request The execution ID. ```bash cURL theme={null} curl https://api.rotavision.com/v1/orchestrate/executions/exec_xyz789 \ -H "Authorization: Bearer rv_live_..." ``` ```python Python theme={null} execution = client.orchestrate.get_execution("exec_xyz789") print(f"Status: {execution.status}") if execution.status == "completed": print(f"Response: {execution.outputs['response']}") ``` ```json 200 - Completed theme={null} { "id": "exec_xyz789", "workflow_id": "wf_abc123", "workflow_name": "Customer Support Triage", "status": "completed", "inputs": { "ticket": "I have been waiting for my refund for 2 weeks. Order #12345. This is unacceptable!" }, "outputs": { "category": "refund", "priority": "high", "response": "Dear Customer,\n\nI sincerely apologize for the delay with your refund for Order #12345. I understand how frustrating this must be, and I want to resolve this for you immediately.\n\nI've escalated your case to our finance team with urgent priority. You should receive your refund within 24-48 hours.\n\nAs a gesture of goodwill, I've also added a ₹500 credit to your account for future purchases.\n\nPlease don't hesitate to reach out if you have any other concerns.\n\nBest regards,\nSupport Team" }, "steps": [ { "id": "step_1", "agent": "classifier", "status": "completed", "output": { "category": "refund", "priority": "high", "sentiment": "frustrated" }, "duration_ms": 450 }, { "id": "step_2", "agent": "escalation", "status": "completed", "output": { "approved": true, "approved_by": "support-lead@company.com", "notes": "Approve - customer has valid complaint" }, "duration_ms": 125000 }, { "id": "step_3", "agent": "responder", "status": "completed", "output": { "response": "Dear Customer..." }, "duration_ms": 1200 } ], "cost": { "usd": 0.012, "inr": 1.00 }, "duration_ms": 126650, "created_at": "2026-02-01T10:30:00Z", "completed_at": "2026-02-01T10:32:07Z" } ``` ```json 200 - Waiting for Approval theme={null} { "id": "exec_xyz789", "workflow_id": "wf_abc123", "status": "waiting_approval", "current_step": "escalation", "waiting_for": { "type": "human_approval", "assignees": ["support-lead@company.com"], "message": "High priority ticket requires approval", "context": { "category": "refund", "priority": "high" } }, "approve_url": "https://dashboard.rotavision.com/approve/exec_xyz789" } ``` ## Approving Human Steps When a workflow is waiting for human approval: ```bash theme={null} curl -X POST https://api.rotavision.com/v1/orchestrate/executions/exec_xyz789/approve \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "approved": true, "notes": "Approved - valid customer complaint" }' ``` # Orchestrate Overview Source: https://docs.rotavision.com/api-reference/orchestrate/overview Multi-Agent Workflow APIs ## Introduction Orchestrate enables building and deploying multi-agent AI workflows for complex enterprise tasks. Coordinate specialized agents, manage state, and implement human-in-the-loop controls. Define multi-agent workflows Execute workflows Monitor workflow progress ## Key Features ### Agent Types | Agent | Capability | | ---------------- | ----------------------------------------- | | **LLM Agent** | Natural language reasoning and generation | | **Code Agent** | Execute Python/JavaScript code | | **Search Agent** | Web and document search | | **Tool Agent** | Call external APIs and tools | | **Human Agent** | Human-in-the-loop approval/input | ### Workflow Patterns * **Sequential**: Agents run in order * **Parallel**: Multiple agents run simultaneously * **Conditional**: Branch based on results * **Loop**: Iterate until condition met * **Map-Reduce**: Process items in parallel, aggregate results ### Enterprise Features * State persistence across executions * Retry and error handling * Audit logging * Cost controls and budgets * Human approval gates ## Quick Example ```python theme={null} from rotavision import Rotavision client = Rotavision() # Create a research workflow workflow = client.orchestrate.create_workflow( name="Market Research Pipeline", agents=[ { "id": "researcher", "type": "llm", "model": "gpt-5-mini", "system_prompt": "You are a market research analyst..." }, { "id": "searcher", "type": "search", "sources": ["web", "news", "academic"] }, { "id": "writer", "type": "llm", "model": "claude-4.5-sonnet", "system_prompt": "You are a report writer..." } ], steps=[ {"agent": "researcher", "action": "plan_research", "input": "{{topic}}"}, {"agent": "searcher", "action": "search", "input": "{{researcher.queries}}"}, {"agent": "writer", "action": "write_report", "input": "{{searcher.results}}"} ] ) # Run the workflow execution = client.orchestrate.run_workflow( workflow_id=workflow.id, inputs={"topic": "Electric vehicle adoption in India 2026"} ) # Get results result = client.orchestrate.get_execution(execution.id) print(result.outputs["report"]) ``` ## Endpoints | Method | Endpoint | Description | | -------- | -------------------------------------- | ------------------ | | `POST` | `/orchestrate/workflows` | Create workflow | | `GET` | `/orchestrate/workflows/{id}` | Get workflow | | `GET` | `/orchestrate/workflows` | List workflows | | `PATCH` | `/orchestrate/workflows/{id}` | Update workflow | | `DELETE` | `/orchestrate/workflows/{id}` | Delete workflow | | `POST` | `/orchestrate/workflows/{id}/run` | Run workflow | | `GET` | `/orchestrate/executions/{id}` | Get execution | | `GET` | `/orchestrate/executions` | List executions | | `POST` | `/orchestrate/executions/{id}/cancel` | Cancel execution | | `POST` | `/orchestrate/executions/{id}/approve` | Approve human step | # Run Workflow Source: https://docs.rotavision.com/api-reference/orchestrate/run-workflow POST /orchestrate/workflows/{workflow_id}/run Execute a workflow ## Request The workflow ID to run. Input variables for the workflow. Runtime configuration overrides. URL for completion webhook. ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/orchestrate/workflows/wf_abc123/run \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "inputs": { "ticket": "I have been waiting for my refund for 2 weeks. Order #12345. This is unacceptable!" } }' ``` ```python Python theme={null} execution = client.orchestrate.run_workflow( workflow_id="wf_abc123", inputs={ "ticket": "I have been waiting for my refund for 2 weeks. Order #12345." } ) print(f"Execution ID: {execution.id}") print(f"Status: {execution.status}") ``` ```json 202 - Running theme={null} { "id": "exec_xyz789", "workflow_id": "wf_abc123", "status": "running", "current_step": "classifier", "progress": { "completed": 0, "total": 3 }, "inputs": { "ticket": "I have been waiting for my refund for 2 weeks..." }, "created_at": "2026-02-01T10:30:00Z" } ``` # API Overview Source: https://docs.rotavision.com/api-reference/overview Introduction to the Rotavision REST API ## Base URL All API requests should be made to: ``` https://api.rotavision.com/v1 ``` ## Authentication Include your API key in the `Authorization` header: ```bash theme={null} curl https://api.rotavision.com/v1/vishwas/analyze \ -H "Authorization: Bearer rv_live_your_api_key" \ -H "Content-Type: application/json" ``` See [Authentication](/authentication) for details on API key types and scopes. ## Request Format All request bodies should be JSON with `Content-Type: application/json`: ```bash theme={null} curl -X POST https://api.rotavision.com/v1/vishwas/analyze \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "model_id": "loan-approval-v2", "dataset": { ... } }' ``` ## Response Format All responses are JSON. Successful responses include the requested data: ```json theme={null} { "id": "analysis_abc123", "model_id": "loan-approval-v2", "status": "completed", "overall_score": 0.82, "created_at": "2026-02-01T10:30:00Z" } ``` Error responses follow a consistent structure: ```json theme={null} { "error": { "code": "invalid_request", "message": "The 'model_id' field is required", "type": "validation_error", "param": "model_id", "request_id": "req_abc123" } } ``` ## Pagination List endpoints support cursor-based pagination: ```bash theme={null} curl "https://api.rotavision.com/v1/vishwas/analyses?limit=20&cursor=abc123" \ -H "Authorization: Bearer rv_live_..." ``` Response includes pagination metadata: ```json theme={null} { "data": [...], "has_more": true, "next_cursor": "xyz789" } ``` | Parameter | Description | | --------- | ------------------------------------------------ | | `limit` | Number of items per page (default: 20, max: 100) | | `cursor` | Cursor for the next page | ## Filtering & Sorting List endpoints support filtering and sorting: ```bash theme={null} # Filter by status and sort by creation date curl "https://api.rotavision.com/v1/guardian/alerts?status=active&sort=-created_at" \ -H "Authorization: Bearer rv_live_..." ``` | Parameter | Description | | ---------------- | ------------------------------------------------ | | `sort` | Field to sort by. Prefix with `-` for descending | | `created_after` | Filter by creation date (ISO 8601) | | `created_before` | Filter by creation date (ISO 8601) | ## Idempotency For POST requests, include an `Idempotency-Key` header to safely retry requests: ```bash theme={null} curl -X POST https://api.rotavision.com/v1/vishwas/analyze \ -H "Authorization: Bearer rv_live_..." \ -H "Idempotency-Key: unique-request-id-123" \ -H "Content-Type: application/json" \ -d '{ ... }' ``` Requests with the same idempotency key within 24 hours return the cached response. ## Versioning The API version is included in the URL path (`/v1`). We follow semantic versioning: * **Patch versions** (v1.0.x): Bug fixes, no breaking changes * **Minor versions** (v1.x.0): New features, backward compatible * **Major versions** (vX.0.0): Breaking changes We provide at least 12 months notice before deprecating major versions. ## SDKs Official SDKs handle authentication, retries, and error handling: `pip install rotavision` `npm install @rotavision/sdk` Maven Central ## Products Trust, Fairness & Explainability APIs AI Reliability Monitoring APIs Document AI & Browser Agent APIs Sovereign AI Gateway APIs Multi-Agent Workflow APIs Fleet & Mobility Intelligence APIs # Get Usage Source: https://docs.rotavision.com/api-reference/sankalp/get-usage GET /sankalp/usage Get usage statistics and costs ## Request Start date (ISO 8601). Defaults to start of current month. End date (ISO 8601). Defaults to now. Group results by: `day`, `week`, `month`, `model`, `provider`. ```bash cURL theme={null} curl "https://api.rotavision.com/v1/sankalp/usage?start_date=2026-01-01&group_by=model" \ -H "Authorization: Bearer rv_live_..." ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() usage = client.sankalp.get_usage( start_date="2026-01-01", group_by="model" ) print(f"Total cost: ₹{usage.total_cost.inr}") for item in usage.breakdown: print(f" {item.model}: {item.requests} requests, ₹{item.cost.inr}") ``` ```json 200 - Success theme={null} { "period": { "start": "2026-01-01T00:00:00Z", "end": "2026-02-01T10:30:00Z" }, "summary": { "total_requests": 125430, "total_tokens": { "input": 45678900, "output": 23456780, "total": 69135680 }, "total_cost": { "usd": 234.56, "inr": 19540.23 }, "avg_latency_ms": 1250 }, "breakdown": [ { "model": "gpt-5-mini", "provider": "openai", "requests": 45000, "tokens": { "input": 18000000, "output": 9000000, "total": 27000000 }, "cost": { "usd": 108.00, "inr": 9000.00 }, "avg_latency_ms": 1100 }, { "model": "sarvam-large", "provider": "sarvam", "requests": 52000, "tokens": { "input": 15678900, "output": 8456780, "total": 24135680 }, "cost": { "usd": 48.27, "inr": 4022.50 }, "avg_latency_ms": 890 }, { "model": "claude-4.5-sonnet", "provider": "anthropic", "requests": 28430, "tokens": { "input": 12000000, "output": 6000000, "total": 18000000 }, "cost": { "usd": 78.29, "inr": 6524.17 }, "avg_latency_ms": 1650 } ], "daily_trend": [ { "date": "2026-01-31", "requests": 4521, "cost": {"usd": 8.42, "inr": 701.67} }, { "date": "2026-02-01", "requests": 2341, "cost": {"usd": 4.21, "inr": 350.83} } ] } ``` # List Models Source: https://docs.rotavision.com/api-reference/sankalp/list-models GET /sankalp/models List available LLM models ## Request Filter by provider: `openai`, `anthropic`, `sarvam`, `krutrim`, etc. Filter by capability: `chat`, `code`, `vision`, `hindi`, `tamil`, etc. Filter by data residency: `india`, `asia`, `us`, `eu`. ```bash cURL theme={null} curl "https://api.rotavision.com/v1/sankalp/models?data_residency=india" \ -H "Authorization: Bearer rv_live_..." ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() models = client.sankalp.list_models(data_residency="india") for model in models.data: print(f"{model.id}: {model.description}") ``` ```json 200 - Success theme={null} { "data": [ { "id": "sarvam-large", "provider": "sarvam", "description": "Sarvam AI's flagship model with strong Indic language support", "capabilities": ["chat", "hindi", "tamil", "telugu", "bengali", "reasoning"], "context_window": 32000, "data_residency": "india", "pricing": { "input_per_1k": 0.0005, "output_per_1k": 0.0015, "currency": "usd" }, "status": "available" }, { "id": "sarvam-small", "provider": "sarvam", "description": "Efficient model for simple tasks", "capabilities": ["chat", "hindi", "english"], "context_window": 8000, "data_residency": "india", "pricing": { "input_per_1k": 0.0001, "output_per_1k": 0.0003, "currency": "usd" }, "status": "available" }, { "id": "krutrim-3", "provider": "krutrim", "description": "Ola's Krutrim model with Indian language focus", "capabilities": ["chat", "hindi", "kannada", "code"], "context_window": 16000, "data_residency": "india", "pricing": { "input_per_1k": 0.0004, "output_per_1k": 0.0012, "currency": "usd" }, "status": "available" }, { "id": "gpt-5-mini", "provider": "openai", "description": "OpenAI's efficient GPT-5 variant", "capabilities": ["chat", "code", "reasoning", "vision"], "context_window": 128000, "data_residency": "us", "pricing": { "input_per_1k": 0.003, "output_per_1k": 0.006, "currency": "usd" }, "status": "available" }, { "id": "claude-4.5-sonnet", "provider": "anthropic", "description": "Anthropic's balanced Claude model", "capabilities": ["chat", "code", "reasoning", "vision"], "context_window": 200000, "data_residency": "us", "pricing": { "input_per_1k": 0.003, "output_per_1k": 0.015, "currency": "usd" }, "status": "available" } ] } ``` # Sankalp Overview Source: https://docs.rotavision.com/api-reference/sankalp/overview Sovereign AI Gateway APIs ## Introduction Sankalp provides a unified API gateway for accessing Indian and international LLMs with built-in data residency controls, cost optimization, and compliance features. Route requests to LLM providers Available models and capabilities Usage analytics and costs ## Key Features ### Unified API Single API for 20+ LLM providers: | Category | Providers | | ----------------- | ------------------------------------------------ | | **International** | OpenAI, Anthropic, Google, Meta, Mistral, Cohere | | **Indian** | Sarvam AI, Krutrim, BharatGPT, Bhashini | | **Open Source** | Llama, Mixtral, Phi (self-hosted) | ### Data Residency Control where your data is processed: ```python theme={null} # Force India-only processing response = client.sankalp.proxy( model="sarvam-large", messages=[...], data_residency="india" # Only use India-based providers ) ``` ### Intelligent Routing * **Cost optimization**: Route to cheapest capable model * **Latency optimization**: Route to fastest available * **Capability matching**: Auto-select model by task requirements * **Fallback chains**: Automatic failover if primary unavailable ### Compliance * Prompt/response logging for audit * PII detection and redaction * Content filtering * Usage quotas and governance ## Quick Example ```python theme={null} from rotavision import Rotavision client = Rotavision() # Simple proxy request response = client.sankalp.proxy( model="gpt-5-mini", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain quantum computing in Hindi"} ], temperature=0.7 ) print(response.choices[0].message.content) print(f"Tokens: {response.usage.total_tokens}") print(f"Cost: ₹{response.cost.inr}") # With routing preferences response = client.sankalp.proxy( model="auto", # Auto-select best model messages=[...], routing={ "optimize": "cost", "max_latency_ms": 2000, "data_residency": "india", "capabilities": ["hindi", "reasoning"] } ) ``` ## Endpoints | Method | Endpoint | Description | | ------ | ----------------------- | ----------------------- | | `POST` | `/sankalp/proxy` | Proxy request to LLM | | `POST` | `/sankalp/proxy/stream` | Streaming proxy request | | `GET` | `/sankalp/models` | List available models | | `GET` | `/sankalp/models/{id}` | Get model details | | `GET` | `/sankalp/usage` | Get usage statistics | | `GET` | `/sankalp/usage/costs` | Get cost breakdown | # Proxy Request Source: https://docs.rotavision.com/api-reference/sankalp/proxy-request POST /sankalp/proxy Route a request to an LLM provider ## Request Model to use. Can be specific (`gpt-5-mini`, `claude-4.5-sonnet`) or `auto` for intelligent routing. Conversation messages in OpenAI format. Message role: `system`, `user`, `assistant`. Message content. Sampling temperature (0-2). Maximum tokens to generate. Enable streaming response. Routing preferences. Optimization target: `cost`, `latency`, `quality`. Data residency requirement: `india`, `asia`, `any`. Maximum acceptable latency. Fallback models if primary unavailable. Required capabilities: `hindi`, `tamil`, `code`, `reasoning`, `vision`. Compliance settings. Log prompts for audit. Redact PII from logs. Apply content filtering. ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/sankalp/proxy \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-5-mini", "messages": [ {"role": "system", "content": "You are a helpful assistant fluent in Hindi."}, {"role": "user", "content": "भारत में AI adoption की स्थिति क्या है?"} ], "temperature": 0.7, "max_tokens": 1000 }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() response = client.sankalp.proxy( model="gpt-5-mini", messages=[ {"role": "system", "content": "You are a helpful assistant fluent in Hindi."}, {"role": "user", "content": "भारत में AI adoption की स्थिति क्या है?"} ], temperature=0.7, max_tokens=1000 ) print(response.choices[0].message.content) # With auto-routing response = client.sankalp.proxy( model="auto", messages=[...], routing={ "optimize": "cost", "data_residency": "india", "capabilities": ["hindi"] } ) ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; const client = new Rotavision(); const response = await client.sankalp.proxy({ model: 'gpt-5-mini', messages: [ { role: 'system', content: 'You are a helpful assistant fluent in Hindi.' }, { role: 'user', content: 'भारत में AI adoption की स्थिति क्या है?' } ], temperature: 0.7, maxTokens: 1000 }); console.log(response.choices[0].message.content); ``` ```json 200 - Success theme={null} { "id": "proxy_abc123", "model": "gpt-5-mini", "provider": "openai", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "भारत में AI adoption तेजी से बढ़ रहा है। कुछ मुख्य बिंदु:\n\n1. **एंटरप्राइज़ अपनाना**: बड़ी कंपनियां जैसे TCS, Infosys, और Reliance AI में भारी निवेश कर रही हैं...\n\n2. **स्टार्टअप इकोसिस्टम**: भारत में 3,000+ AI स्टार्टअप्स हैं...\n\n3. **सरकारी पहल**: Digital India और AI Mission के तहत..." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 45, "completion_tokens": 312, "total_tokens": 357 }, "cost": { "usd": 0.0021, "inr": 0.18 }, "latency_ms": 1250, "routing": { "selected_model": "gpt-5-mini", "selected_provider": "openai", "reason": "explicit_model_request" }, "created_at": "2026-02-01T10:30:00Z" } ``` ```json 200 - Auto-Routed theme={null} { "id": "proxy_def456", "model": "sarvam-large", "provider": "sarvam", "choices": [...], "usage": { "prompt_tokens": 45, "completion_tokens": 298, "total_tokens": 343 }, "cost": { "usd": 0.0008, "inr": 0.07 }, "latency_ms": 890, "routing": { "selected_model": "sarvam-large", "selected_provider": "sarvam", "reason": "cost_optimized_with_india_residency", "alternatives_considered": ["krutrim-3", "gpt-5-mini"] } } ``` ## Streaming For streaming responses, use the stream endpoint or set `stream: true`: ```python theme={null} # Streaming in Python for chunk in client.sankalp.proxy_stream( model="claude-4.5-sonnet", messages=[{"role": "user", "content": "Write a poem about India"}] ): print(chunk.choices[0].delta.content, end="") ``` ```typescript theme={null} // Streaming in Node.js const stream = await client.sankalp.proxyStream({ model: 'claude-4.5-sonnet', messages: [{ role: 'user', content: 'Write a poem about India' }] }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0].delta.content || ''); } ``` # Analyze Fairness Source: https://docs.rotavision.com/api-reference/vishwas/analyze-fairness POST /vishwas/analyze Run a comprehensive fairness analysis on model predictions ## Request Unique identifier for your model. Used for tracking and comparison. The dataset to analyze. List of feature names in the dataset. 2D array of feature values. Either provide `data` or `data_url`. URL to a CSV or Parquet file containing the data. Model predictions (probabilities or class labels). Ground truth labels. Required for accuracy-based metrics. List of feature names to analyze for fairness. Fairness metrics to calculate. Options: * `demographic_parity` * `equalized_odds` * `equal_opportunity` * `calibration` * `individual_fairness` * `counterfactual_fairness` Custom thresholds for each metric. Default is 0.8 (80%) for all metrics. Specify reference groups for each protected attribute. Whether to run analysis asynchronously. Set to `false` for small datasets (\< 10,000 rows). URL to receive webhook when analysis completes. ## Response Unique analysis identifier. The model ID provided in the request. Analysis status: `pending`, `processing`, `completed`, `failed`. Aggregate fairness score from 0-1. Whether any metric fell below its threshold. Detailed results for each fairness metric. Actionable recommendations for improving fairness. ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/vishwas/analyze \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "model_id": "loan-approval-v2", "dataset": { "features": ["age", "income", "credit_score", "gender", "region"], "data_url": "s3://my-bucket/loan-data.parquet", "predictions": "prediction_col", "actuals": "approved_col", "protected_attributes": ["gender", "region"] }, "metrics": ["demographic_parity", "equalized_odds", "calibration"], "thresholds": { "demographic_parity": 0.85, "equalized_odds": 0.80 } }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() analysis = client.vishwas.analyze( model_id="loan-approval-v2", dataset={ "features": ["age", "income", "credit_score", "gender", "region"], "data": data_array, "predictions": predictions, "actuals": actuals, "protected_attributes": ["gender", "region"] }, metrics=["demographic_parity", "equalized_odds", "calibration"], thresholds={ "demographic_parity": 0.85, "equalized_odds": 0.80 } ) print(f"Analysis ID: {analysis.id}") print(f"Status: {analysis.status}") ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; const client = new Rotavision(); const analysis = await client.vishwas.analyze({ modelId: 'loan-approval-v2', dataset: { features: ['age', 'income', 'credit_score', 'gender', 'region'], data: dataArray, predictions: predictions, actuals: actuals, protectedAttributes: ['gender', 'region'] }, metrics: ['demographic_parity', 'equalized_odds', 'calibration'], thresholds: { demographic_parity: 0.85, equalized_odds: 0.80 } }); console.log(`Analysis ID: ${analysis.id}`); console.log(`Status: ${analysis.status}`); ``` ```json 200 - Completed theme={null} { "id": "analysis_abc123xyz", "model_id": "loan-approval-v2", "status": "completed", "overall_score": 0.82, "bias_detected": true, "dataset_summary": { "total_rows": 50000, "protected_groups": { "gender": ["male", "female"], "region": ["urban", "rural", "semi-urban"] } }, "metrics": [ { "name": "demographic_parity", "value": 0.78, "threshold": 0.85, "status": "fail", "details": { "gender": { "male": 0.72, "female": 0.65, "ratio": 0.90 }, "region": { "urban": 0.75, "rural": 0.58, "semi-urban": 0.68, "min_ratio": 0.77 } }, "affected_groups": ["region:rural"] }, { "name": "equalized_odds", "value": 0.91, "threshold": 0.80, "status": "pass", "details": { "tpr_ratio": 0.93, "fpr_ratio": 0.89 } }, { "name": "calibration", "value": 0.85, "threshold": 0.80, "status": "pass" } ], "recommendations": [ { "severity": "high", "metric": "demographic_parity", "group": "region:rural", "message": "Rural applicants have 23% lower approval rate despite similar creditworthiness", "action": "Review feature weights for location-correlated variables (distance_to_branch, digital_access)", "impact_estimate": "+0.12 fairness score improvement" } ], "created_at": "2026-02-01T10:30:00Z", "completed_at": "2026-02-01T10:32:15Z" } ``` ```json 202 - Async Processing theme={null} { "id": "analysis_abc123xyz", "model_id": "loan-approval-v2", "status": "processing", "progress": 0, "estimated_completion": "2026-02-01T10:35:00Z", "created_at": "2026-02-01T10:30:00Z" } ``` # Explain Prediction Source: https://docs.rotavision.com/api-reference/vishwas/explain-prediction POST /vishwas/explain Generate human-readable explanations for model predictions ## Request Unique identifier for your model. The input features for the prediction to explain. The model's prediction (probability or class label). Explanation method to use: * `shap` - SHAP values (recommended) * `lime` - LIME explanations * `anchors` - Rule-based anchors * `counterfactual` - Counterfactual examples * `prototype` - Similar training examples Number of top features to include in explanation. Language for human-readable text. Supports: `en`, `hi`, `ta`, `te`, `bn`, `mr`, `gu`, `kn`, `ml`, `pa`, `or`, `as`. Target audience for explanation: * `technical` - For data scientists and ML engineers * `business` - For business stakeholders * `customer` - For end users/customers ## Response Unique explanation identifier. The model ID. The explanation method used. The prediction being explained. Feature contributions ranked by importance. Human-readable explanation text. Counterfactual examples (if method is `counterfactual`). ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/vishwas/explain \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "model_id": "loan-approval-v2", "input_data": { "age": 32, "income": 850000, "credit_score": 720, "employment_years": 5, "existing_loans": 1, "region": "urban" }, "prediction": 0.73, "method": "shap", "num_features": 5, "language": "en", "audience": "customer" }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() explanation = client.vishwas.explain( model_id="loan-approval-v2", input_data={ "age": 32, "income": 850000, "credit_score": 720, "employment_years": 5, "existing_loans": 1, "region": "urban" }, prediction=0.73, method="shap", num_features=5, language="en", audience="customer" ) print(explanation.summary) for feature in explanation.features: print(f" {feature.name}: {feature.contribution:+.2f}") ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; const client = new Rotavision(); const explanation = await client.vishwas.explain({ modelId: 'loan-approval-v2', inputData: { age: 32, income: 850000, credit_score: 720, employment_years: 5, existing_loans: 1, region: 'urban' }, prediction: 0.73, method: 'shap', numFeatures: 5, language: 'en', audience: 'customer' }); console.log(explanation.summary); explanation.features.forEach(f => { console.log(` ${f.name}: ${f.contribution > 0 ? '+' : ''}${f.contribution.toFixed(2)}`); }); ``` ```json 200 - Success theme={null} { "id": "explain_xyz789", "model_id": "loan-approval-v2", "method": "shap", "prediction": { "value": 0.73, "label": "likely_approved", "confidence": "medium-high" }, "features": [ { "name": "credit_score", "value": 720, "contribution": 0.18, "direction": "positive", "description": "Your credit score of 720 is above average, increasing approval likelihood" }, { "name": "income", "value": 850000, "contribution": 0.15, "direction": "positive", "description": "Your annual income supports the requested loan amount" }, { "name": "employment_years", "value": 5, "contribution": 0.08, "direction": "positive", "description": "5 years of stable employment is viewed favorably" }, { "name": "existing_loans", "value": 1, "contribution": -0.05, "direction": "negative", "description": "Having an existing loan slightly reduces approval likelihood" }, { "name": "age", "value": 32, "contribution": 0.02, "direction": "positive", "description": "Your age falls within a favorable range for this loan type" } ], "summary": "Your loan application has a 73% likelihood of approval. The main factors supporting your application are your good credit score (720) and stable income (₹8.5 lakhs annually). Your 5 years of employment history also strengthens your application. The only factor slightly reducing your score is your existing loan, but this is minor compared to the positive factors.", "baseline": 0.35, "created_at": "2026-02-01T10:30:00Z" } ``` ```json 200 - Counterfactual theme={null} { "id": "explain_xyz789", "model_id": "loan-approval-v2", "method": "counterfactual", "prediction": { "value": 0.42, "label": "likely_rejected" }, "counterfactuals": [ { "changes": { "credit_score": {"from": 620, "to": 680} }, "new_prediction": 0.68, "feasibility": "medium", "description": "Improving your credit score by 60 points would significantly increase approval chances" }, { "changes": { "existing_loans": {"from": 3, "to": 1} }, "new_prediction": 0.61, "feasibility": "high", "description": "Paying off 2 existing loans would improve your debt-to-income ratio" } ], "summary": "Your application currently has a 42% approval likelihood. The most actionable improvement would be to reduce your existing loans from 3 to 1, which could increase approval chances to 61%.", "created_at": "2026-02-01T10:30:00Z" } ``` # Generate Report Source: https://docs.rotavision.com/api-reference/vishwas/generate-report POST /vishwas/reports Generate compliance-ready audit reports for AI fairness ## Request ID of a completed fairness analysis to generate report from. Report template: * `standard` - General fairness report * `rbi` - RBI AI/ML guidelines compliance * `sebi` - SEBI circular compliance * `irdai` - IRDAI AI guidelines compliance * `internal` - Internal audit format Output format: `pdf`, `html`, `json`. Sections to include. Defaults to all: * `executive_summary` * `methodology` * `metrics_detail` * `group_analysis` * `recommendations` * `appendix` Additional metadata to include in the report. Human-readable model name. Model version string. Team or individual responsible. Description of model's business use. Date of review (ISO 8601). URL to receive webhook when report is ready. ## Response Unique report identifier. The analysis this report is based on. Report status: `pending`, `generating`, `completed`, `failed`. URL to download the report (available when completed). When the download URL expires. ```bash cURL theme={null} curl -X POST https://api.rotavision.com/v1/vishwas/reports \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "analysis_id": "analysis_abc123xyz", "template": "rbi", "format": "pdf", "metadata": { "model_name": "Loan Approval Model", "model_version": "2.3.1", "model_owner": "Credit Risk Team", "business_context": "Retail loan underwriting for personal loans up to ₹10 lakhs", "review_date": "2026-02-01" } }' ``` ```python Python theme={null} from rotavision import Rotavision client = Rotavision() report = client.vishwas.generate_report( analysis_id="analysis_abc123xyz", template="rbi", format="pdf", metadata={ "model_name": "Loan Approval Model", "model_version": "2.3.1", "model_owner": "Credit Risk Team", "business_context": "Retail loan underwriting for personal loans up to ₹10 lakhs", "review_date": "2026-02-01" } ) # Poll for completion or use webhooks report = client.vishwas.get_report(report.id) if report.status == "completed": print(f"Download: {report.download_url}") ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; const client = new Rotavision(); const report = await client.vishwas.generateReport({ analysisId: 'analysis_abc123xyz', template: 'rbi', format: 'pdf', metadata: { modelName: 'Loan Approval Model', modelVersion: '2.3.1', modelOwner: 'Credit Risk Team', businessContext: 'Retail loan underwriting for personal loans up to ₹10 lakhs', reviewDate: '2026-02-01' } }); // Poll for completion const completedReport = await client.vishwas.getReport(report.id); if (completedReport.status === 'completed') { console.log(`Download: ${completedReport.downloadUrl}`); } ``` ```json 202 - Generating theme={null} { "id": "report_def456", "analysis_id": "analysis_abc123xyz", "template": "rbi", "format": "pdf", "status": "generating", "created_at": "2026-02-01T10:30:00Z" } ``` ```json 200 - Completed theme={null} { "id": "report_def456", "analysis_id": "analysis_abc123xyz", "template": "rbi", "format": "pdf", "status": "completed", "download_url": "https://storage.rotavision.com/reports/report_def456.pdf?token=...", "expires_at": "2026-02-02T10:30:00Z", "pages": 24, "sections": [ "executive_summary", "methodology", "metrics_detail", "group_analysis", "recommendations", "regulatory_mapping", "appendix" ], "created_at": "2026-02-01T10:30:00Z", "completed_at": "2026-02-01T10:31:45Z" } ``` ## Report Templates ### RBI Template The RBI template maps your fairness analysis to the Reserve Bank of India's guidelines on AI/ML in financial services: * **Section 1**: Executive summary with compliance status * **Section 2**: Model governance and documentation * **Section 3**: Fairness metrics mapped to RBI requirements * **Section 4**: Protected group analysis (gender, geography, income) * **Section 5**: Explainability assessment * **Section 6**: Recommendations and remediation plan * **Appendix**: Technical methodology and data sources ### SEBI Template For capital markets applications per SEBI circulars: * Focus on model risk assessment * Audit trail documentation * Performance monitoring requirements ### IRDAI Template For insurance applications: * Pricing fairness analysis * Claims processing equity * Underwriting bias assessment # Vishwas Overview Source: https://docs.rotavision.com/api-reference/vishwas/overview Trust, Fairness & Explainability APIs ## Introduction Vishwas provides APIs to measure and monitor fairness in AI systems, generate human-readable explanations, and create compliance-ready audit reports. Measure bias across protected attributes Generate interpretable explanations Create audit-ready compliance reports ## Key Features ### Fairness Metrics Vishwas supports 15+ industry-standard fairness metrics: | Category | Metrics | | ------------------ | ----------------------------------------------------- | | **Group Fairness** | Demographic Parity, Equalized Odds, Equal Opportunity | | **Calibration** | Calibration, Sufficiency, Balance | | **Individual** | Individual Fairness, Counterfactual Fairness | | **Causal** | Causal Discrimination, Path-Specific Effects | ### Explanation Methods | Method | Best For | | ------------------- | ------------------------------------------------- | | **SHAP** | Feature importance with game-theoretic foundation | | **LIME** | Local interpretable explanations | | **Anchors** | Rule-based explanations | | **Counterfactuals** | "What-if" scenarios | | **Prototypes** | Similar examples from training data | ### Indian Context Vishwas includes India-specific enhancements: * **Protected attributes**: Caste, religion, regional origin * **Language support**: Explanations in 12 Indian languages * **Regulatory mapping**: RBI, SEBI, IRDAI guidelines ## Quick Example ```python theme={null} from rotavision import Rotavision client = Rotavision() # Analyze fairness analysis = client.vishwas.analyze( model_id="loan-approval-v2", dataset={ "features": features, "predictions": predictions, "actuals": actuals, "protected_attributes": ["gender", "region"] }, metrics=["demographic_parity", "equalized_odds"] ) print(f"Overall Score: {analysis.overall_score}") print(f"Bias Detected: {analysis.bias_detected}") # Explain a prediction explanation = client.vishwas.explain( model_id="loan-approval-v2", input_data=applicant_features, prediction=0.73, method="shap" ) print(f"Top factors: {explanation.top_features}") ``` ## Endpoints | Method | Endpoint | Description | | ------ | ------------------------ | -------------------------- | | `POST` | `/vishwas/analyze` | Run fairness analysis | | `GET` | `/vishwas/analyses/{id}` | Get analysis results | | `GET` | `/vishwas/analyses` | List analyses | | `POST` | `/vishwas/explain` | Explain a prediction | | `POST` | `/vishwas/reports` | Generate compliance report | | `GET` | `/vishwas/reports/{id}` | Get report status/download | # Authentication Source: https://docs.rotavision.com/authentication Secure your API requests with Rotavision API keys ## Get Your API Key Click "Get API Key" to instantly receive a test key. No signup required. All API requests to Rotavision require authentication using an API key. ### Self-Service Registration 1. Visit [api.rotavision.com/docs](https://api.rotavision.com/docs) 2. Click **"Get API Key"** in the top navigation 3. Enter your email, name, and company 4. Receive your `rv_test_*` key instantly via email Test keys include 100 requests/day in the sandbox environment. For production access, [contact our team](https://rotavision.com/contact). ### Key Types | Type | Prefix | Usage | | -------- | ---------- | ----------------------- | | **Live** | `rv_live_` | Production environments | | **Test** | `rv_test_` | Development and testing | Never expose your live API keys in client-side code, public repositories, or logs. Use environment variables or a secrets manager. ## Authentication Methods ### Bearer Token (Recommended) Include your API key in the `Authorization` header: ```bash theme={null} curl https://api.rotavision.com/v1/vishwas/analyze \ -H "Authorization: Bearer rv_live_abc123..." \ -H "Content-Type: application/json" \ -d '{"model_id": "my-model"}' ``` ### Using SDKs Our SDKs handle authentication automatically: ```python Python theme={null} from rotavision import Rotavision # Option 1: Pass directly client = Rotavision(api_key="rv_live_...") # Option 2: Environment variable (recommended) # Set ROTAVISION_API_KEY in your environment client = Rotavision() ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; // Option 1: Pass directly const client = new Rotavision({ apiKey: 'rv_live_...' }); // Option 2: Environment variable (recommended) // Set ROTAVISION_API_KEY in your environment const client = new Rotavision(); ``` ```java Java theme={null} import com.rotavision.Rotavision; // Option 1: Pass directly Rotavision client = new Rotavision("rv_live_..."); // Option 2: Environment variable (recommended) // Set ROTAVISION_API_KEY in your environment Rotavision client = new Rotavision(); ``` ## API Key Scopes When creating an API key, you can restrict its permissions to specific products: | Scope | Description | | ------------------- | ------------------------------------- | | `vishwas:read` | Read fairness analyses and reports | | `vishwas:write` | Create new fairness analyses | | `guardian:read` | Read monitoring data and alerts | | `guardian:write` | Configure monitors and log inferences | | `dastavez:read` | Read extraction results | | `dastavez:write` | Submit documents for extraction | | `sankalp:proxy` | Make LLM proxy requests | | `orchestrate:read` | Read workflow executions | | `orchestrate:write` | Create and run workflows | | `gati:read` | Read fleet and route data | | `gati:write` | Submit optimization requests | ### Example: Read-Only Key ```json theme={null} { "name": "Analytics Dashboard", "scopes": [ "vishwas:read", "guardian:read", "gati:read" ] } ``` ## Organization & Project Keys For larger teams, Rotavision supports hierarchical key management: ``` Organization (Acme Corp) ├── Project: Production │ ├── Key: Backend Service (all scopes) │ └── Key: Analytics (read-only) ├── Project: Staging │ └── Key: CI/CD Pipeline └── Project: Development └── Key: Local Testing ``` Project-scoped keys inherit organization-level rate limits but can have additional restrictions applied. ## IP Allowlisting For enhanced security, you can restrict API keys to specific IP addresses or CIDR ranges: ```json theme={null} { "name": "Production Backend", "allowed_ips": [ "203.0.113.0/24", "198.51.100.42" ] } ``` ## Key Rotation We recommend rotating API keys periodically. The dashboard supports: 1. **Create new key** with the same scopes 2. **Update your application** with the new key 3. **Verify functionality** in production 4. **Revoke the old key** Use a secrets manager (AWS Secrets Manager, HashiCorp Vault, etc.) to automate key rotation without application deployments. ## Security Best Practices Never hardcode API keys in your source code. Use environment variables or a secrets manager. ```bash theme={null} export ROTAVISION_API_KEY=rv_live_... ``` Only grant the permissions your application actually needs. A monitoring dashboard doesn't need write access. Use `rv_test_` keys in development and CI/CD. Never use live keys in non-production environments. Review API key usage in your dashboard. Investigate unexpected patterns or unauthorized access attempts. For production keys, restrict access to known IP addresses of your servers. ## Rate Limits by Key Type | Key Type | Requests/min | Requests/day | Access | | ------------------- | ------------ | ------------ | ------------------------------------------------ | | Test (Self-Service) | 10 | 100 | [Get instantly](https://api.rotavision.com/docs) | | Live (Starter) | 600 | 50,000 | [Contact sales](https://rotavision.com/contact) | | Live (Growth) | 3,000 | 500,000 | [Contact sales](https://rotavision.com/contact) | | Live (Enterprise) | Custom | Custom | [Contact sales](https://rotavision.com/contact) | See [Rate Limits](/concepts/rate-limits) for detailed information. # Architecture Source: https://docs.rotavision.com/concepts/architecture Understanding the Rotavision platform architecture ## Platform Overview Rotavision is built as a modular, cloud-native platform that integrates seamlessly with your existing ML infrastructure. ```mermaid theme={null} flowchart TB subgraph Application["Your Application"] APP[Web/Mobile/Backend] end subgraph SDK["Rotavision SDK Layer"] PY[Python] NODE[Node.js] JAVA[Java] REST[REST API] end subgraph Gateway["API Gateway"] AUTH[Authentication] RATE[Rate Limiting] ROUTE[Request Routing] end subgraph Products["Product Services"] VISHWAS[Vishwas
Trust & Fairness] GUARDIAN[Guardian
Monitoring] DASTAVEZ[Dastavez
Document AI] SANKALP[Sankalp
LLM Gateway] ORCHESTRATE[Orchestrate
Multi-Agent] GATI[Gati
Fleet Intel] end subgraph Infra["Shared Infrastructure"] STORAGE[(Storage)] COMPUTE[Compute] ML[ML Runtime] ANALYTICS[Analytics] WEBHOOKS[Webhooks] end APP --> SDK PY & NODE & JAVA & REST --> Gateway AUTH & RATE & ROUTE --> Products VISHWAS & GUARDIAN & DASTAVEZ & SANKALP & ORCHESTRATE & GATI --> Infra style Application fill:#f5f5f5,stroke:#333 style Gateway fill:#010ED0,stroke:#333,color:#fff style Products fill:#6B8BFF,stroke:#333,color:#fff ``` ## Deployment Options **Rotavision Cloud** is the fastest way to get started. We manage all infrastructure, scaling, and updates. * Multi-region availability (Mumbai, Singapore) * 99.9% SLA * SOC 2 Type II compliant **Rotavision Enterprise** can be deployed in your own infrastructure for maximum data control. * Kubernetes or VM deployment * Air-gapped environments supported * Custom compliance requirements ## Data Flow ### Synchronous Requests For real-time operations (explanations, proxy requests): ```mermaid theme={null} sequenceDiagram participant C as Client participant G as API Gateway participant S as Product Service C->>G: Request Note over C,G: < 100ms G->>S: Route Request Note over G,S: < 500ms S-->>G: Response G-->>C: Response ``` ### Asynchronous Jobs For batch operations (fairness analysis, document extraction): ```mermaid theme={null} sequenceDiagram participant C as Client participant G as API Gateway participant Q as Job Queue participant W as Worker participant WH as Webhook C->>G: Submit Job Note over C,G: < 100ms G->>Q: Queue Job G-->>C: job_id Q->>W: Process Note over Q,W: seconds-minutes W->>WH: Notify Complete WH-->>C: Webhook Callback ``` Async jobs return immediately with a `job_id`. Poll the status endpoint or configure webhooks for completion notifications. ## Data Residency All data processed by Rotavision Cloud is stored in India by default: | Data Type | Storage Location | Retention | | ---------------- | ----------------------- | ---------------- | | API Requests | Mumbai (AWS ap-south-1) | 90 days | | Analysis Results | Mumbai (AWS ap-south-1) | Configurable | | Model Artifacts | Customer-specified | Customer-managed | | Logs & Metrics | Mumbai (AWS ap-south-1) | 30 days | If you use Sankalp to proxy requests to international LLM providers, your prompts may be processed outside India according to each provider's data policies. ## Security Architecture ```mermaid theme={null} flowchart LR subgraph Security["Security Layers"] direction TB T["🔒 Transport
TLS 1.3, Certificate Pinning"] AN["🔑 Authentication
API Keys, OAuth 2.0, SAML"] AZ["👤 Authorization
Scoped Keys, RBAC, Policies"] D["💾 Data Protection
AES-256 at rest, Field encryption"] N["🌐 Network
VPC isolation, Private endpoints"] A["📋 Audit
Immutable logs, SIEM integration"] end T --> AN --> AZ --> D --> N --> A style Security fill:#f8f9fa,stroke:#333 ``` ```mermaid theme={null} flowchart TB subgraph Perimeter["Network Perimeter"] WAF[Web Application Firewall] DDoS[DDoS Protection] end subgraph Auth["Authentication Layer"] API[API Key Validation] OAuth[OAuth 2.0] SAML[SAML SSO] end subgraph Core["Core Services"] ENC[Encryption Service] VAULT[Secrets Vault] AUDIT[Audit Logger] end subgraph Data["Data Layer"] DB[(Encrypted Storage)] LOGS[(Immutable Logs)] end Perimeter --> Auth --> Core --> Data style Perimeter fill:#fee2e2,stroke:#991b1b style Auth fill:#fef3c7,stroke:#92400e style Core fill:#dbeafe,stroke:#1e40af style Data fill:#dcfce7,stroke:#166534 ``` ## Integration Patterns ### Direct Integration Call Rotavision APIs directly from your application: ```python theme={null} # In your ML serving code prediction = model.predict(features) explanation = rotavision.vishwas.explain(model_id, features, prediction) ``` ### Sidecar Pattern Deploy Rotavision as a sidecar container for transparent monitoring: ```yaml theme={null} # Kubernetes deployment containers: - name: ml-model image: your-model:v1 - name: rotavision-sidecar image: rotavision/guardian-agent:latest env: - name: ROTAVISION_API_KEY valueFrom: secretKeyRef: name: rotavision-credentials key: api-key ``` ### Event-Driven Process events asynchronously via message queues: ```mermaid theme={null} flowchart LR MS[Model Service] --> MQ[Kafka / SQS] MQ --> RC[Rotavision Consumer] RC --> ST[(Storage)] RC --> WH[Webhook Notifications] style MS fill:#f5f5f5,stroke:#333 style MQ fill:#ff6b6b,stroke:#333,color:#fff style RC fill:#010ED0,stroke:#333,color:#fff style ST fill:#22c55e,stroke:#333,color:#fff ``` ## Product Integration Flow ```mermaid theme={null} flowchart TB subgraph Input["Input Sources"] API_REQ[API Request] WEBHOOK_IN[Webhook Event] BATCH[Batch Upload] end subgraph Processing["Rotavision Processing"] direction TB subgraph Trust["Trust Layer"] V_ANALYZE[Vishwas Analyze] V_EXPLAIN[Vishwas Explain] end subgraph Monitor["Monitoring Layer"] G_DETECT[Guardian Detect] G_ALERT[Guardian Alert] end subgraph Intelligence["Intelligence Layer"] D_EXTRACT[Dastavez Extract] S_PROXY[Sankalp Proxy] O_RUN[Orchestrate Run] end end subgraph Output["Output Channels"] RESPONSE[API Response] WEBHOOK_OUT[Webhook Callback] DASHBOARD[Dashboard] end Input --> Processing --> Output style Trust fill:#dcfce7,stroke:#166534 style Monitor fill:#fef3c7,stroke:#92400e style Intelligence fill:#dbeafe,stroke:#1e40af ``` ## High Availability Rotavision Cloud is designed for 99.9% availability: * **Multi-AZ deployment** within Mumbai region * **Automatic failover** for all stateful services * **Circuit breakers** prevent cascade failures * **Graceful degradation** maintains core functionality during partial outages ```mermaid theme={null} flowchart TB subgraph Region["Mumbai Region (ap-south-1)"] subgraph AZ1["Availability Zone 1"] LB1[Load Balancer] APP1[App Servers] DB1[(Primary DB)] end subgraph AZ2["Availability Zone 2"] LB2[Load Balancer] APP2[App Servers] DB2[(Replica DB)] end subgraph AZ3["Availability Zone 3"] LB3[Load Balancer] APP3[App Servers] DB3[(Replica DB)] end end GLB[Global Load Balancer] --> LB1 & LB2 & LB3 DB1 -.->|Replication| DB2 & DB3 style Region fill:#f5f5f5,stroke:#333 style AZ1 fill:#dcfce7,stroke:#166534 style AZ2 fill:#dbeafe,stroke:#1e40af style AZ3 fill:#fef3c7,stroke:#92400e ``` See our [Status Page](/status) for real-time availability. # Rate Limits Source: https://docs.rotavision.com/concepts/rate-limits Understanding API rate limits and quotas ## Overview Rotavision applies rate limits to ensure fair usage and platform stability. Limits are applied per API key and vary by plan. ## Rate Limit Tiers | Plan | Requests/min | Requests/day | Concurrent | | -------------- | -----------: | -----------: | ---------: | | **Free** | 20 | 500 | 2 | | **Starter** | 60 | 5,000 | 5 | | **Growth** | 600 | 50,000 | 20 | | **Enterprise** | 3,000 | 500,000 | 100 | | **Custom** | Unlimited | Unlimited | Custom | Enterprise and Custom plans can request higher limits. Contact [sales@rotavision.com](mailto:sales@rotavision.com). ## Product-Specific Limits Some products have additional limits beyond the base rate: ### Vishwas (Fairness Analysis) | Operation | Limit | Notes | | ----------------- | ---------: | ---------------------- | | `analyze` | 100/hour | Per model\_id | | `explain` | 1,000/hour | Real-time explanations | | `generate_report` | 20/hour | PDF generation | ### Guardian (Monitoring) | Operation | Limit | Notes | | ---------------- | ---------: | ----------------------- | | `log_inference` | 10,000/min | High-throughput logging | | `create_monitor` | 100/day | Monitor creation | | `get_alerts` | 600/min | Alert retrieval | ### Dastavez (Document AI) | Operation | Limit | Notes | | -------------- | ------: | ---------------------- | | `extract` | 100/min | Document extraction | | `create_agent` | 20/hour | Browser agent creation | | File size | 50 MB | Per document | ### Sankalp (LLM Gateway) | Operation | Limit | Notes | | ---------------- | ---------: | --------------------------- | | `proxy` | Plan limit | Passthrough to LLM provider | | Token throughput | Plan-based | Input + output tokens | ### Orchestrate (Workflows) | Operation | Limit | Notes | | ----------------- | -------: | -------------------- | | `create_workflow` | 50/hour | Workflow definitions | | `run_workflow` | 500/hour | Workflow executions | | Concurrent runs | 10-100 | Plan-based | ### Gati (Fleet Intelligence) | Operation | Limit | Notes | | -------------------- | ---------: | ------------------ | | `optimize_routes` | 100/hour | Route optimization | | `track_fleet` | 10,000/min | Vehicle tracking | | Vehicles per request | 1,000 | Route optimization | ## Rate Limit Headers Every API response includes rate limit information: ``` X-RateLimit-Limit: 600 X-RateLimit-Remaining: 542 X-RateLimit-Reset: 1706780400 ``` | Header | Description | | ----------------------- | -------------------------------------- | | `X-RateLimit-Limit` | Maximum requests allowed in the window | | `X-RateLimit-Remaining` | Requests remaining in current window | | `X-RateLimit-Reset` | Unix timestamp when the window resets | ## Handling Rate Limits When you exceed a rate limit, you'll receive a `429 Too Many Requests` response: ```json theme={null} { "error": { "code": "rate_limit_exceeded", "message": "Rate limit exceeded. Retry after 30 seconds.", "type": "rate_limit_error" } } ``` The response includes a `Retry-After` header indicating when to retry: ``` Retry-After: 30 ``` ### Recommended Retry Strategy ```python Python theme={null} import time from rotavision import Rotavision from rotavision.exceptions import RateLimitError client = Rotavision() def call_with_backoff(func, max_retries=5): for attempt in range(max_retries): try: return func() except RateLimitError as e: if attempt == max_retries - 1: raise # Use Retry-After header or exponential backoff wait_time = e.retry_after or (2 ** attempt) print(f"Rate limited. Waiting {wait_time}s...") time.sleep(wait_time) # Usage result = call_with_backoff( lambda: client.vishwas.analyze(model_id="my-model", dataset=data) ) ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; import { RateLimitError } from '@rotavision/sdk/errors'; const client = new Rotavision(); async function callWithBackoff( fn: () => Promise, maxRetries = 5 ): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await fn(); } catch (e) { if (!(e instanceof RateLimitError) || attempt === maxRetries - 1) { throw e; } const waitTime = e.retryAfter || Math.pow(2, attempt); console.log(`Rate limited. Waiting ${waitTime}s...`); await new Promise(resolve => setTimeout(resolve, waitTime * 1000)); } } throw new Error('Max retries exceeded'); } // Usage const result = await callWithBackoff(() => client.vishwas.analyze({ modelId: 'my-model', dataset: data }) ); ``` ## Best Practices Don't retry immediately after a rate limit. Use exponential backoff with jitter to avoid thundering herd. Cache analysis results and explanations that don't change frequently to reduce API calls. For Guardian logging, use batch endpoints to send multiple inferences in one request. ```python theme={null} # Instead of for inference in inferences: client.guardian.log_inference(inference) # Use batch endpoint client.guardian.log_inferences(inferences) # Up to 1000 per call ``` Track your rate limit headers and set up alerts before hitting limits. For async operations, use webhooks instead of polling status endpoints. ## Quota Management Beyond rate limits, some resources have monthly quotas: | Resource | Starter | Growth | Enterprise | | -------------------- | ------: | -----: | ---------: | | Documents processed | 1,000 | 10,000 | 100,000+ | | LLM tokens (Sankalp) | 1M | 10M | 100M+ | | Storage (GB) | 10 | 100 | 1,000+ | | Monitors | 5 | 25 | Unlimited | Check your quota usage in the dashboard or via API: ```bash theme={null} curl https://api.rotavision.com/v1/usage \ -H "Authorization: Bearer rv_live_..." ``` ```json theme={null} { "period": "2026-02", "documents_processed": 847, "documents_limit": 10000, "tokens_used": 2450000, "tokens_limit": 10000000, "storage_used_gb": 12.4, "storage_limit_gb": 100 } ``` ## Requesting Higher Limits If you need higher rate limits: 1. **Growth Plan**: Upgrade via dashboard for 10x limits 2. **Enterprise Plan**: Contact sales for custom limits 3. **Temporary Increase**: Contact support for short-term increases during migrations or load tests # Trust Scores Source: https://docs.rotavision.com/concepts/trust-scores Understanding Rotavision's AI trust measurement framework ## Overview Rotavision's trust scoring system provides a unified framework for measuring AI system trustworthiness across multiple dimensions. Each dimension is scored from 0-100, with higher scores indicating greater trustworthiness. ## Trust Dimensions Measures equitable treatment across protected groups Measures consistency and stability of predictions Measures how well predictions can be understood Measures data protection and privacy preservation ## Overall Trust Score The overall trust score is a weighted combination of individual dimensions: ``` Trust Score = Σ (dimension_score × dimension_weight) ``` Default weights are: * Fairness: 30% * Reliability: 30% * Explainability: 25% * Privacy: 15% Weights can be customized based on your industry and regulatory requirements. Financial services often increase fairness weight, while healthcare may prioritize explainability. ## Fairness Metrics Vishwas calculates fairness using industry-standard metrics: | Metric | Description | Threshold | | --------------------------- | ----------------------------------------------------- | --------- | | **Demographic Parity** | Equal positive prediction rates across groups | ≥ 0.80 | | **Equalized Odds** | Equal TPR and FPR across groups | ≥ 0.80 | | **Calibration** | Predicted probabilities match actual outcomes | ≥ 0.80 | | **Individual Fairness** | Similar individuals receive similar predictions | ≥ 0.75 | | **Counterfactual Fairness** | Predictions unchanged if protected attributes changed | ≥ 0.80 | ### Calculating Demographic Parity ```python theme={null} # Demographic parity ratio dp_ratio = P(Ŷ=1 | A=minority) / P(Ŷ=1 | A=majority) # Score (0-100) fairness_score = min(dp_ratio, 1/dp_ratio) * 100 ``` ### Multi-Group Fairness For attributes with multiple groups (e.g., states, languages), Rotavision calculates: 1. **Pairwise ratios** between all group pairs 2. **Minimum ratio** as the fairness bound 3. **Weighted average** based on group sizes ## Reliability Metrics Guardian monitors reliability through: | Metric | Description | Alert Threshold | | -------------------- | ------------------------------------ | --------------- | | **Prediction Drift** | KL divergence of output distribution | > 0.1 | | **Feature Drift** | PSI of input features | > 0.2 | | **Accuracy Decay** | Drop in monitored accuracy metric | > 5% | | **Latency P99** | 99th percentile response time | > SLA | | **Error Rate** | Percentage of failed predictions | > 1% | ### Drift Detection ```python theme={null} # Population Stability Index (PSI) psi = Σ (actual_% - expected_%) × ln(actual_% / expected_%) # Interpretation # PSI < 0.1 → No significant drift # PSI 0.1-0.2 → Moderate drift (monitor) # PSI > 0.2 → Significant drift (investigate) ``` ## Explainability Scores Measured through explanation quality metrics: | Metric | Description | | --------------------- | -------------------------------------------------- | | **Faithfulness** | How accurately explanations reflect model behavior | | **Stability** | Consistency of explanations for similar inputs | | **Comprehensibility** | Human-understandable explanation complexity | | **Completeness** | Coverage of important features in explanations | ## Score Interpretation Model meets highest trust standards. Suitable for high-stakes decisions with minimal additional oversight. Model is generally trustworthy. Consider targeted improvements for specific dimensions below threshold. Significant trust gaps exist. Recommend human oversight and remediation plan before production use. Model does not meet minimum trust requirements. Do not deploy without major improvements. ## Industry Benchmarks Based on our analysis of enterprise AI deployments in India: | Industry | Average Trust Score | Top Quartile | | ----------------- | ------------------: | -----------: | | Banking & Finance | 72 | 85+ | | Insurance | 68 | 82+ | | Healthcare | 65 | 80+ | | E-commerce | 70 | 83+ | | Telecom | 74 | 86+ | ## Regulatory Alignment Rotavision trust scores map to regulatory requirements: | Regulation | Relevant Dimensions | | ------------------- | ------------------------- | | RBI AI Guidelines | Fairness, Explainability | | DPDP Act 2023 | Privacy, Transparency | | SEBI ML Circular | Reliability, Auditability | | IRDAI AI Guidelines | Fairness, Explainability | Generate compliance-ready reports with `vishwas.generate_report()` that map your scores to specific regulatory requirements. ## Improving Trust Scores Review dimension-level scores to find areas below threshold Use Vishwas explanations to understand why specific metrics are low Apply recommended techniques (resampling, threshold adjustment, etc.) Set up Guardian alerts to catch score degradation early # Webhooks Source: https://docs.rotavision.com/concepts/webhooks Receive real-time notifications for Rotavision events ## Overview Webhooks allow you to receive HTTP callbacks when events occur in your Rotavision account. Instead of polling for status updates, webhooks push data to your server in real-time. ## Supported Events | Event | Description | | ---------------------- | --------------------------------- | | `analysis.completed` | Fairness analysis job finished | | `analysis.failed` | Fairness analysis job failed | | `alert.triggered` | Guardian alert threshold exceeded | | `alert.resolved` | Guardian alert returned to normal | | `extraction.completed` | Document extraction finished | | `extraction.failed` | Document extraction failed | | `workflow.completed` | Orchestrate workflow finished | | `workflow.failed` | Orchestrate workflow failed | ## Setting Up Webhooks ### Via Dashboard 1. Go to **Settings → Webhooks** in your dashboard 2. Click **Add Endpoint** 3. Enter your endpoint URL 4. Select events to subscribe to 5. Save and note your signing secret ### Via API ```bash theme={null} curl -X POST https://api.rotavision.com/v1/webhooks \ -H "Authorization: Bearer rv_live_..." \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/webhooks/rotavision", "events": ["analysis.completed", "alert.triggered"], "description": "Production webhook" }' ``` Response: ```json theme={null} { "id": "wh_abc123", "url": "https://your-app.com/webhooks/rotavision", "events": ["analysis.completed", "alert.triggered"], "secret": "whsec_xyz789...", "status": "active", "created_at": "2026-02-01T10:00:00Z" } ``` Store your webhook secret securely. You'll need it to verify incoming webhooks. ## Webhook Payload All webhooks follow this structure: ```json theme={null} { "id": "evt_abc123", "type": "analysis.completed", "created_at": "2026-02-01T10:30:00Z", "data": { "id": "analysis_xyz789", "model_id": "loan-approval-v2", "overall_score": 0.82, "status": "completed" } } ``` ## Verifying Signatures All webhooks are signed using HMAC-SHA256. Verify the signature to ensure the webhook came from Rotavision: ```python Python theme={null} import hmac import hashlib def verify_webhook(payload: bytes, signature: str, secret: str) -> bool: expected = hmac.new( secret.encode(), payload, hashlib.sha256 ).hexdigest() return hmac.compare_digest(f"sha256={expected}", signature) # In your webhook handler @app.post("/webhooks/rotavision") def handle_webhook(request): payload = request.body signature = request.headers.get("X-Rotavision-Signature") if not verify_webhook(payload, signature, WEBHOOK_SECRET): return Response(status=401) event = json.loads(payload) # Process event... ``` ```typescript Node.js theme={null} import crypto from 'crypto'; function verifyWebhook( payload: string, signature: string, secret: string ): boolean { const expected = crypto .createHmac('sha256', secret) .update(payload) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(`sha256=${expected}`), Buffer.from(signature) ); } // In your webhook handler (Express) app.post('/webhooks/rotavision', (req, res) => { const payload = req.rawBody; const signature = req.headers['x-rotavision-signature']; if (!verifyWebhook(payload, signature, WEBHOOK_SECRET)) { return res.status(401).send('Invalid signature'); } const event = JSON.parse(payload); // Process event... }); ``` ```java Java theme={null} import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.security.MessageDigest; public boolean verifyWebhook(String payload, String signature, String secret) { try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256")); byte[] hash = mac.doFinal(payload.getBytes()); String expected = "sha256=" + bytesToHex(hash); return MessageDigest.isEqual(expected.getBytes(), signature.getBytes()); } catch (Exception e) { return false; } } ``` ## Handling Webhooks ### Best Practices Return a `200` response within 5 seconds. Process the event asynchronously if needed. ```python theme={null} @app.post("/webhooks/rotavision") def handle_webhook(request): # Verify and enqueue event = verify_and_parse(request) queue.enqueue(process_event, event) return Response(status=200) # Respond immediately ``` Webhooks may be delivered multiple times. Use the `id` field for idempotency. ```python theme={null} def process_event(event): if redis.sismember("processed_events", event["id"]): return # Already processed # Process event... redis.sadd("processed_events", event["id"]) redis.expire("processed_events", 86400) # 24 hour TTL ``` Always verify the `X-Rotavision-Signature` header before processing. If processing fails, return a non-2xx status. We'll retry with exponential backoff. ### Retry Policy Failed webhook deliveries are retried with exponential backoff: | Attempt | Delay | | ------- | ---------- | | 1 | Immediate | | 2 | 1 minute | | 3 | 5 minutes | | 4 | 30 minutes | | 5 | 2 hours | | 6 | 8 hours | | 7 | 24 hours | After 7 failed attempts, the webhook is marked as failed and you'll receive an email notification. ## Testing Webhooks ### Using the CLI ```bash theme={null} rotavision webhooks trigger analysis.completed \ --endpoint wh_abc123 \ --data '{"model_id": "test-model"}' ``` ### Using the Dashboard 1. Go to **Settings → Webhooks** 2. Click on your endpoint 3. Click **Send Test Event** 4. Select an event type 5. Review the delivery log ## Event Reference ### analysis.completed ```json theme={null} { "id": "evt_abc123", "type": "analysis.completed", "created_at": "2026-02-01T10:30:00Z", "data": { "id": "analysis_xyz789", "model_id": "loan-approval-v2", "overall_score": 0.82, "bias_detected": true, "metrics_summary": { "demographic_parity": 0.78, "equalized_odds": 0.91, "calibration": 0.85 }, "report_url": "https://dashboard.rotavision.com/reports/analysis_xyz789" } } ``` ### alert.triggered ```json theme={null} { "id": "evt_def456", "type": "alert.triggered", "created_at": "2026-02-01T10:30:00Z", "data": { "id": "alert_uvw123", "monitor_id": "mon_abc789", "model_id": "recommendation-v3", "metric": "prediction_drift", "value": 0.25, "threshold": 0.1, "severity": "high", "message": "Significant prediction drift detected (PSI: 0.25)" } } ``` ### extraction.completed ```json theme={null} { "id": "evt_ghi789", "type": "extraction.completed", "created_at": "2026-02-01T10:30:00Z", "data": { "id": "extract_mno456", "document_type": "aadhaar", "confidence": 0.97, "fields": { "name": "राहुल शर्मा", "name_english": "Rahul Sharma", "dob": "1990-05-15", "gender": "Male", "aadhaar_number": "XXXX-XXXX-1234" } } } ``` # Errors Source: https://docs.rotavision.com/errors Understanding and handling Rotavision API errors ## Error Response Format All API errors follow a consistent JSON structure: ```json theme={null} { "error": { "code": "invalid_request", "message": "The 'model_id' field is required", "type": "validation_error", "param": "model_id", "request_id": "req_abc123xyz" } } ``` | Field | Description | | ------------ | --------------------------------------------------- | | `code` | Machine-readable error code | | `message` | Human-readable description | | `type` | Error category | | `param` | The parameter that caused the error (if applicable) | | `request_id` | Unique identifier for debugging | ## HTTP Status Codes | Status | Description | | ------ | ----------------------------------------- | | `200` | Success | | `201` | Created | | `400` | Bad Request - Invalid parameters | | `401` | Unauthorized - Invalid or missing API key | | `403` | Forbidden - Insufficient permissions | | `404` | Not Found - Resource doesn't exist | | `409` | Conflict - Resource already exists | | `422` | Unprocessable Entity - Validation failed | | `429` | Too Many Requests - Rate limit exceeded | | `500` | Internal Server Error | | `503` | Service Unavailable - Temporary outage | ## Error Types ### Authentication Errors ```json theme={null} { "error": { "code": "invalid_api_key", "message": "The API key provided is invalid or has been revoked", "type": "authentication_error" } } ``` **Common causes:** * API key is malformed or incorrect * Key has been revoked * Key doesn't have required scopes ### Validation Errors ```json theme={null} { "error": { "code": "invalid_request", "message": "The 'metrics' field must contain at least one valid metric", "type": "validation_error", "param": "metrics" } } ``` **Common causes:** * Missing required fields * Invalid field values or types * Array/object constraints violated ### Rate Limit Errors ```json theme={null} { "error": { "code": "rate_limit_exceeded", "message": "Rate limit exceeded. Retry after 30 seconds.", "type": "rate_limit_error" } } ``` The response includes headers to help you handle rate limits: ``` X-RateLimit-Limit: 600 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1706780400 Retry-After: 30 ``` ### Resource Errors ```json theme={null} { "error": { "code": "model_not_found", "message": "No model found with ID 'loan-model-v3'", "type": "not_found_error", "param": "model_id" } } ``` ## Handling Errors in SDKs Our SDKs throw typed exceptions that you can catch and handle: ```python Python theme={null} from rotavision import Rotavision from rotavision.exceptions import ( AuthenticationError, ValidationError, RateLimitError, NotFoundError, RotavisionError ) client = Rotavision() try: result = client.vishwas.analyze(model_id="my-model", dataset=data) except AuthenticationError as e: print(f"Check your API key: {e.message}") except ValidationError as e: print(f"Invalid request: {e.message} (param: {e.param})") except RateLimitError as e: print(f"Rate limited. Retry after {e.retry_after} seconds") except NotFoundError as e: print(f"Resource not found: {e.message}") except RotavisionError as e: print(f"API error: {e.message} (request_id: {e.request_id})") ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; import { AuthenticationError, ValidationError, RateLimitError, NotFoundError, RotavisionError } from '@rotavision/sdk/errors'; const client = new Rotavision(); try { const result = await client.vishwas.analyze({ modelId: 'my-model', dataset: data }); } catch (e) { if (e instanceof AuthenticationError) { console.log(`Check your API key: ${e.message}`); } else if (e instanceof ValidationError) { console.log(`Invalid request: ${e.message} (param: ${e.param})`); } else if (e instanceof RateLimitError) { console.log(`Rate limited. Retry after ${e.retryAfter} seconds`); } else if (e instanceof NotFoundError) { console.log(`Resource not found: ${e.message}`); } else if (e instanceof RotavisionError) { console.log(`API error: ${e.message} (request_id: ${e.requestId})`); } } ``` ```java Java theme={null} import com.rotavision.Rotavision; import com.rotavision.exceptions.*; Rotavision client = new Rotavision(); try { Vishwas.AnalyzeResult result = client.vishwas().analyze(request); } catch (AuthenticationException e) { System.out.println("Check your API key: " + e.getMessage()); } catch (ValidationException e) { System.out.println("Invalid request: " + e.getMessage()); } catch (RateLimitException e) { System.out.println("Rate limited. Retry after " + e.getRetryAfter() + " seconds"); } catch (NotFoundException e) { System.out.println("Resource not found: " + e.getMessage()); } catch (RotavisionException e) { System.out.println("API error: " + e.getMessage()); } ``` ## Retry Strategy For transient errors (rate limits, 5xx errors), we recommend exponential backoff: ```python Python theme={null} import time from rotavision import Rotavision from rotavision.exceptions import RateLimitError, RotavisionError def call_with_retry(func, max_retries=3): for attempt in range(max_retries): try: return func() except RateLimitError as e: if attempt == max_retries - 1: raise time.sleep(e.retry_after or (2 ** attempt)) except RotavisionError as e: if e.status_code < 500 or attempt == max_retries - 1: raise time.sleep(2 ** attempt) ``` Our SDKs include built-in retry logic with configurable settings. Check the SDK documentation for details. ## Debugging When contacting support, always include the `request_id` from the error response: ``` Request ID: req_abc123xyz Error: rate_limit_exceeded Timestamp: 2026-02-01T10:30:00Z ``` You can also find request IDs in the `X-Request-Id` response header for successful requests. # Bias Detection Guide Source: https://docs.rotavision.com/guides/bias-detection Detect and mitigate bias in your AI models ## Overview This guide walks through using Vishwas to detect and address bias in machine learning models, with a focus on Indian regulatory requirements and protected attributes. ## Prerequisites * Rotavision account with Vishwas access * Model predictions and ground truth labels * Identified protected attributes (gender, region, etc.) ## Step 1: Prepare Your Data ```python theme={null} import pandas as pd from rotavision import Rotavision client = Rotavision() # Load your dataset df = pd.read_csv("loan_applications.csv") # Prepare for analysis dataset = { "features": df.columns.tolist(), "data": df.values.tolist(), "predictions": df["model_prediction"].tolist(), "actuals": df["approved"].tolist(), "protected_attributes": ["gender", "region", "age_group"] } ``` ## Step 2: Run Fairness Analysis ```python theme={null} analysis = client.vishwas.analyze( model_id="loan-approval-v2", dataset=dataset, metrics=[ "demographic_parity", "equalized_odds", "equal_opportunity", "calibration" ], thresholds={ "demographic_parity": 0.80, # 80% threshold "equalized_odds": 0.80 } ) print(f"Overall Fairness Score: {analysis.overall_score:.2f}") print(f"Bias Detected: {analysis.bias_detected}") ``` ## Step 3: Interpret Results ```python theme={null} for metric in analysis.metrics: status_icon = "✅" if metric.status == "pass" else "⚠️" print(f"{status_icon} {metric.name}: {metric.value:.3f} (threshold: {metric.threshold})") if metric.affected_groups: print(f" Affected groups: {', '.join(metric.affected_groups)}") ``` ### Example Output ``` ⚠️ demographic_parity: 0.72 (threshold: 0.80) Affected groups: region:rural, gender:female ✅ equalized_odds: 0.85 (threshold: 0.80) ✅ equal_opportunity: 0.88 (threshold: 0.80) ✅ calibration: 0.91 (threshold: 0.80) ``` ## Step 4: Review Recommendations ```python theme={null} for rec in analysis.recommendations: print(f"[{rec.severity.upper()}] {rec.message}") print(f" Action: {rec.action}") print(f" Expected impact: {rec.impact_estimate}") print() ``` ## Step 5: Generate Compliance Report ```python theme={null} report = client.vishwas.generate_report( analysis_id=analysis.id, template="rbi", # RBI compliance format format="pdf", metadata={ "model_name": "Loan Approval Model v2", "model_owner": "Credit Risk Team", "review_date": "2026-02-01" } ) # Download report print(f"Report URL: {report.download_url}") ``` ## Common Mitigation Strategies Balance training data across protected groups: ```python theme={null} from sklearn.utils import resample # Oversample minority groups df_majority = df[df.gender == 'male'] df_minority = df[df.gender == 'female'] df_minority_upsampled = resample( df_minority, replace=True, n_samples=len(df_majority) ) ``` Apply different decision thresholds per group: ```python theme={null} # Post-processing threshold adjustment thresholds = { "urban": 0.50, "rural": 0.45, # Lower threshold for disadvantaged group } ``` Remove or transform proxy features: ```python theme={null} # Remove features highly correlated with protected attributes corr = df[['prediction', 'pincode', 'region']].corr() # Consider removing 'pincode' if it's a proxy for region ``` ## Indian Regulatory Context ### RBI Guidelines The RBI requires fairness analysis for AI/ML models used in: * Credit scoring and lending decisions * Customer segmentation * Fraud detection Key requirements: * Document protected attributes considered * Quantify disparate impact * Implement ongoing monitoring ### Protected Attributes in India Common protected attributes to analyze: * **Gender**: Male, Female, Other * **Region**: Urban, Semi-urban, Rural * **State**: Geographic bias across states * **Language**: Language preference as proxy * **Age**: Age-based discrimination Caste and religion are highly sensitive in India. Consult legal counsel before including in analysis, even for bias detection purposes. ## Continuous Monitoring Set up Guardian to monitor fairness drift in production: ```python theme={null} monitor = client.guardian.create_monitor( model_id="loan-approval-v2", name="Fairness Monitor", metrics=["prediction_drift"], alerts=[ { "metric": "prediction_drift", "threshold": 0.15, "severity": "warning", "group_by": "region" # Monitor drift per region } ] ) ``` ## Next Steps Generate explanations for model decisions Set up continuous fairness monitoring # Document Extraction Guide Source: https://docs.rotavision.com/guides/document-extraction Extract data from Indian documents with Dastavez ## Overview Dastavez provides intelligent document extraction optimized for Indian documents including Aadhaar, PAN, GST invoices, and more. This guide covers common extraction workflows. ## Supported Documents | Category | Documents | | ------------- | ------------------------------------------------- | | **Identity** | Aadhaar, PAN, Voter ID, Passport, Driving License | | **Financial** | Bank Statements, ITR, Form 16, Salary Slips | | **Business** | GST Invoice, GST Returns, Company Registration | | **Legal** | Property Documents, Rental Agreements | ## Basic Extraction ```python theme={null} from rotavision import Rotavision client = Rotavision() # Extract from Aadhaar card result = client.dastavez.extract( document_type="aadhaar", file_url="https://storage.example.com/aadhaar-scan.pdf" ) print(f"Name: {result.fields['name']}") print(f"Name (English): {result.fields['name_english']}") print(f"DOB: {result.fields['dob']}") print(f"Confidence: {result.confidence}") ``` ## Extracting from Different Sources ### From URL ```python theme={null} result = client.dastavez.extract( document_type="pan", file_url="https://storage.example.com/pan-card.jpg" ) ``` ### From File Upload ```python theme={null} with open("document.pdf", "rb") as f: result = client.dastavez.extract( document_type="gst_invoice", file=f ) ``` ### From Base64 ```python theme={null} import base64 with open("document.pdf", "rb") as f: base64_content = base64.b64encode(f.read()).decode() result = client.dastavez.extract( document_type="bank_statement", file_base64=base64_content ) ``` ## Document-Specific Examples ### Aadhaar Card ```python theme={null} result = client.dastavez.extract( document_type="aadhaar", file_url="...", options={ "mask_number": True, # Returns XXXX-XXXX-1234 "extract_photo": True } ) # Fields extracted: # - name (in original script) # - name_english # - dob # - gender # - aadhaar_number (masked if option set) # - address (full, line1, line2, city, state, pincode) # - photo (if extract_photo=True) ``` ### GST Invoice ```python theme={null} result = client.dastavez.extract( document_type="gst_invoice", file_url="..." ) # Fields extracted: # - invoice_number # - invoice_date # - seller (name, gstin, address) # - buyer (name, gstin, address) # - items[] (description, hsn_code, quantity, unit_price, total) # - subtotal, cgst, sgst, igst, total # - amount_in_words ``` ### Bank Statement ```python theme={null} result = client.dastavez.extract( document_type="bank_statement", file_url="...", options={ "mask_account": True } ) # Fields extracted: # - bank_name # - account_number (masked) # - account_holder # - statement_period (from, to) # - opening_balance # - closing_balance # - transactions[] (date, description, debit, credit, balance) ``` ## Handling Multi-Page Documents For documents with multiple pages (like bank statements): ```python theme={null} result = client.dastavez.extract( document_type="bank_statement", file_url="...", options={ "pages": "all" # or "1-5" or [1, 3, 5] } ) # Transactions are aggregated across all pages print(f"Total transactions: {len(result.fields['transactions'])}") ``` ## Validation and Quality ### Check Confidence Scores ```python theme={null} result = client.dastavez.extract( document_type="aadhaar", file_url="..." ) if result.confidence < 0.9: print("Warning: Low confidence extraction") print(f"Confidence: {result.confidence}") # Per-field confidence for field, value in result.fields.items(): if hasattr(value, 'confidence'): print(f"{field}: {value.value} (confidence: {value.confidence})") ``` ### Validation Checks ```python theme={null} # Built-in validation for Indian documents if result.validation['checksum_valid']: print("Document checksum verified") else: print("Warning: Checksum validation failed") # Aadhaar Verhoeff check if result.validation.get('verhoeff_check') == 'pass': print("Aadhaar number is valid") ``` ## Multi-Language Support Dastavez supports extraction from documents in 12 Indian languages: ```python theme={null} result = client.dastavez.extract( document_type="aadhaar", file_url="...", options={ "language_hint": "hi" # Hindi # Supported: hi, ta, te, bn, mr, gu, kn, ml, pa, or, as, en } ) # Names and addresses are returned in both original script and transliterated print(f"Name (original): {result.fields['name']}") print(f"Name (English): {result.fields['name_english']}") ``` ## Error Handling ```python theme={null} from rotavision.exceptions import ( ValidationError, DocumentProcessingError ) try: result = client.dastavez.extract( document_type="aadhaar", file_url="..." ) except ValidationError as e: print(f"Invalid input: {e.message}") except DocumentProcessingError as e: if e.code == "unreadable_document": print("Document image is too blurry or damaged") elif e.code == "wrong_document_type": print("Document doesn't match specified type") else: print(f"Processing error: {e.message}") ``` ## Best Practices * Minimum 300 DPI for scanned documents * Ensure good lighting and contrast * Avoid shadows and glare * Dastavez auto-enhances images, but quality input = better results * Use `mask_number: True` for Aadhaar * Use `mask_account: True` for bank statements * Store extracted PII securely * Delete source documents after processing if not needed For high-volume processing: ```python theme={null} # Submit multiple documents jobs = [] for doc_url in document_urls: job = client.dastavez.extract_async( document_type="auto", file_url=doc_url ) jobs.append(job) # Collect results for job in jobs: result = client.dastavez.get_extraction(job.id) ``` ## Next Steps Automate document retrieval from portals Full API documentation # Model Monitoring Guide Source: https://docs.rotavision.com/guides/model-monitoring Set up production monitoring with Guardian ## Overview Guardian provides real-time monitoring for AI models in production. This guide covers setting up comprehensive monitoring for drift detection, performance tracking, and alerting. ## Quick Start ```python theme={null} from rotavision import Rotavision client = Rotavision() # Create a monitor monitor = client.guardian.create_monitor( model_id="recommendation-v3", name="Prod Recommendations", metrics=["prediction_drift", "data_drift", "latency_p99", "error_rate"], alerts=[ {"metric": "prediction_drift", "threshold": 0.1, "severity": "warning"}, {"metric": "prediction_drift", "threshold": 0.2, "severity": "critical"}, {"metric": "error_rate", "threshold": 0.01, "severity": "critical"}, ] ) print(f"Monitor created: {monitor.id}") ``` ## Integrating with Your Serving Code ### Basic Integration ```python theme={null} # In your model serving code import time from rotavision import Rotavision client = Rotavision() MONITOR_ID = "mon_abc123" def predict(features): start = time.time() try: prediction = model.predict(features) latency_ms = (time.time() - start) * 1000 # Log to Guardian client.guardian.log_inference( monitor_id=MONITOR_ID, input_data=features, prediction=prediction, latency_ms=latency_ms ) return prediction except Exception as e: # Log error client.guardian.log_inference( monitor_id=MONITOR_ID, input_data=features, error={"code": type(e).__name__, "message": str(e)} ) raise ``` ### Async/Batch Integration (Recommended) For production workloads, use async logging to minimize latency impact: ```python theme={null} from rotavision.logging import AsyncLogger # Create async logger logger = AsyncLogger( api_key="rv_live_...", monitor_id="mon_abc123", batch_size=100, # Send in batches of 100 flush_interval_ms=1000 # Or flush every second ) def predict(features): start = time.time() prediction = model.predict(features) latency_ms = (time.time() - start) * 1000 # Non-blocking log logger.log( input_data=features, prediction=prediction, latency_ms=latency_ms ) return prediction # Flush on shutdown import atexit atexit.register(logger.flush) ``` ## Setting Up Drift Detection ### Establishing Baseline Guardian needs a baseline distribution to detect drift: ```python theme={null} # Option 1: Use historical data monitor = client.guardian.create_monitor( model_id="my-model", name="Production Monitor", metrics=["prediction_drift", "data_drift"], baseline={ "data_url": "s3://my-bucket/baseline-data.parquet" } ) # Option 2: Use rolling window (learns from recent production data) monitor = client.guardian.create_monitor( model_id="my-model", name="Production Monitor", metrics=["prediction_drift", "data_drift"], baseline={ "window": "30d" # Use last 30 days as baseline } ) ``` ### Drift Metrics | Metric | Description | Typical Threshold | | ----------------- | --------------------------- | ---------------------------- | | **PSI** | Population Stability Index | Warning: 0.1, Critical: 0.2 | | **KL Divergence** | Kullback-Leibler divergence | Warning: 0.1, Critical: 0.2 | | **JS Distance** | Jensen-Shannon distance | Warning: 0.1, Critical: 0.15 | | **KS Statistic** | Kolmogorov-Smirnov test | Warning: 0.05, Critical: 0.1 | ## Configuring Alerts ### Alert Channels ```python theme={null} monitor = client.guardian.create_monitor( model_id="my-model", name="Production Monitor", metrics=["prediction_drift", "error_rate"], alerts=[ { "metric": "prediction_drift", "threshold": 0.2, "severity": "critical", "window": "1h" # Evaluate over 1 hour } ], notifications={ "email": ["ml-team@company.com", "oncall@company.com"], "slack_webhook": "https://hooks.slack.com/services/...", "pagerduty_key": "your-pagerduty-key" } ) ``` ### Alert Severity Levels | Severity | Use Case | Response | | ---------- | ------------------- | ---------------------- | | `info` | FYI notifications | Review when convenient | | `warning` | Potential issues | Investigate within 24h | | `critical` | Immediate attention | Page on-call engineer | ## Viewing Metrics ### Dashboard Access the monitoring dashboard at: ``` https://dashboard.rotavision.com/monitors/{monitor_id} ``` ### API ```python theme={null} # Get current metrics metrics = client.guardian.get_metrics( monitor_id="mon_abc123", start_time="2026-02-01T00:00:00Z", end_time="2026-02-01T12:00:00Z", granularity="hour" ) for point in metrics.data: print(f"{point.timestamp}: PSI={point.prediction_drift:.3f}, P99={point.latency_p99}ms") ``` ## Handling Alerts ### Acknowledging ```python theme={null} # Acknowledge alert (stops repeat notifications) client.guardian.acknowledge_alert( alert_id="alert_xyz789", acknowledged_by="jane@company.com", note="Investigating - may be related to data pipeline issue" ) ``` ### Resolving ```python theme={null} # Resolve alert with root cause client.guardian.resolve_alert( alert_id="alert_xyz789", resolved_by="jane@company.com", resolution="Rolled back model to v2 due to training data issue", root_cause="data_quality" # For analytics ) ``` ## Best Practices Begin with essential metrics: * `prediction_drift` - Catches distribution shifts * `latency_p99` - Performance degradation * `error_rate` - System health Add more granular metrics as you learn your model's failure modes. * Start with conservative thresholds (more alerts) * Tune based on false positive rate * Different models may need different thresholds Never block your serving path with synchronous logging. Use the AsyncLogger or batch endpoints. If you can obtain ground truth labels later: ```python theme={null} # Log prediction logger.log(inference_id="inf_123", prediction=pred) # Later, when ground truth is available client.guardian.update_inference( inference_id="inf_123", actual=actual_outcome ) ``` ## Next Steps Add fairness monitoring to your pipeline Full API documentation # Multi-Agent Workflows Guide Source: https://docs.rotavision.com/guides/multi-agent-workflows Build complex AI workflows with Orchestrate ## Overview Orchestrate enables building sophisticated AI workflows that coordinate multiple specialized agents. This guide covers workflow design patterns and best practices. ## Core Concepts ### Agents Agents are specialized workers that perform specific tasks: | Type | Use Case | | ---------------- | -------------------------------------- | | **LLM Agent** | Natural language reasoning, generation | | **Code Agent** | Execute Python/JavaScript | | **Search Agent** | Web, document, or database search | | **Tool Agent** | Call external APIs | | **Human Agent** | Human-in-the-loop approval | ### Workflows Workflows define how agents collaborate: ```python theme={null} workflow = { "agents": [...], # Agent definitions "steps": [...], # Execution sequence "config": {...} # Settings } ``` ## Building Your First Workflow ### Research Assistant Example ```python theme={null} from rotavision import Rotavision client = Rotavision() workflow = client.orchestrate.create_workflow( name="Research Assistant", agents=[ { "id": "planner", "type": "llm", "model": "gpt-5-mini", "system_prompt": """You are a research planner. Given a topic, output a JSON list of 3-5 specific search queries to research it thoroughly.""" }, { "id": "searcher", "type": "search", "sources": ["web", "news", "academic"] }, { "id": "synthesizer", "type": "llm", "model": "claude-4.5-sonnet", "system_prompt": """You are a research synthesizer. Given search results, create a comprehensive summary with citations.""" } ], steps=[ { "id": "plan", "agent": "planner", "action": "generate", "input": "Research topic: {{topic}}" }, { "id": "search", "agent": "searcher", "action": "search", "input": "{{plan.queries}}" }, { "id": "synthesize", "agent": "synthesizer", "action": "generate", "input": "Topic: {{topic}}\n\nSearch Results:\n{{search.results}}" } ] ) # Run the workflow execution = client.orchestrate.run_workflow( workflow_id=workflow.id, inputs={"topic": "Electric vehicle adoption in India 2026"} ) # Wait for completion result = client.orchestrate.wait_for_execution(execution.id) print(result.outputs["synthesize"]) ``` ## Workflow Patterns ### Sequential Processing Steps execute one after another: ```python theme={null} steps = [ {"agent": "classifier", "action": "classify", "input": "{{text}}"}, {"agent": "processor", "action": "process", "input": "{{classifier.output}}"}, {"agent": "formatter", "action": "format", "input": "{{processor.output}}"} ] ``` ### Parallel Processing Steps execute simultaneously: ```python theme={null} steps = [ { "parallel": [ {"agent": "web_search", "action": "search", "input": "{{query}}"}, {"agent": "news_search", "action": "search", "input": "{{query}}"}, {"agent": "academic_search", "action": "search", "input": "{{query}}"} ] }, { "agent": "aggregator", "action": "aggregate", "input": "{{web_search.results}}\n{{news_search.results}}\n{{academic_search.results}}" } ] ``` ### Conditional Execution Branch based on results: ```python theme={null} steps = [ {"agent": "classifier", "action": "classify", "input": "{{ticket}}"}, { "condition": "{{classifier.priority}} == 'high'", "then": [ {"agent": "escalation", "action": "notify", "input": "High priority: {{ticket}}"} ], "else": [ {"agent": "auto_responder", "action": "respond", "input": "{{ticket}}"} ] } ] ``` ### Loop/Iteration Process items iteratively: ```python theme={null} steps = [ {"agent": "splitter", "action": "split", "input": "{{document}}"}, { "loop": { "items": "{{splitter.chunks}}", "as": "chunk", "steps": [ {"agent": "processor", "action": "process", "input": "{{chunk}}"} ] } }, {"agent": "combiner", "action": "combine", "input": "{{loop.results}}"} ] ``` ## Human-in-the-Loop Add approval gates for sensitive operations: ```python theme={null} workflow = client.orchestrate.create_workflow( name="Content Moderation", agents=[ { "id": "moderator", "type": "llm", "model": "gpt-5-mini", "system_prompt": "Analyze content for policy violations..." }, { "id": "human_review", "type": "human", "assignees": ["moderation-team@company.com"], "timeout_hours": 24 }, { "id": "action_taker", "type": "tool", "tools": ["content_api"] } ], steps=[ {"agent": "moderator", "action": "analyze", "input": "{{content}}"}, { "condition": "{{moderator.requires_human_review}}", "then": [ { "agent": "human_review", "action": "approve", "input": "Review needed for: {{content}}\nAI Assessment: {{moderator.assessment}}" } ] }, { "condition": "{{human_review.approved}} or not {{moderator.requires_human_review}}", "then": [ {"agent": "action_taker", "action": "publish", "input": "{{content}}"} ], "else": [ {"agent": "action_taker", "action": "reject", "input": "{{content}}"} ] } ] ) ``` ## Error Handling ### Retry Configuration ```python theme={null} workflow = client.orchestrate.create_workflow( name="Robust Workflow", config={ "max_retries": 3, "retry_delay_ms": 1000, "on_error": "retry" # or "stop", "continue" }, steps=[...] ) ``` ### Per-Step Error Handling ```python theme={null} steps = [ { "agent": "api_caller", "action": "call", "input": "{{data}}", "on_error": { "retry": 3, "fallback": { "agent": "fallback_handler", "action": "handle", "input": "Error: {{error}}" } } } ] ``` ## Cost Controls ### Budget Limits ```python theme={null} workflow = client.orchestrate.create_workflow( name="Controlled Workflow", config={ "budget_usd": 1.00, # Max $1 per execution "on_budget_exceeded": "stop" }, steps=[...] ) ``` ### Token Limits ```python theme={null} agents = [ { "id": "writer", "type": "llm", "model": "claude-4.5-sonnet", "max_tokens": 2000 # Limit per call } ] ``` ## Monitoring Executions ```python theme={null} # Get execution status execution = client.orchestrate.get_execution("exec_xyz789") print(f"Status: {execution.status}") print(f"Current step: {execution.current_step}") print(f"Progress: {execution.progress.completed}/{execution.progress.total}") # View step-by-step results for step in execution.steps: print(f"\n{step.id}: {step.status}") if step.output: print(f" Output: {step.output[:200]}...") if step.error: print(f" Error: {step.error}") ``` ## Best Practices Each agent should do one thing well. Instead of one mega-agent, use multiple specialized agents. * Fast/cheap models (GPT-5-mini) for classification, routing * Powerful models (Claude 4.5 Sonnet) for synthesis, writing * Code agents for deterministic operations For anything that could cause harm or significant business impact, add human approval. Always set budget limits to prevent runaway costs from infinite loops or unexpected usage. ## Next Steps Full API documentation Route LLM requests efficiently # AWS Integration Source: https://docs.rotavision.com/integrations/aws Integrate Rotavision with AWS services ## Overview Rotavision integrates with AWS for data access, model monitoring, and LLM routing. ## S3 Integration ### Direct Access Rotavision can read data directly from S3: ```python theme={null} from rotavision import Rotavision client = Rotavision() # Analyze data from S3 result = client.vishwas.analyze( model_id="my-model", dataset={ "data_url": "s3://my-bucket/predictions.parquet", "aws_credentials": { "access_key_id": "AKIA...", "secret_access_key": "...", "region": "ap-south-1" } } ) ``` ### IAM Role (Recommended) For production, use IAM roles: 1. Create an IAM role with S3 read access 2. Add Rotavision's AWS account as trusted entity 3. Configure in Rotavision dashboard ```python theme={null} # No credentials needed - uses assumed role result = client.vishwas.analyze( model_id="my-model", dataset={ "data_url": "s3://my-bucket/predictions.parquet" } ) ``` ## SageMaker Integration ### Monitor SageMaker Endpoints ```python theme={null} from rotavision.integrations.aws import SageMakerMonitor # Create monitor for SageMaker endpoint monitor = SageMakerMonitor( endpoint_name="my-sagemaker-endpoint", rotavision_api_key="rv_live_...", aws_region="ap-south-1" ) # Automatically logs inferences to Guardian monitor.start() ``` ### SageMaker Pipeline Integration Add Rotavision to your SageMaker Pipeline: ```python theme={null} from sagemaker.workflow.steps import ProcessingStep from rotavision.integrations.aws import RotavisionProcessor # Fairness analysis step fairness_step = ProcessingStep( name="FairnessAnalysis", processor=RotavisionProcessor( api_key="rv_live_...", role=role, instance_type="ml.m5.xlarge" ), inputs=[ ProcessingInput(source=predictions_uri, destination="/opt/ml/processing/input") ], code="analyze_fairness.py" ) ``` ## Bedrock Integration Route Sankalp requests to AWS Bedrock: ```python theme={null} # Sankalp automatically routes to Bedrock for supported models response = client.sankalp.proxy( model="claude-3-sonnet", # Routes to Bedrock messages=[{"role": "user", "content": "Hello"}], routing={ "provider_preference": ["bedrock", "anthropic"], "data_residency": "india" } ) ``` ### Configure Bedrock Access In Rotavision dashboard or via API: ```python theme={null} client.integrations.configure( provider="aws_bedrock", config={ "access_key_id": "AKIA...", "secret_access_key": "...", "region": "us-east-1" # Bedrock region } ) ``` ## CloudWatch Integration Export Rotavision metrics to CloudWatch: ```python theme={null} from rotavision.integrations.aws import CloudWatchExporter exporter = CloudWatchExporter( namespace="Rotavision/ML", region="ap-south-1" ) # Metrics automatically pushed to CloudWatch monitor = client.guardian.create_monitor( model_id="my-model", metrics=["prediction_drift", "latency_p99"], exporters=[exporter] ) ``` ## Terraform Module Deploy Rotavision integration with Terraform: ```hcl theme={null} module "rotavision" { source = "rotavision/integration/aws" version = "1.0.0" rotavision_api_key = var.rotavision_api_key # S3 buckets to grant access s3_buckets = [ "my-ml-data-bucket", "my-predictions-bucket" ] # SageMaker endpoints to monitor sagemaker_endpoints = [ "prod-recommendation-endpoint", "prod-fraud-detection-endpoint" ] } ``` ## IAM Policies ### Minimal S3 Policy ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::my-bucket", "arn:aws:s3:::my-bucket/*" ] } ] } ``` ### SageMaker Monitoring Policy ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sagemaker:InvokeEndpoint", "sagemaker:DescribeEndpoint", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "*" } ] } ``` # Azure Integration Source: https://docs.rotavision.com/integrations/azure Integrate Rotavision with Microsoft Azure ## Overview Rotavision integrates with Azure for data access, ML monitoring, and Azure OpenAI routing. ## Blob Storage ```python theme={null} from rotavision import Rotavision client = Rotavision() # Analyze data from Azure Blob result = client.vishwas.analyze( model_id="my-model", dataset={ "data_url": "https://myaccount.blob.core.windows.net/container/data.parquet", "azure_credentials": { "connection_string": "DefaultEndpointsProtocol=https;..." } } ) ``` ## Azure ML Integration Monitor models deployed on Azure ML: ```python theme={null} from rotavision.integrations.azure import AzureMLMonitor monitor = AzureMLMonitor( workspace_name="my-workspace", endpoint_name="my-endpoint", rotavision_api_key="rv_live_..." ) monitor.start() ``` ## Azure OpenAI Route Sankalp requests via Azure OpenAI: ```python theme={null} response = client.sankalp.proxy( model="gpt-4", messages=[{"role": "user", "content": "Hello"}], routing={ "provider": "azure_openai" } ) ``` Configure Azure OpenAI in dashboard: ```python theme={null} client.integrations.configure( provider="azure_openai", config={ "endpoint": "https://my-resource.openai.azure.com", "api_key": "...", "deployment_id": "gpt-4-deployment" } ) ``` # Google Cloud Integration Source: https://docs.rotavision.com/integrations/gcp Integrate Rotavision with Google Cloud Platform ## Overview Rotavision integrates with GCP for data access, Vertex AI monitoring, and Gemini routing. ## Cloud Storage ```python theme={null} from rotavision import Rotavision client = Rotavision() # Analyze data from GCS result = client.vishwas.analyze( model_id="my-model", dataset={ "data_url": "gs://my-bucket/predictions.parquet", "gcp_credentials": { "service_account_key": {...} # JSON key } } ) ``` ## Vertex AI Integration Monitor Vertex AI endpoints: ```python theme={null} from rotavision.integrations.gcp import VertexAIMonitor monitor = VertexAIMonitor( project_id="my-project", endpoint_id="123456789", rotavision_api_key="rv_live_..." ) monitor.start() ``` ## Gemini via Sankalp Route to Gemini through Sankalp: ```python theme={null} response = client.sankalp.proxy( model="gemini-3-pro", messages=[{"role": "user", "content": "Hello"}] ) ``` # LangChain Integration Source: https://docs.rotavision.com/integrations/langchain Add Rotavision trust & monitoring to LangChain apps ## Overview Integrate Rotavision with LangChain to add fairness monitoring, explainability, and reliability tracking to your LLM applications. ## Installation ```bash theme={null} pip install rotavision langchain ``` ## Sankalp as LangChain LLM Use Sankalp as your LangChain LLM for unified routing and monitoring: ```python theme={null} from langchain.llms import BaseLLM from rotavision.integrations.langchain import SankalpLLM # Create Sankalp-backed LLM llm = SankalpLLM( api_key="rv_live_...", model="gpt-5-mini", routing={ "optimize": "cost", "data_residency": "india" } ) # Use with LangChain from langchain.chains import LLMChain from langchain.prompts import PromptTemplate prompt = PromptTemplate( input_variables=["topic"], template="Write a brief summary about {topic}" ) chain = LLMChain(llm=llm, prompt=prompt) result = chain.run("AI adoption in India") ``` ## Callback Handler for Monitoring Add Guardian monitoring to any LangChain app: ```python theme={null} from langchain.callbacks import BaseCallbackHandler from rotavision.integrations.langchain import GuardianCallbackHandler # Create callback handler guardian_callback = GuardianCallbackHandler( api_key="rv_live_...", monitor_id="mon_abc123" ) # Use with any LangChain component from langchain.chat_models import ChatOpenAI llm = ChatOpenAI( callbacks=[guardian_callback] ) # All LLM calls are automatically logged to Guardian response = llm.predict("Hello, world!") ``` ## RAG with Fairness Monitoring Monitor your RAG pipeline for fairness: ```python theme={null} from langchain.chains import RetrievalQA from langchain.vectorstores import Chroma from rotavision.integrations.langchain import FairnessMonitor # Create fairness monitor fairness_monitor = FairnessMonitor( api_key="rv_live_...", protected_attributes=["language", "region"] ) # Wrap your retriever monitored_retriever = fairness_monitor.wrap_retriever( retriever=vectorstore.as_retriever() ) # Use in RAG chain qa_chain = RetrievalQA.from_chain_type( llm=llm, retriever=monitored_retriever ) # Queries are analyzed for fairness across protected groups result = qa_chain.run("What are the loan eligibility criteria?") ``` ## Agent Monitoring Monitor LangChain agents: ```python theme={null} from langchain.agents import initialize_agent, Tool from rotavision.integrations.langchain import AgentMonitor agent_monitor = AgentMonitor( api_key="rv_live_...", log_thoughts=True, log_actions=True ) agent = initialize_agent( tools=tools, llm=llm, agent="zero-shot-react-description", callbacks=[agent_monitor] ) # Agent reasoning and actions are logged result = agent.run("Research the latest EV sales in India") ``` ## LCEL Integration Works with LangChain Expression Language: ```python theme={null} from langchain.schema.runnable import RunnablePassthrough from rotavision.integrations.langchain import rotavision_middleware # Add Rotavision middleware to any chain chain = ( {"context": retriever, "question": RunnablePassthrough()} | rotavision_middleware(api_key="rv_live_...", monitor_id="mon_123") | prompt | llm | output_parser ) ``` # LlamaIndex Integration Source: https://docs.rotavision.com/integrations/llamaindex Add Rotavision trust & monitoring to LlamaIndex apps ## Overview Integrate Rotavision with LlamaIndex for monitoring and fairness analysis of your RAG applications. ## Installation ```bash theme={null} pip install rotavision llama-index ``` ## Sankalp as LlamaIndex LLM ```python theme={null} from llama_index.llms import CustomLLM from rotavision.integrations.llamaindex import SankalpLLM # Use Sankalp as your LLM llm = SankalpLLM( api_key="rv_live_...", model="claude-4.5-sonnet", routing={"data_residency": "india"} ) # Create index with Sankalp from llama_index import VectorStoreIndex, SimpleDirectoryReader documents = SimpleDirectoryReader("data").load_data() index = VectorStoreIndex.from_documents(documents, llm=llm) ``` ## Query Engine Monitoring Monitor your query engine: ```python theme={null} from rotavision.integrations.llamaindex import GuardianCallback callback = GuardianCallback( api_key="rv_live_...", monitor_id="mon_abc123" ) query_engine = index.as_query_engine( callbacks=[callback] ) # Queries are logged to Guardian response = query_engine.query("What are the key findings?") ``` ## Retrieval Fairness Analyze retrieval fairness: ```python theme={null} from rotavision.integrations.llamaindex import FairnessAnalyzer analyzer = FairnessAnalyzer(api_key="rv_live_...") # Analyze retrieval results analysis = analyzer.analyze_retrieval( query_engine=query_engine, test_queries=[ {"query": "Loan options for urban customers", "metadata": {"region": "urban"}}, {"query": "Loan options for rural customers", "metadata": {"region": "rural"}}, ], protected_attribute="region" ) print(f"Retrieval fairness score: {analysis.score}") ``` # Integrations Overview Source: https://docs.rotavision.com/integrations/overview Connect Rotavision with your infrastructure ## Overview Rotavision integrates with popular cloud providers, ML platforms, and enterprise systems. S3, SageMaker, Bedrock Blob Storage, Azure ML, OpenAI GCS, Vertex AI, Gemini LangChain integration LlamaIndex integration ## Integration Types ### Data Sources Connect your data for analysis: * Cloud storage (S3, GCS, Azure Blob) * Data warehouses (Snowflake, BigQuery, Redshift) * Feature stores (Feast, Tecton) ### ML Platforms Monitor models across platforms: * AWS SageMaker * Azure ML * Google Vertex AI * MLflow * Kubeflow ### LLM Frameworks Add trust & monitoring to LLM apps: * LangChain * LlamaIndex * Haystack ### Notifications Alert routing: * Slack * PagerDuty * Email * Custom webhooks ## Quick Setup Most integrations follow this pattern: ```python theme={null} from rotavision import Rotavision from rotavision.integrations import AWSIntegration client = Rotavision() # Configure integration aws = AWSIntegration( access_key_id="...", secret_access_key="...", region="ap-south-1" ) # Use with Rotavision result = client.vishwas.analyze( model_id="my-model", dataset={ "data_url": "s3://my-bucket/data.parquet" # Direct S3 access } ) ``` # Introduction Source: https://docs.rotavision.com/introduction Build trusted AI systems with Rotavision's enterprise-grade infrastructure Rotavision Platform Rotavision Platform ## Welcome to Rotavision Rotavision provides the infrastructure layer for building **trusted, fair, and reliable AI systems** in India and emerging markets. Our platform helps enterprises deploy AI with confidence through comprehensive trust measurement, monitoring, and governance tools. Click "Get API Key" to receive a test key instantly. No signup required — just enter your email and start building. Get up and running with Rotavision in under 5 minutes Explore the complete API documentation Official SDKs for Python, Node.js, and Java Connect with AWS, Azure, LangChain, and more ## Platform Products Rotavision offers six core products that work together to provide end-to-end AI trust infrastructure: Measure and monitor fairness across protected attributes. Generate human-readable explanations for any model prediction. Build audit-ready compliance reports. **Key Features:** * Bias detection across 15+ fairness metrics * SHAP/LIME explanations with Indian context * Automated audit report generation Real-time monitoring for model drift, data quality, and performance degradation. Get alerts before issues impact users. **Key Features:** * Drift detection (concept, data, prediction) * Anomaly detection on inputs/outputs * SLA monitoring and alerting Extract structured data from Indian documents (Aadhaar, PAN, GST invoices). Deploy browser agents for web automation. **Key Features:** * 50+ Indian document templates * Multi-language OCR (12 Indian languages) * Browser automation agents Unified API gateway for Indian and international LLMs. Route requests based on compliance, cost, and capability requirements. **Key Features:** * Single API for 20+ LLM providers * Data residency controls * Cost optimization & fallbacks Build and deploy multi-agent AI workflows. Coordinate specialized agents for complex enterprise tasks. **Key Features:** * Visual workflow builder * Agent marketplace * Human-in-the-loop controls AI-powered route optimization and demand prediction for logistics and mobility companies. **Key Features:** * Real-time route optimization * Demand forecasting * Fleet analytics ## Why Rotavision? Built for Indian regulations, languages, and infrastructure realities SOC 2 Type II compliant with on-premise deployment options Peer-reviewed AI safety research from Rota Labs ## Getting Help Connect with other developers building trusted AI Get help from our engineering team # Quickstart Source: https://docs.rotavision.com/quickstart Get started with Rotavision in under 5 minutes ## Prerequisites Before you begin, you'll need: * A free API key ([get one instantly](https://api.rotavision.com/docs) - click "Get API Key") * Python 3.8+, Node.js 18+, or Java 17+ Test keys (`rv_test_*`) are free and include 100 requests/day. No credit card required. ## Installation Install the Rotavision SDK for your preferred language: ```bash Python theme={null} pip install rotavision ``` ```bash Node.js theme={null} npm install @rotavision/sdk ``` ```xml Java (Maven) theme={null} com.rotavision rotavision-java 0.1.0 ``` ```groovy Java (Gradle) theme={null} implementation 'com.rotavision:rotavision-java:0.1.0' ``` ## Initialize the Client ```python Python theme={null} from rotavision import Rotavision client = Rotavision(api_key="rv_live_...") # Or use environment variable ROTAVISION_API_KEY client = Rotavision() ``` ```typescript Node.js theme={null} import { Rotavision } from '@rotavision/sdk'; const client = new Rotavision({ apiKey: 'rv_live_...' }); // Or use environment variable ROTAVISION_API_KEY const client = new Rotavision(); ``` ```java Java theme={null} import com.rotavision.Rotavision; Rotavision client = new Rotavision("rv_live_..."); // Or use environment variable ROTAVISION_API_KEY Rotavision client = new Rotavision(); ``` ## Your First API Call Let's analyze a model prediction for fairness using **Vishwas**: ```python Python theme={null} # Analyze fairness of a loan approval model result = client.vishwas.analyze( model_id="loan-approval-v2", dataset={ "features": ["age", "income", "credit_score", "gender", "location"], "predictions": predictions, "actuals": actuals, "protected_attributes": ["gender", "location"] }, metrics=["demographic_parity", "equalized_odds", "calibration"] ) print(f"Fairness Score: {result.overall_score}") print(f"Bias Detected: {result.bias_detected}") for metric in result.metrics: print(f" {metric.name}: {metric.value:.3f} ({metric.status})") ``` ```typescript Node.js theme={null} // Analyze fairness of a loan approval model const result = await client.vishwas.analyze({ modelId: 'loan-approval-v2', dataset: { features: ['age', 'income', 'credit_score', 'gender', 'location'], predictions: predictions, actuals: actuals, protectedAttributes: ['gender', 'location'] }, metrics: ['demographic_parity', 'equalized_odds', 'calibration'] }); console.log(`Fairness Score: ${result.overallScore}`); console.log(`Bias Detected: ${result.biasDetected}`); result.metrics.forEach(metric => { console.log(` ${metric.name}: ${metric.value.toFixed(3)} (${metric.status})`); }); ``` ```java Java theme={null} // Analyze fairness of a loan approval model Vishwas.AnalyzeResult result = client.vishwas().analyze( new Vishwas.AnalyzeRequest() .modelId("loan-approval-v2") .dataset(dataset) .protectedAttributes(Arrays.asList("gender", "location")) .metrics(Arrays.asList("demographic_parity", "equalized_odds")) ); System.out.println("Fairness Score: " + result.getOverallScore()); System.out.println("Bias Detected: " + result.isBiasDetected()); ``` ## Example Response ```json theme={null} { "id": "analysis_abc123", "model_id": "loan-approval-v2", "overall_score": 0.82, "bias_detected": true, "metrics": [ { "name": "demographic_parity", "value": 0.78, "threshold": 0.80, "status": "warning", "affected_groups": ["location:rural"] }, { "name": "equalized_odds", "value": 0.91, "threshold": 0.80, "status": "pass" }, { "name": "calibration", "value": 0.85, "threshold": 0.80, "status": "pass" } ], "recommendations": [ { "severity": "medium", "message": "Rural applicants have 22% lower approval rate despite similar creditworthiness", "action": "Review feature weights for location-correlated variables" } ], "created_at": "2026-02-01T10:30:00Z" } ``` ## Next Steps Learn about API keys, scopes, and security best practices Explore all fairness metrics and explanation methods Configure Guardian to monitor your models in production Use Dastavez to process Indian documents # Java SDK Source: https://docs.rotavision.com/sdks/java Official Java SDK for Rotavision ## Installation ### Maven ```xml theme={null} com.rotavision rotavision-java 0.1.0 ``` ### Gradle ```groovy theme={null} implementation 'com.rotavision:rotavision-java:0.1.0' ``` Requirements: Java 17+ ## Quick Start ```java theme={null} import com.rotavision.Rotavision; // Initialize client Rotavision client = new Rotavision("rv_live_..."); // Or use environment variable ROTAVISION_API_KEY Rotavision client = new Rotavision(); // Use any product Vishwas.AnalyzeResult result = client.vishwas().analyze( new Vishwas.AnalyzeRequest() .modelId("my-model") .dataset(dataset) ); ``` ## Configuration ```java theme={null} import com.rotavision.Rotavision; import com.rotavision.RotavisionConfig; RotavisionConfig config = RotavisionConfig.builder() .apiKey("rv_live_...") .baseUrl("https://api.rotavision.com") .timeout(Duration.ofSeconds(30)) .maxRetries(3) .build(); Rotavision client = new Rotavision(config); ``` ## Products ### Vishwas - Fairness & Explainability ```java theme={null} import com.rotavision.Vishwas; // Analyze fairness Vishwas.AnalyzeResult analysis = client.vishwas().analyze( new Vishwas.AnalyzeRequest() .modelId("loan-model") .dataset(new Dataset() .features(Arrays.asList("age", "income", "gender")) .predictions(predictions) .actuals(actuals) .protectedAttributes(Arrays.asList("gender"))) .metrics(Arrays.asList("demographic_parity", "equalized_odds")) ); System.out.println("Score: " + analysis.getOverallScore()); System.out.println("Bias: " + analysis.isBiasDetected()); // Explain prediction Vishwas.ExplainResult explanation = client.vishwas().explain( new Vishwas.ExplainRequest() .modelId("loan-model") .inputData(Map.of("age", 30, "income", 50000)) .prediction(0.75) .method("shap") ); System.out.println(explanation.getSummary()); ``` ### Guardian - Monitoring ```java theme={null} import com.rotavision.Guardian; // Create monitor Guardian.Monitor monitor = client.guardian().createMonitor( new Guardian.CreateMonitorRequest() .modelId("recommendation-model") .name("Prod Monitor") .metrics(Arrays.asList("prediction_drift", "latency_p99")) .alerts(Arrays.asList( new Guardian.AlertConfig() .metric("prediction_drift") .threshold(0.2) .severity("critical") )) ); // Log inference client.guardian().logInference( new Guardian.LogInferenceRequest() .monitorId(monitor.getId()) .inputData(features) .prediction(prediction) .latencyMs(45) ); ``` ### Dastavez - Document AI ```java theme={null} import com.rotavision.Dastavez; // Extract from document URL Dastavez.ExtractResult result = client.dastavez().extract( new Dastavez.ExtractRequest() .documentType("aadhaar") .fileUrl("https://storage.example.com/doc.pdf") ); System.out.println("Name: " + result.getFields().get("name")); System.out.println("Confidence: " + result.getConfidence()); // From file Path filePath = Paths.get("document.pdf"); Dastavez.ExtractResult result = client.dastavez().extract( new Dastavez.ExtractRequest() .documentType("pan") .file(filePath) ); ``` ### Sankalp - LLM Gateway ```java theme={null} import com.rotavision.Sankalp; // Proxy to LLM Sankalp.ProxyResult response = client.sankalp().proxy( new Sankalp.ProxyRequest() .model("gpt-5-mini") .messages(Arrays.asList( new Message().role("user").content("Hello!") )) ); System.out.println(response.getChoices().get(0).getMessage().getContent()); ``` ### Orchestrate - Workflows ```java theme={null} import com.rotavision.Orchestrate; // Run workflow Orchestrate.Execution execution = client.orchestrate().runWorkflow( "wf_abc123", Map.of("query", "Research AI in India") ); // Wait for completion Orchestrate.Execution result = client.orchestrate() .waitForExecution(execution.getId()); System.out.println(result.getOutputs()); ``` ### Gati - Fleet Intelligence ```java theme={null} import com.rotavision.Gati; // Optimize routes Gati.OptimizeResult result = client.gati().optimizeRoutes( new Gati.OptimizeRequest() .vehicles(Arrays.asList( new Vehicle().id("v1").capacity(100).startLocation(location) )) .orders(Arrays.asList( new Order().id("o1").location(loc).demand(10) )) ); for (Gati.Route route : result.getRoutes()) { System.out.printf("Vehicle %s: %d stops%n", route.getVehicleId(), route.getStops().size()); } ``` ## Async Support ```java theme={null} import java.util.concurrent.CompletableFuture; // Async API calls CompletableFuture future = client.vishwas().analyzeAsync(request); future.thenAccept(result -> { System.out.println("Score: " + result.getOverallScore()); }); // Or with reactive streams (if using Reactor) Mono mono = client.vishwas().analyzeReactive(request); ``` ## Error Handling ```java theme={null} import com.rotavision.exceptions.*; try { Vishwas.AnalyzeResult result = client.vishwas().analyze(request); } catch (AuthenticationException e) { System.out.println("Invalid API key"); } catch (ValidationException e) { System.out.println("Invalid request: " + e.getParam()); } catch (RateLimitException e) { System.out.println("Rate limited, retry after " + e.getRetryAfter() + "s"); } catch (RotavisionException e) { System.out.println("API error: " + e.getMessage()); } ``` ## Logging The SDK uses SLF4J for logging. Add your preferred implementation: ```xml theme={null} ch.qos.logback logback-classic 1.4.11 ``` ```xml theme={null} ``` # Node.js SDK Source: https://docs.rotavision.com/sdks/nodejs Official Node.js SDK for Rotavision ## Installation ```bash theme={null} npm install @rotavision/sdk ``` Requirements: Node.js 18+ ## Quick Start ```typescript theme={null} import { Rotavision } from '@rotavision/sdk'; // Initialize client const client = new Rotavision({ apiKey: 'rv_live_...' }); // Or use environment variable ROTAVISION_API_KEY const client = new Rotavision(); // Use any product const result = await client.vishwas.analyze({ modelId: 'my-model', dataset: data }); ``` ## Configuration ```typescript theme={null} import { Rotavision } from '@rotavision/sdk'; const client = new Rotavision({ apiKey: 'rv_live_...', baseUrl: 'https://api.rotavision.com', // Custom endpoint timeout: 30000, // Request timeout (ms) maxRetries: 3, // Retry attempts }); ``` ## Products ### Vishwas - Fairness & Explainability ```typescript theme={null} // Analyze fairness const analysis = await client.vishwas.analyze({ modelId: 'loan-model', dataset: { features: ['age', 'income', 'gender'], predictions: predictions, actuals: actuals, protectedAttributes: ['gender'] }, metrics: ['demographic_parity', 'equalized_odds'] }); console.log(`Score: ${analysis.overallScore}`); console.log(`Bias: ${analysis.biasDetected}`); // Explain prediction const explanation = await client.vishwas.explain({ modelId: 'loan-model', inputData: { age: 30, income: 50000 }, prediction: 0.75, method: 'shap' }); console.log(explanation.summary); ``` ### Guardian - Monitoring ```typescript theme={null} // Create monitor const monitor = await client.guardian.createMonitor({ modelId: 'recommendation-model', name: 'Prod Monitor', metrics: ['prediction_drift', 'latency_p99'], alerts: [ { metric: 'prediction_drift', threshold: 0.2, severity: 'critical' } ] }); // Log inference await client.guardian.logInference({ monitorId: monitor.id, inputData: features, prediction: prediction, latencyMs: 45 }); // Batch logging await client.guardian.logInferences({ monitorId: monitor.id, inferences: [ { inputData: f1, prediction: p1, latencyMs: 40 }, { inputData: f2, prediction: p2, latencyMs: 42 }, ] }); ``` ### Dastavez - Document AI ```typescript theme={null} // Extract from document const result = await client.dastavez.extract({ documentType: 'aadhaar', fileUrl: 'https://storage.example.com/doc.pdf' }); console.log(`Name: ${result.fields.name}`); console.log(`Confidence: ${result.confidence}`); // From file buffer import fs from 'fs'; const buffer = fs.readFileSync('document.pdf'); const result = await client.dastavez.extract({ documentType: 'pan', file: buffer }); ``` ### Sankalp - LLM Gateway ```typescript theme={null} // Proxy to LLM const response = await client.sankalp.proxy({ model: 'gpt-5-mini', messages: [ { role: 'user', content: 'Hello!' } ] }); console.log(response.choices[0].message.content); // Streaming const stream = await client.sankalp.proxyStream({ model: 'claude-4.5-sonnet', messages: [{ role: 'user', content: 'Write a story' }] }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0].delta.content || ''); } ``` ### Orchestrate - Workflows ```typescript theme={null} // Run workflow const execution = await client.orchestrate.runWorkflow({ workflowId: 'wf_abc123', inputs: { query: 'Research AI in India' } }); // Poll for completion const result = await client.orchestrate.waitForExecution(execution.id); console.log(result.outputs); ``` ### Gati - Fleet Intelligence ```typescript theme={null} // Optimize routes const result = await client.gati.optimizeRoutes({ vehicles: [{ id: 'v1', capacity: 100, startLocation: {...} }], orders: [{ id: 'o1', location: {...}, demand: 10 }] }); result.routes.forEach(route => { console.log(`Vehicle ${route.vehicleId}: ${route.stops.length} stops`); }); ``` ## TypeScript Support The SDK is written in TypeScript and provides full type definitions: ```typescript theme={null} import { Rotavision, VishwasAnalysis, GuardianMonitor, DastavezExtraction } from '@rotavision/sdk'; const client = new Rotavision(); // Full type inference const analysis: VishwasAnalysis = await client.vishwas.analyze({ modelId: 'my-model', dataset: { ... } }); ``` ## Error Handling ```typescript theme={null} import { RotavisionError, AuthenticationError, ValidationError, RateLimitError, NotFoundError } from '@rotavision/sdk/errors'; try { const result = await client.vishwas.analyze({ ... }); } catch (e) { if (e instanceof AuthenticationError) { console.log('Invalid API key'); } else if (e instanceof ValidationError) { console.log(`Invalid request: ${e.param}`); } else if (e instanceof RateLimitError) { console.log(`Rate limited, retry after ${e.retryAfter}s`); } else if (e instanceof RotavisionError) { console.log(`API error: ${e.message}`); } } ``` ## Logging ```typescript theme={null} import { Rotavision } from '@rotavision/sdk'; const client = new Rotavision({ debug: true // Enable debug logging }); // Or use custom logger const client = new Rotavision({ logger: { debug: (msg) => console.debug(msg), info: (msg) => console.info(msg), warn: (msg) => console.warn(msg), error: (msg) => console.error(msg), } }); ``` # SDK Overview Source: https://docs.rotavision.com/sdks/overview Official Rotavision SDKs ## Official SDKs Rotavision provides official SDKs for popular programming languages. All SDKs provide: * Type-safe API interfaces * Automatic retries with exponential backoff * Request/response logging * Error handling with typed exceptions Python 3.8+ Node.js 18+ Java 17+ ## Installation ```bash Python theme={null} pip install rotavision ``` ```bash Node.js theme={null} npm install @rotavision/sdk ``` ```xml Java (Maven) theme={null} com.rotavision rotavision-java 0.1.0 ``` ## Quick Comparison | Feature | Python | Node.js | Java | | ------------- | ------------ | --------------- | ------------------- | | Async Support | ✅ asyncio | ✅ Promises | ✅ CompletableFuture | | Streaming | ✅ Generators | ✅ AsyncIterator | ✅ Flux (Reactor) | | Type Safety | ✅ Type hints | ✅ TypeScript | ✅ Native | | Retries | ✅ Built-in | ✅ Built-in | ✅ Built-in | ## Source Code All SDKs are open source under the Apache 2.0 license: * **Python**: [github.com/rotavision-ai/python-sdk](https://github.com/rotavision-ai/python-sdk) * **Node.js**: [github.com/rotavision-ai/node-sdk](https://github.com/rotavision-ai/node-sdk) * **Java**: [github.com/rotavision-ai/java-sdk](https://github.com/rotavision-ai/java-sdk) ## Community SDKs Community-maintained SDKs (not officially supported): | Language | Repository | Status | | -------- | ----------- | ------- | | Go | Coming soon | Planned | | Ruby | Coming soon | Planned | | .NET | Coming soon | Planned | Interested in maintaining a community SDK? Contact us at [developers@rotavision.com](mailto:developers@rotavision.com) # Python SDK Source: https://docs.rotavision.com/sdks/python Official Python SDK for Rotavision ## Installation ```bash theme={null} pip install rotavision ``` Requirements: Python 3.8+ ## Quick Start ```python theme={null} from rotavision import Rotavision # Initialize client client = Rotavision(api_key="rv_live_...") # Or use environment variable ROTAVISION_API_KEY client = Rotavision() # Use any product result = client.vishwas.analyze(model_id="my-model", dataset=data) ``` ## Configuration ```python theme={null} from rotavision import Rotavision client = Rotavision( api_key="rv_live_...", base_url="https://api.rotavision.com", # Custom endpoint timeout=30.0, # Request timeout (seconds) max_retries=3, # Retry attempts log_level="INFO" # Logging level ) ``` ## Products ### Vishwas - Fairness & Explainability ```python theme={null} # Analyze fairness analysis = client.vishwas.analyze( model_id="loan-model", dataset={ "features": ["age", "income", "gender"], "predictions": predictions, "actuals": actuals, "protected_attributes": ["gender"] }, metrics=["demographic_parity", "equalized_odds"] ) print(f"Score: {analysis.overall_score}") print(f"Bias: {analysis.bias_detected}") # Explain prediction explanation = client.vishwas.explain( model_id="loan-model", input_data={"age": 30, "income": 50000}, prediction=0.75, method="shap" ) print(explanation.summary) ``` ### Guardian - Monitoring ```python theme={null} # Create monitor monitor = client.guardian.create_monitor( model_id="recommendation-model", name="Prod Monitor", metrics=["prediction_drift", "latency_p99"], alerts=[ {"metric": "prediction_drift", "threshold": 0.2, "severity": "critical"} ] ) # Log inference client.guardian.log_inference( monitor_id=monitor.id, input_data=features, prediction=prediction, latency_ms=45 ) # Batch logging (more efficient) client.guardian.log_inferences( monitor_id=monitor.id, inferences=[ {"input_data": f1, "prediction": p1, "latency_ms": 40}, {"input_data": f2, "prediction": p2, "latency_ms": 42}, ] ) ``` ### Dastavez - Document AI ```python theme={null} # Extract from document result = client.dastavez.extract( document_type="aadhaar", file_url="https://storage.example.com/doc.pdf" ) print(f"Name: {result.fields['name']}") print(f"Confidence: {result.confidence}") # Or from file with open("document.pdf", "rb") as f: result = client.dastavez.extract( document_type="pan", file=f ) ``` ### Sankalp - LLM Gateway ```python theme={null} # Proxy to LLM response = client.sankalp.proxy( model="gpt-5-mini", messages=[ {"role": "user", "content": "Hello!"} ] ) print(response.choices[0].message.content) # Streaming for chunk in client.sankalp.proxy_stream( model="claude-4.5-sonnet", messages=[{"role": "user", "content": "Write a story"}] ): print(chunk.choices[0].delta.content, end="") ``` ### Orchestrate - Workflows ```python theme={null} # Run workflow execution = client.orchestrate.run_workflow( workflow_id="wf_abc123", inputs={"query": "Research AI in India"} ) # Wait for completion result = client.orchestrate.wait_for_execution(execution.id) print(result.outputs) ``` ### Gati - Fleet Intelligence ```python theme={null} # Optimize routes result = client.gati.optimize_routes( vehicles=[{"id": "v1", "capacity": 100, "start_location": {...}}], orders=[{"id": "o1", "location": {...}, "demand": 10}] ) for route in result.routes: print(f"Vehicle {route.vehicle_id}: {len(route.stops)} stops") ``` ## Async Support ```python theme={null} import asyncio from rotavision import AsyncRotavision async def main(): client = AsyncRotavision() # Async API calls result = await client.vishwas.analyze(...) # Concurrent requests analyses = await asyncio.gather( client.vishwas.analyze(model_id="model1", ...), client.vishwas.analyze(model_id="model2", ...), ) asyncio.run(main()) ``` ## Error Handling ```python theme={null} from rotavision.exceptions import ( RotavisionError, AuthenticationError, ValidationError, RateLimitError, NotFoundError ) try: result = client.vishwas.analyze(...) except AuthenticationError: print("Invalid API key") except ValidationError as e: print(f"Invalid request: {e.param}") except RateLimitError as e: print(f"Rate limited, retry after {e.retry_after}s") except RotavisionError as e: print(f"API error: {e.message}") ``` ## Logging ```python theme={null} import logging # Enable debug logging logging.basicConfig(level=logging.DEBUG) # Or configure specific logger logger = logging.getLogger("rotavision") logger.setLevel(logging.DEBUG) ```