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

# Upload a raw document to a given assistant

> Upload a raw document to a given assistant.

## Overview

Upload a document to your AI assistant's knowledge base. This endpoint uploads the document to Ragie (AI knowledge platform), saves it to your database, and optionally links it to a specific AI assistant through folder association.

Perfect for programmatically building and maintaining your AI assistant's knowledge base with custom content.

## Use Cases

* **Knowledge Base Building**: Programmatically add content to AI assistants
* **Content Sync**: Import content from external systems (CMS, wikis, etc.)
* **Bulk Upload**: Upload multiple documents via API
* **Dynamic Content**: Add generated or user-submitted content
* **Documentation Updates**: Keep AI knowledge up-to-date with latest docs
* **Multi-language Content**: Upload translations and localized content

## Authentication

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

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

## Request Body

| Field         | Type          | Required | Description                                        |
| ------------- | ------------- | -------- | -------------------------------------------------- |
| `content`     | string        | Yes      | The actual content/text of the document            |
| `fileName`    | string        | Yes      | Name of the document file                          |
| `externalId`  | string        | Yes      | Your unique identifier for tracking this document  |
| `folderId`    | string (UUID) | Yes      | Folder ID where document will be stored            |
| `assistantId` | string (UUID) | No       | Optional assistant ID to link folder with          |
| `icon`        | string        | No       | Optional emoji/icon for the document (default: 📄) |

<Note>
  **External ID**: Use a unique identifier from your system to track documents.
  This is used for updates and deletions.
</Note>

## What Happens When You Upload

1. **Upload to Ragie**: Document content is uploaded to Ragie AI platform
2. **Save to Database**: Document metadata saved with folder association
3. **Link to Assistant**: If `assistantId` provided, folder is linked to that assistant
4. **AI Processing**: Ragie processes the document for AI retrieval

## Response Structure

| Field           | Type   | Description                     |
| --------------- | ------ | ------------------------------- |
| `ragieDocument` | object | Document info from Ragie API    |
| `savedDocument` | object | Document info saved in database |

### Ragie Document Object

| Field         | Type          | Description                       |
| ------------- | ------------- | --------------------------------- |
| `id`          | string (UUID) | Ragie document ID                 |
| `name`        | string        | Document name                     |
| `status`      | string        | Processing status                 |
| `chunk_count` | number        | Number of chunks for AI retrieval |
| `external_id` | string        | Your external ID                  |
| `created_at`  | string (ISO)  | Creation timestamp                |

### Saved Document Object

| Field              | Type          | Description          |
| ------------------ | ------------- | -------------------- |
| `id`               | string (UUID) | Database document ID |
| `name`             | string        | Document name        |
| `icon`             | string        | Document icon        |
| `parent_folder_id` | string (UUID) | Associated folder ID |
| `content`          | string        | Document content     |
| `client_id`        | string (UUID) | Your organization ID |

## Example Request

```bash theme={null}
curl --request POST \
  'https://api.vambe.me/api/documents/assistant/raw' \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: your_api_key_here' \
  --data-raw '{
    "content": "# Product FAQ\n\nQ: How to reset password?\nA: Go to settings...",
    "fileName": "product-faq.md",
    "externalId": "ext-product-faq-001",
    "folderId": "550e8400-e29b-41d4-a716-446655440000",
    "assistantId": "660e8400-e29b-41d4-a716-446655440001",
    "icon": "❓"
  }'
```

## Example Response

```json theme={null}
{
  "ragieDocument": {
    "id": "ragie-doc-12345",
    "name": "product-faq.md",
    "status": "initialized",
    "chunk_count": 0,
    "external_id": "ext-product-faq-001",
    "created_at": "2024-09-30T10:00:00.000Z",
    "updated_at": "2024-09-30T10:00:00.000Z",
    "metadata": {
      "clientId": "660e8400-e29b-41d4-a716-446655440001",
      "folderId": "550e8400-e29b-41d4-a716-446655440000",
      "source_type": "vambe"
    }
  },
  "savedDocument": {
    "id": "ragie-doc-12345",
    "name": "product-faq.md",
    "icon": "❓",
    "parent_folder_id": "550e8400-e29b-41d4-a716-446655440000",
    "content": "# Product FAQ\n\nQ: How to reset password?\nA: Go to settings...",
    "client_id": "660e8400-e29b-41d4-a716-446655440001",
    "src_type": "vambe",
    "is_public": false,
    "created_at": "2024-09-30T10:00:00.000Z",
    "updated_at": "2024-09-30T10:00:00.000Z"
  }
}
```

## Common Use Cases

### 1. Upload FAQ Document

```javascript theme={null}
const uploadFAQ = async (folderId) => {
  const faqContent = `
# Frequently Asked Questions

## Billing
Q: How do I update my payment method?
A: Go to Settings > Billing > Payment Methods

Q: What payment methods do you accept?
A: We accept credit cards, PayPal, and wire transfer

## Account
Q: How do I reset my password?
A: Click "Forgot Password" on the login page
  `.trim();

  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: faqContent,
        fileName: 'billing-faq.md',
        externalId: `faq-${Date.now()}`,
        folderId: folderId,
        icon: '❓',
      }),
    },
  );

  const result = await response.json();
  console.log('FAQ uploaded:', result.savedDocument.name);

  return result;
};
```

### 2. Bulk Upload Documents

