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

# Assign an team member to an AI contact

## Overview

Assign a specific team member (agent) to a contact. This creates a direct relationship between the team member and the contact, making the team member responsible for managing that conversation.

This is essential for routing conversations to the right person, implementing assignment rules, and ensuring accountability in customer interactions.

## Use Cases

* **Manual Assignment**: Allow supervisors to manually assign conversations to specific agents
* **Load Balancing**: Programmatically distribute contacts across team members
* **Specialized Routing**: Assign contacts to agents based on skills, language, or expertise
* **Escalation Workflows**: Reassign contacts to senior agents when needed
* **Territory Management**: Assign contacts to agents based on geographic region
* **VIP Handling**: Route high-value customers to dedicated account managers

## Authentication

This endpoint requires authentication using an API key. Include your API key in the request header:

```
x-api-key: your_api_key_here
```

## Path Parameters

| Parameter      | Type          | Required | Description                                    |
| -------------- | ------------- | -------- | ---------------------------------------------- |
| `aiContactId`  | string (UUID) | Yes      | Unique identifier of the contact to assign     |
| `teamMemberId` | string (UUID) | Yes      | Unique identifier of the team member to assign |

## Query Parameters

| Parameter              | Type    | Required | Default | Description                                                     |
| ---------------------- | ------- | -------- | ------- | --------------------------------------------------------------- |
| `removeExistingAgents` | boolean | No       | false   | If true, replaces all existing assigned agents with the new one |

## Response Structure

The endpoint returns a success response confirming the assignment:

| Field     | Type    | Description                           |
| --------- | ------- | ------------------------------------- |
| `success` | boolean | Whether the assignment was successful |
| `message` | string  | Confirmation message                  |

## Example Requests

### Add Agent to Existing Assignments (Default Behavior)

```bash theme={null}
curl --request POST \
  'https://api.vambe.me/api/public/contact/1937bd2c-a13c-4365-af06-43af9a988e36/assign-team-member/228d7a0d-9072-4ca8-939b-959b75cc606a' \
  --header 'x-api-key: your_api_key_here'
```

### Replace All Agents with New Agent

```bash theme={null}
curl --request POST \
  'https://api.vambe.me/api/public/contact/1937bd2c-a13c-4365-af06-43af9a988e36/assign-team-member/228d7a0d-9072-4ca8-939b-959b75cc606a?removeExistingAgents=true' \
  --header 'x-api-key: your_api_key_here'
```

## Example Response

```json theme={null}
{
  "success": true,
  "message": "Team member assigned successfully"
}
```

## Common Use Cases

### 1. Assign Contact from Dropdown Selection

```javascript theme={null}
const assignContactToAgent = async (
  contactId,
  agentId,
  replaceExisting = false,
) => {
  // Build URL with optional query parameter
  const url = new URL(
    `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${agentId}`,
  );

  if (replaceExisting) {
    url.searchParams.append('removeExistingAgents', 'true');
  }

  const response = await fetch(url.toString(), {
    method: 'POST',
    headers: {
      'x-api-key': 'your_api_key_here',
    },
  });

  const result = await response.json();

  if (result.success) {
    console.log('Agent assigned successfully!');
    // Refresh UI or show success message
  }

  return result;
};

// Usage examples
// Add agent to existing assignments:
// assignContactToAgent('contact-uuid', 'agent-uuid', false);

// Replace all agents with new one:
// assignContactToAgent('contact-uuid', 'agent-uuid', true);
```

### 2. Round-Robin Assignment

```javascript theme={null}
const assignContactRoundRobin = async (contactId) => {
  // Get all team members
  const teamResponse = await fetch(
    'https://api.vambe.me/api/public/team-members/all',
    {
      headers: {
        'x-api-key': 'your_api_key_here',
      },
    },
  );

  const teamMembers = await teamResponse.json();

  // Simple round-robin: rotate through team members
  const assignmentIndex = await getNextAssignmentIndex(); // Your logic to track rotation
  const selectedAgent = teamMembers[assignmentIndex % teamMembers.length];

  // Assign contact
  const response = await fetch(
    `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${selectedAgent.id}`,
    {
      method: 'POST',
      headers: {
        'x-api-key': 'your_api_key_here',
      },
    },
  );

  console.log(`Assigned to ${selectedAgent.name}`);
  return await response.json();
};
```

### 3. Skill-Based Assignment

