> ## 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.

# Delete a document from a given assistant

> Delete a document from a given assistant.

## Overview

Delete a document from your AI assistant's knowledge base using its external ID. This removes the document from both Ragie (AI platform) and your database, ensuring your assistant no longer uses this content.

Use this endpoint to remove outdated, incorrect, or sensitive information from your AI's knowledge.

## Use Cases

* **Content Updates**: Remove old versions before uploading new ones
* **Data Cleanup**: Remove outdated or deprecated documentation
* **Compliance**: Delete sensitive information that shouldn't be in AI knowledge
* **Content Management**: Remove documents that are no longer relevant
* **Error Correction**: Delete incorrectly uploaded documents
* **Bulk Cleanup**: Programmatically remove multiple outdated documents

## 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                                 |
| ------------ | ------ | -------- | ------------------------------------------- |
| `externalId` | string | Yes      | The external ID you assigned when uploading |

<Note>
  **External ID**: This is the same `externalId` you provided when uploading the
  document with `POST /api/documents/assistant/raw`.
</Note>

## Response Structure

| Field    | Type   | Description                       |
| -------- | ------ | --------------------------------- |
| `status` | string | Deletion status (e.g., "deleted") |

## Example Request

```bash theme={null}
curl --request DELETE \
  'https://api.vambe.me/api/documents/assistant/ext-product-faq-001' \
  --header 'x-api-key: your_api_key_here'
```

## Example Response

```json theme={null}
{
  "status": "deleted"
}
```

## Common Use Cases

### 1. Delete Single Document