```javascript theme={null}
const bulkUploadDocuments = async (folderId, documents) => {
  const results = [];

  for (const doc of documents) {
    try {
      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: doc.content,
            fileName: doc.fileName,
            externalId: doc.id,
            folderId: folderId,
            icon: doc.icon || '📄',
          }),
        },
      );

      const result = await response.json();
      results.push({
        success: true,
        fileName: doc.fileName,
        id: result.savedDocument.id,
      });

      console.log(`✅ Uploaded: ${doc.fileName}`);
    } catch (error) {
      results.push({
        success: false,
        fileName: doc.fileName,
        error: error.message,
      });
      console.error(`❌ Failed: ${doc.fileName}`);
    }

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

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

  return results;
};
```

### 3. Upload and Link to Assistant

```javascript theme={null}
const uploadAndLinkToAssistant = async (assistantId, folderId, docData) => {
  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: docData.content,
        fileName: docData.fileName,
        externalId: docData.externalId,
        folderId: folderId,
        assistantId: assistantId, // Links folder to assistant
        icon: '🤖',
      }),
    },
  );

  const result = await response.json();

  console.log('Document uploaded and linked to assistant');
  console.log('Ragie ID:', result.ragieDocument.id);
  console.log('DB ID:', result.savedDocument.id);

  return result;
};
```

### 4. Sync from External CMS

```javascript theme={null}
const syncFromCMS = async (cmsArticles, folderId) => {
  const syncResults = [];

  for (const article of cmsArticles) {
    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: article.content,
          fileName: article.title,
          externalId: `cms-${article.id}`, // Use CMS ID as external ID
          folderId: folderId,
          icon: article.category === 'guide' ? '📖' : '📄',
        }),
      },
    );

    const result = await response.json();
    syncResults.push({
      cmsId: article.id,
      ragieId: result.ragieDocument.id,
      title: article.title,
    });
  }

  console.log(`Synced ${syncResults.length} articles from CMS`);

  return syncResults;
};
```

## Content Format

The `content` field accepts plain text or markdown:

**Plain Text**:

```
Product X is our flagship solution...
```

**Markdown**:

```markdown theme={null}
# Product X Overview

## Features

- Feature 1
- Feature 2

## Pricing

Starting at $99/month
```

**HTML** (converted to text):

```
<h1>Product Guide</h1>
<p>This is our product...</p>
```

The AI will process any format and make it searchable.

## External ID

The `externalId` is YOUR identifier for the document:

* **Must be unique** within your organization
* Used for **updates and deletions**
* Can be any string (e.g., `"doc-123"`, `"cms-article-456"`)
* Helps you **track** which documents you've uploaded

## Error Responses

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

## Important Notes

* **Required Subscription**: This endpoint requires an active subscription
* **Ragie Processing**: Documents are processed asynchronously by Ragie
* **External ID Tracking**: Use consistent external IDs for updates/deletes
* **Folder Required**: Must specify a valid folder ID
* **Content Limit**: Very large documents may be rejected (keep under 1MB)
* **Assistant Linking**: Folder linked to assistant, not individual document

## Related Endpoints

* [GET /api/documents/assistant/folders](/reference/assistant/get-folders) - List available folders
* [POST /api/documents/assistant/folders](/reference/assistant/create-folder) - Create a folder first
* [DELETE /api/documents/assistant/{externalId}](/reference/assistant/delete-document) - Delete uploaded document

## Best Practices

### 1. Use Descriptive External IDs

```javascript theme={null}
// Good: Clear, trackable IDs
externalId: 'product-guide-v2';
externalId: 'faq-billing-2024-09';
externalId: `cms-${article.id}`;

// Avoid: Generic or unclear IDs
externalId: 'doc1';
externalId: 'temp';
```

### 2. Organize with Icons

```javascript theme={null}
const iconsByType = {
  faq: '❓',
  guide: '📖',
  policy: '📋',
  api: '🔌',
  tutorial: '🎓',
};

const icon = iconsByType[documentType] || '📄';
```

### 3. Handle Errors

```javascript theme={null}
try {
  const result = await uploadDocument(data);
  console.log('✅ Upload successful');
} catch (error) {
  if (error.status === 404) {
    console.error('Folder not found - create it first');
  } else if (error.status === 400) {
    console.error('Invalid data:', error.message);
  } else {
    console.error('Upload failed:', error);
  }
}
```


## OpenAPI

````yaml post /api/documents/assistant/raw
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/raw:
    post:
      tags:
        - Assistant Documents
      summary: Upload a raw document to a given assistant
      description: Upload a raw document to a given assistant.
      operationId: PublicRagieController_createRagieRaw
      parameters:
        - name: x-api-key
          in: header
          description: API key needed to authorize the request
          required: true
          schema:
            type: string
      requestBody:
        required: true
        description: >-
          The content of the document, the name of the file, the external id,
          folder id, optional assistant id and icon.
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateRawDocumentDto'
      responses:
        '201':
          description: Document created successfully.
        '400':
          description: Bad request.
        '401':
          description: Unauthorized.
components:
  schemas:
    CreateRawDocumentDto:
      type: object
      properties:
        content:
          type: string
          minLength: 1
        fileName:
          type: string
          minLength: 1
        externalId:
          type: string
          minLength: 1
        assistantId:
          type: string
          format: uuid
          pattern: >-
            ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$
        folderId:
          type: string
          format: uuid
          pattern: >-
            ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$
        icon:
          type: string
          maxLength: 50
      required:
        - content
        - fileName
        - externalId
        - folderId

````