```javascript theme={null}
const assignBySkill = async (contactId, requiredSkill) => {
  // Get all team members
  const teamResponse = await fetch(
    'https://api.vambe.me/api/public/team-members/all',
    {
      headers: {
        'x-api-key': 'your_api_key_here',
      },
    },
  );

  const teamMembers = await teamResponse.json();

  // Your custom logic to map skills to team members
  const skillMap = {
    technical_support: ['228d7a0d-9072-4ca8-939b-959b75cc606a'],
    billing: ['338e8b1e-8183-5db9-a4ab-a6ab86dd717b'],
    sales: ['448f9c2f-9294-6eca-b5bc-b7bc97ee828c'],
  };

  const eligibleAgentIds = skillMap[requiredSkill] || [];
  const selectedAgentId = eligibleAgentIds[0]; // Or use more sophisticated selection

  if (!selectedAgentId) {
    throw new Error(`No agent available for skill: ${requiredSkill}`);
  }

  const response = await fetch(
    `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${selectedAgentId}`,
    {
      method: 'POST',
      headers: {
        'x-api-key': 'your_api_key_here',
      },
    },
  );

  return await response.json();
};
```

### 4. Reassign to Senior Agent (Escalation)

```javascript theme={null}
const escalateToSenior = async (contactId) => {
  const SENIOR_AGENT_ID = '228d7a0d-9072-4ca8-939b-959b-959b75cc606a'; // Your senior agent ID

  const response = await fetch(
    `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${SENIOR_AGENT_ID}`,
    {
      method: 'POST',
      headers: {
        'x-api-key': 'your_api_key_here',
      },
    },
  );

  const result = await response.json();

  if (result.success) {
    // Send notification to senior agent
    console.log('Contact escalated to senior agent');
  }

  return result;
};
```

### 4a. Replace All Agents with New Agent

```javascript theme={null}
const reassignContact = async (contactId, newAgentId) => {
  // Replace all existing agents with the new one
  const response = await fetch(
    `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${newAgentId}?removeExistingAgents=true`,
    {
      method: 'POST',
      headers: {
        'x-api-key': 'your_api_key_here',
      },
    },
  );

  const result = await response.json();

  if (result.success) {
    console.log('Contact reassigned - all previous agents removed');
  }

  return result;
};

// Usage: When you need to transfer a contact completely to a new agent
// await reassignContact('contact-uuid', 'new-agent-uuid');
```

### 5. Geographic Territory Assignment

```javascript theme={null}
const assignByTerritory = async (contactId, contactPhoneNumber) => {
  // Extract country code from phone number
  const countryCode = contactPhoneNumber.substring(0, 3); // e.g., "+56" for Chile

  // Territory mapping
  const territoryAgents = {
    '+56': '228d7a0d-9072-4ca8-939b-959b75cc606a', // Chile
    '+52': '338e8b1e-8183-5db9-a4ab-a6ab86dd717b', // Mexico
    '+57': '448f9c2f-9294-6eca-b5bc-b7bc97ee828c', // Colombia
  };

  const agentId = territoryAgents[countryCode];

  if (!agentId) {
    console.log('No agent for this territory, using default');
    return;
  }

  const response = await fetch(
    `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${agentId}`,
    {
      method: 'POST',
      headers: {
        'x-api-key': 'your_api_key_here',
      },
    },
  );

  return await response.json();
};
```

### 6. Bulk Assignment

```javascript theme={null}
const bulkAssignContacts = async (contactIds, agentId) => {
  const results = [];

  for (const contactId of contactIds) {
    try {
      const response = await fetch(
        `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${agentId}`,
        {
          method: 'POST',
          headers: {
            'x-api-key': 'your_api_key_here',
          },
        },
      );

      const result = await response.json();
      results.push({ contactId, success: result.success });
    } catch (error) {
      results.push({ contactId, success: false, error: error.message });
    }
  }

  console.log(
    `Assigned ${results.filter((r) => r.success).length} of ${contactIds.length} contacts`,
  );

  return results;
};
```

## Assignment Behavior

### What Happens When You Assign

1. **Agent Assignment**: The team member is added to the contact's assigned agents list
2. **Notification**: The assigned agent may receive a notification (depending on your settings)
3. **Visibility**: The contact appears in the agent's assigned contacts view
4. **Multiple Assignments**: A contact can have multiple assigned agents
5. **Activity Log**: The assignment is recorded in the contact's activity history

### Replacing vs Adding

* **By default**, this endpoint **adds** the team member to the contact's assigned agents
* **To replace** all assigned agents with a single agent, set the `removeExistingAgents=true` query parameter
* When `removeExistingAgents=false` (default), a contact can have multiple assigned team members working together
* When `removeExistingAgents=true`, all previous agent assignments are removed and only the new agent is assigned

## Error Responses

| Status Code | Description                                  |
| ----------- | -------------------------------------------- |
| 400         | Bad Request - Invalid contact or agent ID    |
| 401         | Unauthorized - Invalid or missing API key    |
| 404         | Not Found - Contact or team member not found |
| 500         | Internal Server Error - Something went wrong |

## Important Notes

