> ## Documentation Index
> Fetch the complete documentation index at: https://docs.parcha.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Run a KYB Agent

> Learn how to run a Know Your Business (KYB) agent with step-by-step instructions

This guide explains how to run a Know Your Business (KYB) agent using Parcha's API. The KYB agent helps verify business information and perform various compliance checks.

## Prerequisites

Before you can run a KYB agent, you need:

1. **API Key**: A unique API key for authentication. See [Authentication](/authentication) for how to generate one.
2. **Agent Key**: Your KYB agent key from the Parcha dashboard. This is unique to your organization and agent configuration.

<Warning>
  **Important**: You must use your own agent key, not a default or public agent key. Your agent key can be found in the Parcha dashboard under your agent's settings, or in the "Test API Integration" dialog.
</Warning>

<Warning>
  Never share your API key or agent key. Keep them secure and use environment variables or secure secret management systems to store them.
</Warning>

## Overview

The KYB process involves several steps:

1. Prepare the business schema
2. Start the KYB agent job
3. Monitor job status and results
4. Handle job completion

```mermaid theme={null}
sequenceDiagram
    participant Client
    participant API
    participant KYB Agent
    participant Check Services

    Client->>API: 1. Start KYB Agent Job
    API->>KYB Agent: 2. Initialize Job
    KYB Agent->>API: 3. Return Job ID

    Note over KYB Agent: 4. Run Required Checks
    
    loop For each check
        KYB Agent->>Check Services: 5. Run Check
        Check Services-->>KYB Agent: 6. Check Results
        KYB Agent->>API: 7. Update Job Status
    end

    KYB Agent->>API: 8. Mark Job Complete
    API-->>Client: 9. Job Complete
```

## Step-by-Step Guide

### 1. Prepare the Business Schema

First, prepare your business schema following the [Business Schema documentation](/schemas/business-schema). The schema should include:

* Basic business information
* Required documents
* Associated individuals and entities

<Note>
  Make sure to include all required fields for the checks you plan to run. See the [Check Requirements](/schemas/business-schema#check-requirements) table for details.
</Note>

### 2. Start the KYB Agent Job

Use the `/startKYBAgentJob` endpoint to start a new KYB job:

```bash theme={null}
curl -X POST 'https://api.parcha.ai/api/v1/startKYBAgentJob' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
  "agent_key": "your-kyb-agent-key",
  "kyb_schema": {
    "id": "example-business-case",
    "self_attested_data": {
      "business_name": "Example Corp",
      "website": "https://example.com"
    }
  },
  "webhook_url": "https://your-webhook-url.com",
  "check_ids": ["kyb.basic_business_profile_check", "kyb.adverse_media_check"]
}'
```

The response will include:

* `job_id`: Unique identifier for the job
* `status`: Initial job status
* `created_at`: Timestamp of job creation
* `message`: Status message

### 3. Monitor Job Status and Results

You can monitor the job status and results in two ways:

#### Option 1: Get Job by ID

Use the `/getJobById` endpoint to get detailed information about a specific job:

```bash theme={null}
curl -X GET 'https://api.parcha.ai/api/v1/getJobById?job_id=YOUR_JOB_ID&include_check_results=true' \
-H 'Authorization: Bearer YOUR_API_KEY'
```

This endpoint provides:

* Job status and progress (Possible statuses include PENDING, RUNNING, COMPLETE, FAILED, RETRIED)
* Check results
* Status messages
* Input payload
* Timestamps

<Note>
  If a job status is `RETRIED`, the response will include a `new_job_id` field. You should use this new ID to call `/getJobById` again to get the status of the current job. The new job will also contain an `original_job_id` field, pointing back to the job that was retried.
</Note>

#### Option 2: Get Jobs by Case ID

Use the `/getJobsByCaseId` endpoint to get all jobs associated with a case:

```bash theme={null}
curl -X GET 'https://api.parcha.ai/api/v1/getJobsByCaseId?case_id=YOUR_CASE_ID&agent_key=your-kyb-agent-key&include_check_results=true' \
-H 'Authorization: Bearer YOUR_API_KEY'
```

This endpoint provides:

* List of all jobs for the case
* Job statuses
* Check results
* Status messages

### 4. Handle Job Completion

When a job completes, you can:

1. Review the check results in the response
2. Process any required follow-up actions
3. Update your application state based on the results

## Common Check Types

### Compliance Checks

* Basic Business Profile Check
* Adverse Media Screening
* Web Presence Check
* High Risk Country Check
* Business Reviews Check
* Industry Activity Check

### Document Verifications

* Business Ownership Document Verification
* Incorporation Document Verification
* Proof of Address Document Verification
* EIN Document Verification
* Source of Funds Document Verification

## Best Practices

1. **Schema Preparation**
   * Include all required fields for your checks
   * Validate the schema before submission
   * Ensure document URLs are accessible

2. **Error Handling**
   * Implement proper error handling for API responses
   * Monitor for validation errors
   * Handle rate limiting appropriately

3. **Status Monitoring**
   * Use webhooks for real-time updates
   * Regularly check job status
   * Log all check results

4. **Security**
   * Keep API keys secure
   * Use HTTPS for all requests
   * Follow least privilege principle

## Example Workflow

Here's a complete example of running a KYB agent:

```python theme={null}
import requests
import time

def run_kyb_workflow(api_key, agent_key, business_schema):
    # 1. Start KYB Job
    response = requests.post(
        'https://api.parcha.ai/api/v1/startKYBAgentJob',
        headers={'Authorization': f'Bearer {api_key}'},
        json={
            'agent_key': agent_key,  # Use your own agent key from the Parcha dashboard
            'kyb_schema': business_schema,
            'webhook_url': 'https://your-webhook-url.com'
        }
    )
    job_id = response.json()['job_id']
    
    # 2. Monitor Job Status
    while True:
        current_job_id = job_id # Initialize current_job_id
        response = requests.get(
            f'https://api.parcha.ai/api/v1/getJobById?job_id={current_job_id}&include_check_results=true',
            headers={'Authorization': f'Bearer {api_key}'}
        )
        job_data = response.json()
        
        if job_data['status'] == 'complete':
            return job_data
        elif job_data['status'] == 'error':
            raise Exception(f'Job {current_job_id} failed')
        elif job_data['status'] == 'RETRIED':
            new_job_id = job_data.get('new_job_id')
            if not new_job_id:
                raise Exception(f'Job {current_job_id} has status RETRIED but no new_job_id found.')
            print(f"Job {current_job_id} was retried. New job ID: {new_job_id}. Continuing with new job.")
            job_id = new_job_id # Update job_id to the new one for the next loop iteration
            # Continue to the next iteration to fetch the new job status
            continue 
            
        time.sleep(5)  # Wait before next check
```

<Card title="API Reference" icon="book-open" href="/api-reference">
  View the complete API documentation for all endpoints and features.
</Card>