```javascript theme={null}
const deleteDocument = async (externalId) => {
  const response = await fetch(
    `https://api.vambe.me/api/documents/assistant/${externalId}`,
    {
      method: 'DELETE',
      headers: {
        'x-api-key': 'your_api_key_here',
      },
    },
  );

  const result = await response.json();

  if (result.status === 'deleted') {
    console.log(`✅ Document ${externalId} deleted successfully`);
  }

  return result;
};
```

### 2. Update Document (Delete + Upload)

```javascript theme={null}
const updateDocument = async (externalId, newContent, folderId) => {
  // 1. Delete old version
  await fetch(`https://api.vambe.me/api/documents/assistant/${externalId}`, {
    method: 'DELETE',
    headers: {
      'x-api-key': 'your_api_key_here',
    },
  });

  console.log('Old version deleted');

  // 2. Upload new version with same external ID
  const response = await fetch(
    'https://api.vambe.me/api/documents/assistant/raw',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'your_api_key_here',
      },
      body: JSON.stringify({
        content: newContent,
        fileName: 'updated-document.md',
        externalId: externalId, // Same ID for tracking
        folderId: folderId,
        icon: '📄',
      }),
    },
  );

  const result = await response.json();
  console.log('New version uploaded');

  return result;
};
```

### 3. Bulk Delete Documents

```javascript theme={null}
const bulkDeleteDocuments = async (externalIds) => {
  const results = [];

  for (const externalId of externalIds) {
    try {
      const response = await fetch(
        `https://api.vambe.me/api/documents/assistant/${externalId}`,
        {
          method: 'DELETE',
          headers: {
            'x-api-key': 'your_api_key_here',
          },
        },
      );

      const result = await response.json();
      results.push({ externalId, success: true, status: result.status });

      console.log(`✅ Deleted: ${externalId}`);
    } catch (error) {
      results.push({ externalId, success: false, error: error.message });
      console.error(`❌ Failed to delete: ${externalId}`);
    }

    // Small delay to avoid rate limiting
    await new Promise((resolve) => setTimeout(resolve, 100));
  }

  console.log(
    `Deleted ${results.filter((r) => r.success).length} of ${externalIds.length} documents`,
  );

  return results;
};
```

### 4. Clean Up Old Documents

```javascript theme={null}
const cleanupOldDocuments = async (olderThanDays = 30) => {
  // Get all folders with documents
  const foldersResponse = await fetch(
    'https://api.vambe.me/api/documents/assistant/folders',
    {
      headers: {
        'x-api-key': 'your_api_key_here',
      },
    },
  );

  const folders = await foldersResponse.json();

  // Find documents to delete (this would need metadata about age)
  // For example, if your external IDs include timestamps
  const oldDocumentIds = [];

  const cutoffDate = new Date();
  cutoffDate.setDate(cutoffDate.getDate() - olderThanDays);

  // Your logic to identify old documents
  // e.g., external IDs with dates: 'doc-2024-01-15-product'

  // Delete old documents
  for (const externalId of oldDocumentIds) {
    await deleteDocument(externalId);
  }

  console.log(`Cleaned up ${oldDocumentIds.length} old documents`);
};
```

### 5. Safe Delete with Confirmation

```javascript theme={null}
const safeDeleteDocument = async (externalId) => {
  try {
    // Optional: Get folder info to show what's being deleted
    const foldersResponse = await fetch(
      'https://api.vambe.me/api/documents/assistant/folders',
      {
        headers: { 'x-api-key': 'your_api_key_here' },
      },
    );

    const folders = await foldersResponse.json();

    // Find the document in folders (for confirmation)
    let foundDoc = null;
    for (const folder of folders) {
      foundDoc = folder.documents.find((d) => d.id === externalId);
      if (foundDoc) break;
    }

    if (foundDoc) {
      console.log(`About to delete: ${foundDoc.name}`);
    }

    // Delete
    const response = await fetch(
      `https://api.vambe.me/api/documents/assistant/${externalId}`,
      {
        method: 'DELETE',
        headers: {
          'x-api-key': 'your_api_key_here',
        },
      },
    );

    const result = await response.json();
    console.log('✅ Document deleted');

    return result;
  } catch (error) {
    console.error('Delete failed:', error);
    throw error;
  }
};
```

## What Gets Deleted

When you delete a document:

1. ✅ **Ragie Document**: Removed from AI knowledge platform
2. ✅ **Database Record**: Removed from knowledge\_base\_document table
3. ✅ **AI Knowledge**: Assistant will no longer use this content
4. ❌ **Folder**: The containing folder is NOT deleted
5. ❌ **Assistant Link**: Assistant-folder link remains (only document removed)

## Error Responses

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

## Important Notes

* **Uses External ID**: Delete by YOUR external ID, not Ragie's internal ID
* **Permanent**: Deletion is permanent and cannot be undone
* **Both Systems**: Deletes from both Ragie and your database
* **Folder Intact**: Only document is deleted, folder remains
* **Immediate Effect**: AI will stop using this content immediately
* **Not Found OK**: Deleting non-existent document returns 404

## External ID Format

Your external ID can be any string:

* ✅ `"product-guide-v2"`
* ✅ `"cms-article-12345"`
* ✅ `"faq-${Date.now()}"`
* ✅ `"user-manual-en"`

Make sure to track these IDs in your system!

## Related Endpoints

* [POST /api/documents/assistant/raw](/reference/assistant/upload-document) - Upload a new document
* [GET /api/documents/assistant/folders](/reference/assistant/get-folders) - List folders and documents
* [POST /api/documents/assistant/folders](/reference/assistant/create-folder) - Create folders

## Best Practices

### 1. Track External IDs

```javascript theme={null}
// Keep a mapping of your documents
const documentRegistry = {
  'product-guide-v1': { uploaded: '2024-01-15', active: false },
  'product-guide-v2': { uploaded: '2024-09-30', active: true },
};

// Delete old version
await deleteDocument('product-guide-v1');
```

### 2. Confirm Before Delete

```javascript theme={null}
const confirmAndDelete = async (externalId, documentName) => {
  const confirmed = confirm(`Delete "${documentName}"?`);

  if (confirmed) {
    return await deleteDocument(externalId);
  }

  console.log('Deletion cancelled');
  return null;
};
```

### 3. Handle Not Found Gracefully

```javascript theme={null}
const safeDelete = async (externalId) => {
  try {
    return await deleteDocument(externalId);
  } catch (error) {
    if (error.status === 404) {
      console.log('Document already deleted or never existed');
      return { status: 'already_deleted' };
    }
    throw error;
  }
};
```


## OpenAPI

````yaml delete /api/documents/assistant/{externalId}
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/documents/assistant/{externalId}:
    delete:
      tags:
        - Assistant Documents
      summary: Delete a document from a given assistant
      description: Delete a document from a given assistant.
      operationId: PublicRagieController_deleteRagieFile
      parameters:
        - name: externalId
          required: true
          in: path
          description: The external id of the document
          schema:
            type: string
        - name: x-api-key
          in: header
          description: API key needed to authorize the request
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Document deleted successfully.
        '400':
          description: Bad request.
        '401':
          description: Unauthorized.

````