* **Valid IDs Required**: Both `aiContactId` and `teamMemberId` must be valid UUIDs from your organization
* **Team Member Verification**: The team member must exist and be active in your organization
* **Contact Ownership**: The contact must belong to your organization
* **Idempotent**: Assigning the same agent multiple times won't create duplicates
* **No Body Required**: This is a simple POST with no request body needed
* **Immediate Effect**: The assignment takes effect immediately
* **Default Behavior**: By default, the agent is added to existing assignments (not replaced)
* **Replace Mode**: Set `removeExistingAgents=true` to remove all previous agents and assign only the new one

## Best Practices

### 1. Verify IDs Before Assignment

```javascript theme={null}
// Always validate IDs before attempting assignment
const isValidUUID = (id) => {
  const uuidRegex =
    /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return uuidRegex.test(id);
};

if (!isValidUUID(contactId) || !isValidUUID(agentId)) {
  console.error('Invalid UUID format');
  return;
}
```

### 2. Handle Errors Gracefully

```javascript theme={null}
try {
  const result = await assignContactToAgent(contactId, agentId);
  // Success handling
} catch (error) {
  if (error.status === 404) {
    console.error('Contact or agent not found');
  } else if (error.status === 401) {
    console.error('Invalid API key');
  } else {
    console.error('Assignment failed:', error);
  }
}
```

### 3. Provide User Feedback

```javascript theme={null}
const assignWithFeedback = async (contactId, agentId, agentName) => {
  // Show loading state
  showLoading('Assigning agent...');

  try {
    const response = await fetch(
      `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${agentId}`,
      {
        method: 'POST',
        headers: {
          'x-api-key': 'your_api_key_here',
        },
      },
    );

    const result = await response.json();

    if (result.success) {
      showSuccess(`Successfully assigned to ${agentName}`);
    } else {
      showError('Assignment failed');
    }
  } catch (error) {
    showError(`Error: ${error.message}`);
  } finally {
    hideLoading();
  }
};
```

## Related Endpoints

* [GET /api/public/team-members/all](/reference/team-members/get-all-team-members) - Get list of all team members to choose from
* [GET /api/public/contact/{aiContactId}/info](/reference/contact/get-info-of-an-ai-contact) - Get contact info including currently assigned agents
* [POST /api/public/contact/{aiContactId}/update-metadata](#) - Update contact metadata

## Workflow Example

Complete workflow for assignment UI:

```javascript theme={null}
// 1. Load team members
const teamMembers = await fetch(
  'https://api.vambe.me/api/public/team-members/all',
  {
    headers: { 'x-api-key': 'your_api_key_here' },
  },
).then((r) => r.json());

// 2. Display in dropdown with assignment mode toggle
// <Select options={teamMembers.map(m => ({ value: m.id, label: m.name }))} />
// <Checkbox label="Replace existing agents" onChange={setReplaceMode} />

// 3. On selection, assign
const handleAssignment = async (selectedAgentId, shouldReplace = false) => {
  const url = new URL(
    `https://api.vambe.me/api/public/contact/${contactId}/assign-team-member/${selectedAgentId}`,
  );

  if (shouldReplace) {
    url.searchParams.append('removeExistingAgents', 'true');
  }

  await fetch(url.toString(), {
    method: 'POST',
    headers: { 'x-api-key': 'your_api_key_here' },
  });

  // 4. Refresh contact info
  const updatedContact = await fetch(
    `https://api.vambe.me/api/public/contact/${contactId}/info`,
    {
      headers: { 'x-api-key': 'your_api_key_here' },
    },
  ).then((r) => r.json());

  console.log('Contact updated:', updatedContact);
};
```


## OpenAPI

````yaml post /api/public/contact/{aiContactId}/assign-team-member/{teamMemberId}
openapi: 3.0.0
info:
  title: Vambe AI API
  description: Vambe AI documentation
  version: '1.0'
  contact: {}
servers:
  - url: https://api.vambe.me
    description: Production Server
security: []
tags:
  - name: Vambe AI
    description: ''
paths:
  /api/public/contact/{aiContactId}/assign-team-member/{teamMemberId}:
    post:
      tags:
        - Contact
      summary: Assign an team member to an AI contact
      operationId: PublicAiContactController_assignAgentToAiContact
      parameters:
        - name: x-api-key
          in: header
          description: API key required to authorize the request
          required: true
          schema:
            type: string
        - name: aiContactId
          required: true
          in: path
          description: ID of the AI contact
          schema:
            type: string
        - name: teamMemberId
          required: true
          in: path
          description: ID of the team member
          schema:
            type: string
        - name: removeExistingAgents
          required: false
          in: query
          description: If true, it will replace the existing agents with the new one
          schema:
            type: boolean
      responses:
        '200':
          description: Team member assigned successfully.
        '404':
          description: AI contact or team member not found.

````